query
stringlengths 9
9.05k
| document
stringlengths 10
222k
| metadata
dict | negatives
sequencelengths 30
30
| negative_scores
sequencelengths 30
30
| document_score
stringlengths 4
10
| document_rank
stringclasses 2
values |
---|---|---|---|---|---|---|
Checks if a value is between two boundary values | def between(check:float, boundary_1:float, boundary_2:float)->bool:
if boundary_1 > boundary_2:
boundary_1, boundary_2 = boundary_2, boundary_1
return boundary_1 <= check and check <= boundary_2 | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_if_between(a, b, test_val):\n if a < b:\n return a <= test_val <= b\n else:\n return b <= test_val <= a",
"def within_value(v1, v2):\n percentage = 0.1\n error_allowed = percentage * v1\n high = v1 + error_allowed\n low = v1 - error_allowed\n\n return low <= v2 <= high",
"def between(x, val1, val2):\n\treturn max(val1, val2) > x > min(val1, val2)",
"def _inside_bounds(A, B):\n for axis in 'xyz':\n minA, maxA = axis_bounds(A, axis)\n minB, maxB = axis_bounds(B, axis)\n if (minA <= minB) or (maxA >= maxB):\n return False\n\n return True",
"def check_in_range(value, lim_1, lim_2):\n lo_lim = min(lim_1, lim_2)\n hi_lim = max(lim_1, lim_2)\n \n if (abs(value) > abs(lo_lim)) and (abs(value) < abs(hi_lim)):\n return True\n else:\n return False",
"def inrange ( a , x , b ) :\n _a = float(a)\n _b = float(b)\n _x = float(x)\n return ( _a <= _x or isequal ( _a , _x ) ) and ( _x <= _b or isequal ( _x , _b ) )",
"def is_in_interval(self, low, high, value):\n return low <= value and value <= high",
"def _in_interval(value, low, up):\n if low <= value <= up:\n return True\n else:\n return False",
"def is_between(value, start, end, including_start=False, including_end=False):\n if not including_start and not including_end: # not include both start and end\n if (start < value < end):\n return True\n elif (start > end) and (start < value <= (2**m - 1) or 0 <= value < end):\n return True\n elif (start == end) and (value != start):\n return True\n return False\n elif not including_start and including_end: # include end but not the start\n if value == end:\n return True\n elif (start < value <= end):\n return True\n elif (start > end) and ((start < value <= (2**m - 1)) or (0 <= value <= end)):\n return True\n elif (start == end) and (value != start):\n return True\n return False\n elif including_start and not including_end: # include start but not the end\n if value == start:\n return True\n elif (start <= value < end):\n return True\n elif (start > end) and (start <= value <= (2**m - 1) or 0 <= value < end):\n return True\n elif (start == end) and (value != end):\n return False\n return False\n else: # include both start and end\n if (start <= value <= end):\n return True\n elif (start > end) and (start <= value <= (2**m - 1) or 0 <= value <= end):\n return True\n elif start == end:\n return True\n return False",
"def _in_bounds(self, x, y):\r\n return 0 <= x < 8 and 0 <= y < 8",
"def _range_contains(self, a, b):\n\t\treturn b[0] >= a[0] and b[-1] <= a[-1]",
"def validate(self, value: Union[int, float]) -> bool:\n if self.left_boundary['open']:\n if self.left_boundary['value'] >= value:\n return False\n else:\n if self.left_boundary['value'] > value:\n return False\n if self.right_boundary['open']:\n if value >= self.right_boundary['value']:\n return False\n else:\n if value > self.right_boundary['value']:\n return False\n return True",
"def boundary_check(limits : tuple, coords : tuple) -> bool:\n xl,xh,yl,yh = limits\n x,y = coords\n bound_x = xl <= x and x < xh\n bound_y = yl <= y and y < yh\n return bound_x and bound_y",
"def g_in_bounds(x, lo, hi):\n\n return (x >= lo) and (x <= hi)",
"def check_out_range(value, lim_1, lim_2):\n lo_lim = min(lim_1, lim_2)\n hi_lim = max(lim_1, lim_2)\n \n if (abs(value) > abs(hi_lim)) or (abs(value) < abs(lo_lim)):\n return True\n else:\n return False",
"def is_between(a, b, c):\n a = round(a, 4)\n b = round(b, 4)\n c = round(c, 4)\n if (a < b) & (a > c):\n return True\n if (a > b) & (a < c):\n return True\n return False",
"def in_range(x, a, b):\n return (x >= a and x <= b) or (x <= a and x >= b)",
"def in_interval(value: float, s: float, e: float) -> bool:\n lower = value >= s\n upper = value <= e\n return lower and upper",
"def is_bound(pos1, el1, pos2, el2):\n threshold = 0.1\n if el1 == 'H' or el2 == 'H':\n threshold = 0.2\n if np.linalg.norm(np.array(pos1) - np.array(pos2)) < covalence_radius[el1] + covalence_radius[el2] + threshold:\n return True\n return False",
"def isInRange(val, minv, maxv):\n\treturn val >= minv and val <= maxv",
"def in_bounds(self, x, y):\n return x >= 0 and x < 8 and y >= 0 and y < 8",
"def check_interval_bounds(begin, end):\n if begin.get_midpoint() >= end.get_midpoint():\n return False\n\n if begin.get_radius() is not None and end.get_radius() is not None:\n if begin.get_midpoint() - begin.get_radius() > \\\n end.get_midpoint() - end.get_radius():\n return False\n\n return True",
"def isGE(self, a : float, b : float) -> bool:\n return (a >= b - self.tol * max(abs(a), abs(b), 1.0)) #and (a >= b - 0.1)",
"def in_range(x, y):\n if (x < 0 or x > width or y < 0 or y > length):\n return False\n else:\n return True",
"def assert_between(value, minval, maxval):\n assert_greater_equal(value, minval)\n assert_less_equal(value, maxval)",
"def isWithinGT(self, a, b):\n return ((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5 < self.thresh",
"def in_range(cls, lhs, rhs):\n return rhs[0] <= lhs <= rhs[1]",
"def assertWithin(self, value, lower, upper):\n if value < lower:\n self.fail('%s is below lower bound %s' (value, lower))\n if value > upper:\n self.fail('%s is above upper bound %s' (value, upper))",
"def overlap(range1, range2):\n if range1[0] <= range2[1] and range2[0] <= range1[1]:\n return True\n return False",
"def point_in_rectangle(point: Vector, rect_min: Vector, rect_max: Vector) -> bool:\n return rect_min[0] <= point[0] <= rect_max[0] and rect_min[1] <= point[1] <= rect_max[1]"
] | [
"0.753235",
"0.74662626",
"0.74073505",
"0.74048406",
"0.73218316",
"0.72808284",
"0.72025293",
"0.7180609",
"0.717863",
"0.7134316",
"0.71139634",
"0.7110848",
"0.7095863",
"0.70765793",
"0.7074509",
"0.7058017",
"0.70498204",
"0.702181",
"0.7013493",
"0.7001683",
"0.69881356",
"0.69732815",
"0.69651854",
"0.6851339",
"0.6844334",
"0.6778485",
"0.67741734",
"0.6751971",
"0.67367566",
"0.6718762"
] | 0.82189065 | 0 |
Checks if a point is within the rectangle with edge as one of the diagonals. | def near_segment(point:tuple, edge:tuple)->bool:
return between(point[0], edge[0][0], edge[1][0]) and between(point[1], edge[0][1], edge[1][1]) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def inside(point, rectangle):\n\n ll = rectangle.getP1() # assume p1 is ll (lower left)\n ur = rectangle.getP2() # assume p2 is ur (upper right)\n\n return ll.getX() < point.getX() < ur.getX() and ll.getY() < point.getY() < ur.getY()",
"def in_square(self, point):\n size = self.size\n centre = self.centre\n # Find the upper and lower bounds for the square in-terms of x and y\n lower_x, upper_x = centre.x - size / 2, centre.x + size / 2\n lower_y, upper_y = centre.y - size / 2, centre.y + size / 2\n # Equals with lower bounds only\n return (lower_x <= point.x < upper_x) and (lower_y < point.y <= upper_y)",
"def point_in_rectangle(point: Vector, rect_min: Vector, rect_max: Vector) -> bool:\n return rect_min[0] <= point[0] <= rect_max[0] and rect_min[1] <= point[1] <= rect_max[1]",
"def inside(point, rectangle):\r\n\r\n ll = rectangle.getP1() # assume p1 is ll (lower left)\r\n ur = rectangle.getP2() # assume p2 is ur (upper right)\r\n\r\n return (ll.getX() < point.getX() < ur.getX() \\\r\n and ll.getY() < point.getY() < ur.getY())",
"def is_point_in(self, point):\n return (self.upperleft[0] <= point[0] <= self.upperright[0] and self.upperleft[1] <= point[1] <= self.bottomleft[1])",
"def is_point_in(self, point):\n return (self.upperleft[0] <= point[0] <= self.upperright[0] and self.upperleft[1] <= point[1] <= self.bottomleft[1])",
"def check_diagonals(self):\n\t\tdiags = [[(0,0), (1,1), (2,2)], [(0,2), (1,1), (2,0)]]\n\n\t\tfor diag in diags:\n\t\t\tpts = 0\n\t\t\tfor loc in diag:\n\t\t\t\tif self.board[loc[0]][loc[1]] == self.marker:\n\t\t\t\t\tpts+=1\n\t\t\tif pts == 3:\n\t\t\t\tprint('WE WON')\n\t\t\t\treturn True",
"def isInside(point_x, point_y, area_left, area_top, area_width, area_height):\n return (area_left <= point_x < area_left + area_width) and (area_top <= point_y < area_top + area_height)",
"def contains(self, point : Point):\n return ( self.corner.x <= point.x <= (self.corner.x + self.width)\n and self.corner.y <= point.y <= (self.corner.y + self.height))",
"def in_rectangle(x, y):\n return ((self.min_x <= x <= self.max_x) and\n (self.min_y <= y <= self.max_y))",
"def in_rectangle(rect, point):\n if point[0] < rect[0]:\n return False\n\n elif point[1] < rect[1]:\n return False\n\n elif point[0] > rect[0] + rect[2]:\n return False\n\n elif point[1] > rect[1] + rect[3]:\n return False\n\n return True",
"def valid_ray(self, row, col):\n # if row nor col is at an edge space, returns False\n if row != 0 and row != 9 and col != 0 and col != 9:\n return False\n # ensures no corner spaces have been selected\n if row == 0 or row == 9:\n if col > 8 or col < 1:\n return False\n if col == 0 or col == 9:\n if row > 8 or row < 1:\n return False\n return True",
"def coordinates_within_board(n: int, x: int, y: int) -> bool:\n\n return x < n and y < n and x >= 0 and y >= 0",
"def check_edges(self):\n if self.rect.right >= self.screen_rect.right or self.rect.left <= 0:\n return True",
"def contains(self, pt):\n x,y = pt.as_tuple()\n return (self.left <= x <= self.right and\n self.top <= y <= self.bottom)",
"def within(point: tuple, box: tuple) -> bool:\r\n \r\n return box[0] < point[0] < box[2] and box[1] < point[1] < box[3]",
"def inrange(cc, point):\n return point.row in range(cc.top, cc.bottom+1) and point.col in range(cc.left, cc.right+1)",
"def is_inside(self, mX, mY, point):\n return (math.sqrt((point[0] - mX) * (point[0] - mX)\n + (point[1] - mY) * (point[1] - mY)) <= 2)",
"def within(self, x, y):\n return x >= self.top_x and x <= self.bottom_x and y >= self.bottom_y and y <= self.top_y",
"def isPointInside(self, p):\n x,y = p[0], p[1]\n A = self.left <= x <= self.right\n B = self.bottom <= y <= self.top\n return (A and B)",
"def isPointInside(self, p):\n x,y = p[0], p[1]\n A = self.left <= x <= self.right\n B = self.bottom <= y <= self.top\n return (A and B)",
"def check_edges(self):\n screen_rect = self.screen.get_rect()\n if self.rect.right >= screen_rect.right or self.rect.left <= 0:\n return True",
"def is_border(coord, sides):\n return coord[0] <= 0 or coord[0] >= sides[\"bottom\"]\\\n or coord[1] <= 0 or coord[1] >= sides[\"right\"]",
"def check_edges(self):\r\n screen_rect = self.screen.get_rect()\r\n if self.rect.right >= screen_rect.right:\r\n return True\r\n elif self.rect.left <= 0:\r\n return True",
"def is_down_diagonal_win(self, checker):\n for row in range(self.height-3):\n for col in range(self.width-3):\n if self.slots[row][col] == checker and \\\n self.slots[row+1][col+1] == checker and \\\n self.slots[row+2][col+2] == checker and \\\n self.slots[row+3][col+3] == checker:\n return True\n return False",
"def check_edges(self):\n screen_rect = self.screen.get_rect()\n if self.rect.right >= screen_rect.right:\n return True\n elif self.rect.left <= screen_rect.left:\n return True",
"def check_diagonals(self, win: list) -> bool:\r\n for i in range(self.size - self.win_condition + 1):\r\n # [x x ]\r\n # [ x x ]\r\n # [ x x]\r\n # [ x]\r\n diagonal = []\r\n x = i\r\n y = 0\r\n for j in range(self.size - i):\r\n diagonal.append(self.tags[x][y])\r\n x += 1\r\n y += 1\r\n for j in range(len(diagonal) - len(win) + 1):\r\n if win == diagonal[j:j + self.win_condition]:\r\n return True\r\n # [x ]\r\n # [x x ]\r\n # [ x x ]\r\n # [ x x]\r\n diagonal = []\r\n x = 0\r\n y = i\r\n for j in range(self.size - i):\r\n diagonal.append(self.tags[x][y])\r\n x += 1\r\n y += 1\r\n for j in range(len(diagonal) - len(win) + 1):\r\n if win == diagonal[j:j + self.win_condition]:\r\n return True\r\n\r\n # [ x x]\r\n # [ x x ]\r\n # [x x ]\r\n # [x ]\r\n diagonal = []\r\n x = self.size - 1 - i\r\n y = 0\r\n for j in range(self.size - i):\r\n diagonal.append(self.tags[x][y])\r\n x -= 1\r\n y += 1\r\n for j in range(len(diagonal) - len(win) + 1):\r\n if win == diagonal[j:j + self.win_condition]:\r\n return True\r\n # [ x]\r\n # [ x x]\r\n # [ x x ]\r\n # [x x ]\r\n diagonal = []\r\n x = self.size - 1\r\n y = 0 + i\r\n for j in range(self.size - i):\r\n diagonal.append(self.tags[x][y])\r\n x -= 1\r\n y += 1\r\n for j in range(len(diagonal) - len(win) + 1):\r\n if win == diagonal[j:j + self.win_condition]:\r\n return True",
"def _inside(self, x, y):\n wx, wy, w, h = self._raw_graph_window_dim()\n if wx <= x < wx + w and wy <= y < wy + h:\n return True\n return False",
"def inside_rectangle(self, x, y):\n if (self.pos.x - self.width < x < self.pos.x + self.width and\n self.pos.y - self.height < y < self.pos.y + self.height):\n return True",
"def is_in_polygon(self, point):\n reference_point = self.get_reference_point()\n \n reference_segment = DirectedEdge(point, reference_point)\n\n num_crossings = 0\n \n left_idx = 0\n while left_idx != len(self):\n right_idx = (left_idx + 1) % len(self)\n \n are_crossing = False\n \n if reference_segment.contains_point(self[left_idx]):\n while reference_segment.contains_point(self[right_idx]):\n right_idx = (right_idx + 1) % len(self)\n \n if right_idx == left_idx:\n break\n \n if left_idx == right_idx:\n left_idx = len(self)\n continue\n \n left_endpoint = self[(left_idx - 1) % len(self)]\n right_endpoint = self[(right_idx + 1) % len(self)]\n \n are_crossing = reference_segment.orientation(left_endpoint) != reference_segment.orientation(right_endpoint)\n left_idx = (right_idx + 1) % len(self) if left_idx < (right_idx + 1) % len(self) else len(self) \n elif reference_segment.contains_point(self[right_idx]):\n left_idx += 1\n continue\n else:\n edge = DirectedEdge(self[left_idx], self[right_idx])\n are_crossing = reference_segment.is_intersecting(edge)\n left_idx += 1\n \n num_crossings = num_crossings + 1 if are_crossing else num_crossings\n \n return num_crossings % 2 == 1"
] | [
"0.70133144",
"0.69797367",
"0.6935007",
"0.69121915",
"0.687569",
"0.687569",
"0.6854568",
"0.6748199",
"0.67210734",
"0.6670797",
"0.6650344",
"0.66328245",
"0.6617512",
"0.6605541",
"0.6605422",
"0.65742147",
"0.6531653",
"0.6525218",
"0.65238535",
"0.6522948",
"0.6522948",
"0.6508997",
"0.65068865",
"0.64750457",
"0.64652896",
"0.6464304",
"0.6463815",
"0.6449859",
"0.64467955",
"0.64360243"
] | 0.70146877 | 0 |
Returns true if the vector is a zero vector, otherwise false. | def is_zero_vector(vector:tuple)->bool:
return vector[0] == 0 and vector[1] == 0 | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def isVecZero(vec):\n trues = [isZero(e) for e in vec]\n return all(trues)",
"def is_zero(self):\n for t in self:\n if t != TRIT_ZERO:\n return False\n return True",
"def isZero(self):\n return self.count == 0",
"def is_zero(self):\n return self._express.is_zero()",
"def is_zero(self):\n # any nonzero entry in any matrix representation\n # disqualifies the morphism as having totally zero outputs\n return self._matrix.is_zero()",
"def is_zero(self, a):\n return not a",
"def isZero(self):\n\t\treturn (self.p.isZero() & (self.q.isZero() == False))",
"def is_zero(self) -> bool:\n return self.field.zero == self",
"def is_zero(self):\r\n return self._real.is_zero() and self._imag.is_zero()",
"def _is_zero(self):\n return (len(self._digits) == 1) and\\\n (self._digits[0] == self.Symbols.ZERO.value)",
"def is_zero(self):\n return self._x == 0 and self._y == 0",
"def is_zero(self):\n return (self._num == 0)",
"def is_zero(self):\n return float(self.coeff.nominator) / self.coeff.denominator == 0.0",
"def __nonzero__(self):\n for e in self:\n if e != 0:\n return True\n return False",
"def is_zero(self):\n return -0.0001 <= self.l2_norm() <= 0.0001",
"def is_empty(self):\n return ch.prod(ch.tensor(self.x.shape)).item() == 0",
"def is_vector(self):\n return len(self.coeffs.shape[self.sdim:]) == 1",
"def is_zero(f):\n return dmp_zero_p(f.rep, f.lev)",
"def _is_zero(x):\r\n if not hasattr(x, 'type'):\r\n return np.all(x == 0.)\r\n if isinstance(x.type, NullType):\r\n return 'no'\r\n if isinstance(x.type, DisconnectedType):\r\n return 'yes'\r\n\r\n no_constant_value = True\r\n try:\r\n constant_value = theano.get_scalar_constant_value(x)\r\n no_constant_value = False\r\n except theano.tensor.basic.NotScalarConstantError:\r\n pass\r\n\r\n if no_constant_value:\r\n return 'maybe'\r\n\r\n if constant_value != 0.:\r\n return 'no'\r\n\r\n return 'yes'",
"def _is_zero(x):\n if not hasattr(x, \"type\"):\n return np.all(x == 0.0)\n if isinstance(x.type, NullType):\n return \"no\"\n if isinstance(x.type, DisconnectedType):\n return \"yes\"\n\n no_constant_value = True\n try:\n constant_value = aesara.get_scalar_constant_value(x)\n no_constant_value = False\n except aesara.tensor.exceptions.NotScalarConstantError:\n pass\n\n if no_constant_value:\n return \"maybe\"\n\n if constant_value != 0.0:\n return \"no\"\n\n return \"yes\"",
"def has_zeros(tensor, verbose=True):\n tensor_numpy = tensor.data.cpu().numpy().flatten()\n where_zero = np.argwhere(tensor_numpy == 0.0)\n\n zero_count = len(where_zero)\n zero = zero_count != 0\n\n if verbose and zero:\n print(f\"Encountered {zero_count} zeros\")\n\n return zero",
"def zero(self) -> bool:\n return self._algorithm.is_last_zero(self._stat)",
"def is_vector(x):\r\n return len(x.shape) == 1",
"def iszero(a: float) -> bool:\n return np.isclose(a, 0.0, atol=1.0e-12, rtol=0.0)",
"def __nonzero__(self):\n return not self.as_point == (0, 0)",
"def isZero(val):\n if isSympy(val):\n try:\n val = expressionToNumber(val)\n except Exception:\n return False\n try:\n if np.isclose(np.abs(val), 0):\n return True\n except TypeError:\n newVal = complex(val)\n return np.abs(newVal) == 0",
"def component_is_zero(self, key):\n a = self[key]\n return not np.any(a)",
"def is_zero_matrix(self):\n M = self.rep\n for i in range(self.rows):\n for j in range(self.cols):\n if M[i, j]:\n return False\n return True",
"def is_zero(self):\n for action, prob in self._regrets.items():\n if prob != 0.0:\n return False\n return True",
"def testZeros(self):\n v1 = Vector.zeros(3)\n assert v1 == (0, 0, 0)\n hitException = False\n try:\n Vector.zeros(0)\n except IndexError:\n hitException = True\n assert hitException\n hitException = False\n try:\n Vector.ones(-1)\n except IndexError:\n hitException = True\n assert hitException"
] | [
"0.8560863",
"0.78165585",
"0.7557371",
"0.753894",
"0.74890184",
"0.7482657",
"0.7468545",
"0.74608725",
"0.745997",
"0.7423766",
"0.74129486",
"0.741105",
"0.7316494",
"0.7311554",
"0.7263635",
"0.70921254",
"0.7089508",
"0.707456",
"0.7040816",
"0.7008552",
"0.69950205",
"0.6978518",
"0.6971061",
"0.69670546",
"0.69629574",
"0.69194746",
"0.6892665",
"0.68745095",
"0.6867884",
"0.6791057"
] | 0.8220028 | 1 |
Creates a convex line segment between two points. In the context of polygon creation, desc_y is set to True if we are building the top left or top right corner. Desc_X is set to True if we are building the top right or bottom right corner. This impacts the order we accept points and how we interpret the direction of points compared to the existing line. Params | def convex_line_segment(point_list:list, desc_y:bool=False, desc_x:bool=False)->list:
if len(point_list) < 3:
return point_list
line = []
x_extrema = None
# Since the list is sorted by x second, the last point is actually the
# first point of the last block of y values in the list (if more than
# one coordinate has the minimum y value).
last_point = point_list[-1]
test_point = -2
while point_list[test_point][1] == last_point[1]:
last_point = point_list[test_point]
test_point -= 1
for point in point_list:
# We end when we get to the last point. Points with the same y-value, but
# more inside x-value won't be on the polygon.
if point == last_point:
break
# We skip points that are left of the point we have added already.
if not x_extrema is None:
if desc_x and x_extrema >= point[0]:
continue
elif not desc_x and x_extrema <= point[0]:
continue
# If the line is empty, we just add it.
if not line:
line.append(point)
x_extrema = point[0]
continue
dir = direction(line[-1], point, last_point)
if not desc_y == desc_x:
dir *= -1
if dir > 0: # if and only if the polygon stays convex by adding this point...
if len(line) > 1 and collinear(line[-2], line[-1], point):
# We remove collinear points to match what Graham's scan does.
del line[-1]
line.append(point)
x_extrema = point[0]
# We end by adding the last point to the list to complete the line.
line.append(last_point)
return line | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def addRevLineSeg(self, x1, y1, x2, y2):\n # tip triangles\n if np.allclose(x1, 0.0):\n a = [x1, y1, 0.0]\n for (sa1, ca1), (sa2, ca2) in self._mesh.sincos:\n r = x2\n b = [r * sa2, y2, r * ca2]\n c = [r * sa1, y2, r * ca1]\n self.addTri(a, b, c, None if np.allclose(y1, y2) else a)\n # shank end triangle fan, p1 = top center\n elif np.allclose(x2, 0.0):\n a = [x2, y2, 0.0]\n for (sa1, ca1), (sa2, ca2) in self._mesh.sincos:\n b = [x1 * sa1, y1, x1 * ca1]\n c = [x1 * sa2, y1, x1 * ca2]\n self.addTri(a, b, c, None if np.allclose(y1, y2) else a)\n # triangle strip\n # d o--o c\n # | /|\n # |/ |\n # a o--o b\n else:\n for (sa1, ca1), (sa2, ca2) in self._mesh.sincos:\n self.addQuad([x1 * sa1, y1, x1 * ca1], # a\n [x1 * sa2, y1, x1 * ca2], # b\n [x2 * sa2, y2, x2 * ca2], # c\n [x2 * sa1, y2, x2 * ca1]) # d",
"def createLineSegment(self):\n return _libsbml.Curve_createLineSegment(self)",
"def draw_line(xy1, xy2, ax, **kwargs): \n x_arr = [xy1[0], xy2[0]]\n y_arr = [xy1[1], xy2[1]]\n edge = Line2D([x_arr],[y_arr], **kwargs)\n ax.add_line(edge)\n\n return ax,",
"def discretize_line(p0, p1, segments):\n p0, p1 = Point(p0), Point(p1)\n dx, dy = p1.x - p0.x, p1.y - p0.y\n vtx = [Point(p0).as_tuple()]\n if isinstance(segments, list):\n for ds in segments:\n x0 = p0.x + ds * dx\n y0 = p0.y + ds * dy\n vtx.append((x0, y0))\n return vtx\n for i in range(segments):\n ds = (i + 1) / segments\n x0 = p0.x + ds * dx\n y0 = p0.y + ds * dy\n vtx.append((x0, y0))\n return vtx",
"def add_line(self, x0, y0, x1, y1, style=None):\n style = self.__prepare_style(style, 'o')\n if x0 > x1:\n # swap A and B\n x1, x0 = x0, x1\n y1, y0 = y0, y1\n # get delta x, y\n dx = x1 - x0\n dy = y1 - y0\n # if a length of line is zero just add point\n if dx == 0 and dy == 0:\n if self.check_coord_in_range(x0, y0):\n self.canvas[y0][x0] = style\n return\n # when dx >= dy use fill by x-axis, and use fill by y-axis otherwise\n if abs(dx) >= abs(dy):\n for x in range(x0, x1 + 1):\n y = y0 if dx == 0 else y0 + int(round((x - x0) * dy / float((dx))))\n if self.check_coord_in_range(x, y):\n self.canvas[y][x] = style\n else:\n if y0 < y1:\n for y in range(y0, y1 + 1):\n x = x0 if dy == 0 else x0 + int(round((y - y0) * dx / float((dy))))\n if self.check_coord_in_range(x, y):\n self.canvas[y][x] = style\n else:\n for y in range(y1, y0 + 1):\n x = x0 if dy == 0 else x1 + int(round((y - y1) * dx / float((dy))))\n if self.check_coord_in_range(x, y):\n self.canvas[y][x] = style",
"def TwoPoints(self, p1, p2):\n\n p1 = base.getvector(p1)\n if len(p1) == 2:\n p1 = np.r_[p1, 1]\n p2 = base.getvector(p2)\n if len(p2) == 2:\n p2 = np.r_[p2, 1]\n\n return Line2(np.cross(p1, p2))",
"def _draw_cross_line(self, fig, point, x_range, y_range):\n\t\tvline_x = [point[0] for i in y_range]\n\t\tvline_y = [i for i in y_range]\n\n\t\thline_x = [i for i in x_range]\n\t\thline_y = [point[1] for i in x_range]\n\n\t\tfig.plot(point[0], point[1], 'o', color='red')\n\t\tfig.plot(vline_x, vline_y, color='red', linewidth=2, linestyle='dotted')\n\t\tfig.plot(hline_x, hline_y, color='red', linewidth=2, linestyle='dotted')\n\t\tpass",
"def draw_line(cvs, p1, p2, antialias):\n xs, ys = np.array([p1[0], p2[0]]), np.array([p1[1], p2[1]])\n points = pd.DataFrame({'x': xs, 'y': ys, 'val': 5.0})\n return cvs.line(points, 'x', 'y', agg=ds.reductions.max(\"val\"),\n antialias=antialias)",
"def draw_line(self, point1, point2, line_color, line_width=2):\n if point1 is not None and point2 is not None:\n self.draw.line([point1, point2], fill=line_color, width=line_width)",
"def draw(x,y,x1,y1,d,color=1):\n d.add(dxf.line((x,y),(x1,y1),color=color, layer='LINES',thickness=0.01))",
"def draw_line_segment(\n x1: float, y1: float, x2: float, y2: float, color: C3F\n ) -> None:\n pyglet.graphics.draw(\n 2,\n pyglet.gl.GL_LINE_STRIP,\n (GeoDrawer._VERTEX_MODE, [x1, y1, x2, y2]),\n (GeoDrawer._COLOR_MODE, color * 2),\n )",
"def create_line(self, x1, y1, x2, y2, style=None, parent=None):\n attrs = {'d': 'M %5f %5f L %5f %5f' % (x1, y1, x2, y2)}\n return self.create_path(attrs, style, parent)",
"def draw_line(x1, y1, x2, y2):\r\n #global _canvas\r\n #global _current_line_thickness\r\n #global _current_color\r\n if _canvas == None:\r\n raise RuntimeError(\"Canvas is not open yet.\")\r\n else:\r\n path = Path(Point(x1, y1), Point(x2, y2))\r\n path.setBorderWidth(_current_line_thickness)\r\n path.setBorderColor(_current_color)\r\n _canvas.add(path)",
"def drawLine(x0,y0,x1,y1,ucoords=1):\n if ucoords:\n dislin.rline(x0,y0,x1,y1)\n else:\n dislin.line(x0,y0,x1,y1)",
"def line(x0: float, y0: float, x1: float, y1: float) -> LineCollection:\n return LineCollection([(complex(x0, y0), complex(x1, y1))])",
"def line(self, x0, y0, x1, y1, char): # noqa: C901, PLR0912\n # pylint: disable=too-many-arguments, too-many-branches\n if x0 > x1:\n x1, x0 = x0, x1\n y1, y0 = y0, y1\n\n dx = x1 - x0\n dy = y1 - y0\n\n if dx == 0 and dy == 0:\n self.point(x0, y0, char)\n elif abs(dx) >= abs(dy):\n for x in range(x0, x1 + 1):\n if dx == 0:\n y = y0\n else:\n y = y0 + int(round((x - x0) * dy / float(dx)))\n self.point(x, y, char)\n elif y0 < y1:\n for y in range(y0, y1 + 1):\n if dy == 0:\n x = x0\n else:\n x = x0 + int(round((y - y0) * dx / float(dy)))\n self.point(x, y, char)\n else:\n for y in range(y1, y0 + 1):\n if dy == 0:\n x = x0\n else:\n x = x1 + int(round((y - y1) * dx / float(dy)))\n self.point(x, y, char)",
"def add_line(self, point1: Point, point2: Point, counts_as_step=True, interesting=False) -> Line:\n line = Line(point1=point1, point2=point2)\n self.add_step_premade(line, counts_as_step=counts_as_step, interesting=interesting)\n return line",
"def line(canvas, points, line_width, line_color):\n \n # duplicate first point in case only one point was given\n points = points[0], points\n canvas.create_line(points, width = int(line_width), fill = line_color)",
"def draw_line(self, pt0, pt1, color):\n steep = False\n if abs(pt0[0]-pt1[0]) < abs(pt0[1]-pt1[1]):\n pt0[0], pt0[1] = pt0[1], pt0[0]\n pt1[0], pt1[1] = pt1[1], pt1[0]\n steep = True\n\n if pt0[0] > pt1[0]:\n pt0[0], pt1[0] = pt1[0], pt0[0]\n pt0[1], pt1[1] = pt1[1], pt0[1]\n\n if pt0[1] > pt1[1]:\n dy = pt0[1] - pt1[1]\n inc_y = -1\n else:\n dy = pt1[1] - pt0[1]\n inc_y = 1\n\n dx = pt1[0] - pt0[0]\n d = 2 * dy - dx\n incr_e = 2 * dy\n incr_ne = 2 * (dy - dx)\n x = pt0[0]\n y = pt0[1]\n\n if not steep:\n self.buffer.set_pixel((x, y), color)\n while x < pt1[0]:\n if d <= 0:\n d = d + incr_e\n x = x + 1\n else:\n d = d + incr_ne\n x = x + 1\n y = y + inc_y\n self.buffer.set_pixel((x, y), color)\n else:\n self.buffer.set_pixel((y, x), color)\n while x < pt1[0]:\n if d <= 0:\n d = d + incr_e\n x = x + 1\n else:\n d = d + incr_ne\n x = x + 1\n y = y + inc_y\n self.buffer.set_pixel((y, x), color)",
"def generate_line(point_1, point_2):\r\n A = point_1.y - point_2.y\r\n B = point_2.x - point_1.x\r\n C = point_1.y * B + point_1.x * A\r\n return np.matrix([[A],[B],[-C]])",
"def on_line_and_between_endpoints_2d(pt1, pt2, pt, tol=None):\r\n if tol is None:\r\n tol = get_tol_2d()\r\n return geometry.gmOnLineAndBetweenEndpointsWithTol(pt1, pt2, pt, tol)",
"def linePointXY(l,p,inside=True,distance=False,params=False):\n a=l[0]\n b=l[1]\n # check for degenerate case of zero-length line\n abdist = dist(a,b)\n if abdist < epsilon:\n #raise ValueError('zero-length line passed to linePointXY')\n print('zero-length line passed to linePointXY')\n return False\n\n if distance and params:\n raise ValueError('incompatible distance and params parameters passed to linePointXY')\n\n x0=p[0]\n y0=p[1]\n z0=p[2]\n x1=a[0]\n y1=a[1]\n z1=a[2]\n x2=b[0]\n y2=b[1]\n z2=b[2]\n\n ## check to see if all three points lie in the same x,y plane\n if not isXYPlanar([p,a,b]):\n raise ValueError('non-XY points in linePointXY call')\n return false\n # if abs(z1-z0) > epsilon or abs(z2-z0) > epsilon:\n # return False\n\n linedist = abs( ((y2-y1)*x0 - (x2-x1)*y0 + x2*y1 - y2*x1)/abdist)\n\n ## this is the fast case:\n if not inside and distance:\n return linedist\n \n ## find out where the intersection between the original line and a\n ## line defined by the point and an orthogonal direction vector\n ## is. We do this by constructing two direction vectors\n ## orthogonal to the orgiginal line scaled by the line distance,\n ## and adding them to the point in question. Assuming that the\n ## line distance is not zero, only one of these constructed points\n ## will fall on the line\n\n ## compute unit direction vector for original line\n dir = sub(b,a)\n dir = scale3(dir,1.0/mag(dir))\n\n ## compute two orthogonal direction vectors of length linedist\n ordir1 = scale3(orthoXY(dir),linedist)\n ordir2 = scale3(ordir1, -1.0)\n \n ## there are two possible intersection points\n pi1 = add(p,ordir1)\n pi2 = add(p,ordir2)\n\n ## compute distances\n d1pa = dist(a,pi1)\n d1pb = dist(pi1,b)\n d1 = d1pa+d1pb # \"triangle\" with pi1\n\n d2pa = dist(a,pi2)\n d2pb = dist(pi2,b)\n d2 = d2pa+d2pb # \"triangle\" with pi2\n\n ## the shortest \"triangle\" distance will signal the point that\n ## is actually on the line, even if that point falls outside\n ## the a,b line interval\n \n if params or not inside: # if we don't care about being inside the\n # line segment\n if d1 <= d2:\n if distance:\n return d1\n elif params:\n return d1pb/abdist\n else:\n return pi1\n else:\n if distance:\n return d2\n elif params:\n return d2pb/abdist\n else:\n return pi2\n \n \n ## if the closest point on the line to point p lies between\n ## the endpoints of the line, then either d1 or d2 will equal\n ## abdist. IF neither do, then we know that the closest point lies\n ## outside the endpoints\n\n if abs(d1-abdist) < epsilon:\n if distance:\n return linedist\n else:\n return pi1\n\n if abs(d2-abdist) < epsilon:\n if distance:\n return linedist\n else:\n return pi2\n\n ## closest point is outside the interval. That means that the\n ## distance from point p to whichever endpoint is smaller is the\n ## closest distance\n\n d3 = dist(a,p)\n d4 = dist(b,p)\n\n if d3 < d4:\n if distance:\n return d3\n else:\n return a\n else:\n if distance:\n return d4\n else:\n return b",
"def DrawLinePoint(*args, **kwargs):\n return _gdi_.PseudoDC_DrawLinePoint(*args, **kwargs)",
"def draw_polyline(*points):\r\n global _canvas\r\n if _canvas == None:\r\n raise RuntimeError(\"Canvas is not open yet.\")\r\n else:\r\n #print(points)\r\n #print(len(points))\r\n newpoints = []\r\n for x in range(0, len(points), 2):\r\n #print(x)\r\n pt = Point(points[x], points[x+1])\r\n newpoints += [ pt ]\r\n #print(newpoints)\r\n path = Path(*newpoints)\r\n path.setBorderWidth(_current_line_thickness)\r\n path.setBorderColor(_current_color)\r\n _canvas.add(path)",
"def DrawLinePoint(*args, **kwargs):\n return _gdi_.DC_DrawLinePoint(*args, **kwargs)",
"def test_line_to_points(self):\n delta = 1\n # Create simple line\n L = numpy.array([[0, 0], [2, 0]])\n V = points_along_line(L, 1)\n\n expected_V = [[0, 0], [1, 0], [2, 0]]\n msg = ('Calculated points were %s, expected '\n '%s' % (V, expected_V))\n assert numpy.allclose(V, expected_V), msg\n\n # Not starting at zero\n # Create line\n L2 = numpy.array([[168, -2], [170, -2], [170, 0]])\n V2 = points_along_line(L2, delta)\n\n expected_V2 = [[168, -2], [169, -2], [170, -2],\n [170, -1], [170, 0]]\n msg = ('Calculated points were %s, expected '\n '%s' % (V2, expected_V2))\n assert numpy.allclose(V2, expected_V2), msg\n\n # Realistic polygon\n filename = '%s/%s' % (TESTDATA, 'indonesia_highway_sample.shp')\n layer = read_layer(filename)\n geometry = layer.get_geometry()\n\n P = geometry[0]\n C = points_along_line(P, delta)\n\n # Check against reference centroid\n expected_v = [[106.7168975, -6.15530081],\n [106.85224176, -6.15344678],\n [106.93660016, -6.21370279]]\n assert numpy.allclose(C, expected_v, rtol=1.0e-8)\n\n # Store points to file (to e.g. check with qgis)\n out_filename = unique_filename(prefix='test_points_along_line',\n suffix='.shp')\n V = Vector(data=None,\n projection=DEFAULT_PROJECTION,\n geometry=[C],\n name='Test points_along_line')\n V.write_to_file(out_filename)",
"def draw_line(self, point1, point2, line_width, line_color):\n line_color = check_color(line_color)\n STline.line(self.canvas, (point1, point2), line_width, line_color)",
"def draw(self):\n # s1 = ShowPoint(self.cnv, self.p1.xpt, self.p1.ypt)\n # s2 = ShowPoint(self.cnv, self.p2.xpt, self.p2.ypt)\n # s1.draw()\n # # s2.draw()\n self.cnv.create_line(self.p1.xpt, self.p1.ypt, self.p2.xpt, self.p2.ypt)",
"def drawLine(self,start,stop):\n startX = int(self.vert[start][0]*self.scale + self.size/2)\n startY = int(self.vert[start][1]*self.scale + self.size/2)\n endX = int(self.vert[stop][0]*self.scale + self.size/2)\n endY = int(self.vert[stop][1]*self.scale + self.size/2)\n \n self.canvas.create_line(startX,startY,endX,endY,fill='white')",
"def free_line(p, eps, s, dps1, dps2, ds):\n px = p[0]\n py = p[1]\n s1x = s[0, 0]\n s1y = s[0, 1]\n s2x = s[1, 0]\n s2y = s[1, 1]\n if s1x == s2x and s1y == s2y:\n if eucl_dist(p, s[0]) > eps:\n lf = [-1, -1]\n else:\n lf = [0, 1]\n else:\n if point_to_seg(p, s[0], s[1], dps1, dps2, ds) > eps:\n # print(\"No Intersection\")\n lf = [-1, -1]\n else:\n segl = eucl_dist(s[0], s[1])\n segl2 = segl * segl\n intersect = circle_line_intersection(px, py, s1x, s1y, s2x, s2y, eps)\n if intersect[0][0] != intersect[1][0] or intersect[0][1] != intersect[1][1]:\n i1x = intersect[0, 0]\n i1y = intersect[0, 1]\n u1 = (((i1x - s1x) * (s2x - s1x)) + ((i1y - s1y) * (s2y - s1y))) / segl2\n\n i2x = intersect[1, 0]\n i2y = intersect[1, 1]\n u2 = (((i2x - s1x) * (s2x - s1x)) + ((i2y - s1y) * (s2y - s1y))) / segl2\n ordered_point = sorted((0, 1, u1, u2))\n lf = ordered_point[1:3]\n else:\n if px == s1x and py == s1y:\n lf = [0, 0]\n elif px == s2x and py == s2y:\n lf = [1, 1]\n else:\n i1x = intersect[0][0]\n i1y = intersect[0][1]\n u1 = (((i1x - s1x) * (s2x - s1x)) + ((i1y - s1y) * (s2y - s1y))) / segl2\n if 0 <= u1 <= 1:\n lf = [u1, u1]\n else:\n lf = [-1, -1]\n return lf"
] | [
"0.61220574",
"0.5985634",
"0.58928055",
"0.586802",
"0.5844202",
"0.5812266",
"0.5790249",
"0.57509595",
"0.5726299",
"0.5695145",
"0.5691318",
"0.56896853",
"0.5685234",
"0.5680852",
"0.56595385",
"0.563459",
"0.5601871",
"0.5600169",
"0.5596646",
"0.55840945",
"0.5568787",
"0.55333537",
"0.5532701",
"0.5506179",
"0.5481534",
"0.54809654",
"0.5475724",
"0.54671",
"0.5461482",
"0.54550636"
] | 0.74640554 | 0 |
Determines if a line segment described by d_y, d_x, and b is right of a point. | def intersects_right(point:tuple, line:tuple, d_y:float, d_x:float, b:float, include_top:bool=False, inclusive:bool=False)->bool:
min_y, max_y = line[0][1], line[1][1]
if min_y > max_y:
min_y, max_y = max_y, min_y
if not between(point[1], min_y, max_y):
# The point is above or below the line segment.
return False
if include_top and point[1] == min_y:
# We are excluding the bottom and the point is at the bottom.
return False
if (not include_top) and point[1] == max_y:
# We are excluding the top and teh point is at the top.
return False
if b == None:
# Handling vertical lines
if inclusive and line[0][0] == point[0]:
return True
return line[0][0] > point[0]
x_int = ((point[1]-b) * d_x) / d_y
if inclusive and x_int == point[0]:
return True
return x_int > point[0] | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def point_on_line(point:tuple, line:tuple, d_y:float, d_x:float, b:float)->bool:\n if not near_segment(point, line):\n # Fast fail to handle cases where the point isn't in the bounding rectangle of the line segment.\n return False\n if b == None and point[0] == line[0][0]:\n return True\n return d_y * point[0] == (point[1] - b) * d_x",
"def check_if_intersection(point_a, point_b, point_c, point_d):\n try:\n # get factors a and b of such that y = a + b*x describes line between point_a and point_b\n b = (point_b[1] - point_a[1]) / (point_b[0] - point_a[0])\n a = point_a[1] - b * point_a[0]\n # get factors c and d of such that y = c + d*x describes line between point_c and point_d\n d = (point_d[1] - point_c[1]) / (point_d[0] - point_c[0])\n c = point_c[1] - d * point_c[0]\n\n # calulate intersection by setting a + b*x = c + d*x\n x = (a - c) / (d - b)\n\n # check if x is between x coordinates of points a and b and between x coordinates of points c and d\n return (min(point_a[0], point_b[0]) < x) & (max(point_a[0], point_b[0]) > x) & \\\n (min(point_c[0], point_d[0]) < x) & (max(point_c[0], point_d[0]) > x)\n\n except ZeroDivisionError:\n # this mean point a and b have same x coordinate or point c and d have same c coordinate -> deal with this\n if (point_b[0] == point_a[0]) & (point_c[0] == point_d[0]): # both pairs have same x coordinate\n return point_a[0] == point_c[0]\n if point_b[0] == point_a[0]:\n # get factors c and d of such that y = c + d*x describes line between point_c and point_d\n d = (point_d[1] - point_c[1]) / (point_d[0] - point_c[0])\n c = point_c[1] - d * point_c[0]\n # get y value of connection between c and d at x = point_a[0]\n y = c + d*point_a[0]\n return (y > min(point_a[1], point_b[1])) & (y < max(point_a[1], point_b[1]))\n if point_c[0] == point_d[0]:\n # get factors a and b of such that y = a + b*x describes line between point_a and point_b\n b = (point_b[1] - point_a[1]) / (point_b[0] - point_a[0])\n a = point_a[1] - b * point_a[0]\n # get y value of connection between a and b at x = point_c[0]\n y = a + b*point_c[0]\n return (y > min(point_c[1], point_d[1])) & (y < max(point_c[1], point_d[1]))",
"def is_in_collision_line(self, a, b):\n return abs((b[0]-a[0])*self.x + (a[1]-b[1])*self.y + (a[0]-b[0])*b[1] + (b[1]-a[1])*a[0]) /\\\n sqrt((b[0]-b[1])**2 + (a[1]-b[1])**2 + 0.0000001)< self.r",
"def validate_points(a, b):\r\n\tdiff_y = b[0] - a[0]\r\n\tdiff_x = b[1] - a[1]\r\n\r\n\treturn (diff_y == 0 and diff_x != 0) or (diff_x == 0 and diff_y != 0) or abs(diff_x) == abs(diff_y)",
"def is_on_line(point_a, point_b, point_c):\r\n return (point_b[0] - point_a[0]) * (point_c[1] - point_a[1]) - (point_b[1] - point_a[1]) * (point_c[0] - point_a[0])",
"def on_segment(point_p, point_q, point_r):\n if (point_q.x <= max(point_p.x, point_r.x)\n and point_q.x >= min(point_p.x, point_r.x)\n and point_q.y <= max(point_p.y, point_r.y)\n and point_q.y >= min(point_p.y, point_r.y)):\n return True\n return False",
"def is_above_line(point_a, point_b, test_point):\n d_1 = (point_b[0] - point_a[0])\n d_2 = (test_point[1] - point_a[1])\n d_3 = (point_b[1] - point_a[1])\n d_4 = (test_point[0] - point_a[0])\n pos = (d_1 * d_2) - (d_3 * d_4)\n if pos >= 0: # this means anything on the line is being considered as above\n # the line, this is useful in generating simple polygon.\n return True\n else:\n return False",
"def coplanar_points_are_on_same_side_of_line(a, b, p1, p2):\n check_shape_any(a, (3,), (-1, 3), name=\"a\")\n vg.shape.check(locals(), \"b\", a.shape)\n vg.shape.check(locals(), \"p1\", a.shape)\n vg.shape.check(locals(), \"p2\", a.shape)\n\n # Uses \"same-side technique\" from http://blackpawn.com/texts/pointinpoly/default.html\n along_line = b - a\n return vg.dot(vg.cross(along_line, p1 - a), vg.cross(along_line, p2 - a)) >= 0",
"def is_point_on_same_line(self, x, y = None):\n x, y = y is not None and (x, y) or (x[0], x[1])\n\n if self.is_vertical():\n return Point(x, 0) == Point(self.x_value, 0)\n else:\n return Point(0, y) == Point(0, (self.slope * x + self.y_intercept))",
"def isPointOnLine(node1, node2, point):\n m, b, d = geometry.lineSpec(node1, node2)\n if d == -1: # if two nodes are the same\n if node1 == point:\n return True\n else:\n return False\n else:\n if m == True: # parallel to y axis\n if point[0] == b and \\\n (((node1[1] <= point[1]) and (point[1] <= node2[1])) or\\\n ((node2[1] <= point[1]) and (point[1] <= node1[1]))):\n return True\n else:\n return False\n \n elif m == False:\n if point[1] == b and \\\n (((node1[0] <= point[0]) and (point[0] <= node2[0])) or\\\n ((node2[0] <= point[0]) and (point[0] <= node1[0]))):\n return True\n else:\n return False\n \n else:\n if(abs(point[1] - (m*point[0] + b)) < 0.05) and \\\n (((node1[0] <= point[0]) and (point[0] <= node2[0])) or\\\n ((node2[0] <= point[0]) and (point[0] <= node1[0]))) and\\\n (((node1[1] <= point[1]) and (point[1] <= node2[1])) or\\\n ((node2[1] <= point[1]) and (point[1] <= node1[1]))):\n return True\n else:\n return False",
"def contains_point(self, x, y):\r\n if self.m == None:\r\n if abs(x - self.start[0]) > 0.6:\r\n return False\r\n else:\r\n if (y >= self.start[1] and y <= self.end[1]) or \\\r\n (y <= self.start[1] and y >= self.end[1]):\r\n return True\r\n else:\r\n return False\r\n else: \r\n y0 = int(self.m * x + self.n)\r\n if abs(y - y0) > 0.6: \r\n return False \r\n else: \r\n if ((x >= self.start[0] and x <= self.end[0]) or \\\r\n (x <= self.start[0] and x >= self.end[0])) and \\\r\n ((y >= self.start[1] and y <= self.end[1]) or \\\r\n (y <= self.start[1] and y >= self.end[1])): \r\n return True\r\n else:\r\n return False",
"def is_point_within(self, x, y):\n return abs(x - self._x_position) <= self._x_length / 2 and abs(y - self._y_position) <= self._y_length / 2",
"def contains_point(self, x, y = None):\n x, y = y is not None and Point(x, y) or Point(x[0], x[1])\n\n cond1 = self.min_x() <= x <= self.max_x()\n cond2 = self.min_y() <= y <= self.max_y()\n return self.is_point_on_same_line(x, y) and cond1 and cond2",
"def is_point_on_curve(a, b, p, x, y):\n assert isinstance(a, Bn)\n assert isinstance(b, Bn)\n assert isinstance(p, Bn) and p > 0\n assert (isinstance(x, Bn) and isinstance(y, Bn)) \\\n or (x == None and y == None)\n\n if x == None and y == None:\n return True\n\n lhs = (y * y) % p\n rhs = (x*x*x + a*x + b) % p\n on_curve = (lhs == rhs)\n\n return on_curve",
"def bbox_segment_intersects(bbox, a, b):\n # check whether the line is completely left/right/above/below the bbox\n if ((a[0] < bbox[0] and b[0] < bbox[0]) or\n (a[0] > bbox[2] and b[0] > bbox[2]) or\n (a[1] < bbox[1] and b[1] < bbox[1]) or\n (a[1] > bbox[3] and b[1] > bbox[2])):\n return False\n\n # Check whether any of the four bbox points are on different sides of the\n # line.\n h = homo_line(a, b)\n s = [\n h[0] * p[0] + h[1] * p[1] + h[2] > 0 for p in\n [(bbox[0], bbox[1]), (bbox[0], bbox[3]),\n (bbox[2], bbox[1]), (bbox[2], bbox[3])]\n ]\n return (s[0] != s[1] or s[0] != s[2] or s[0] != s[3])",
"def isOnLine(self, point):\n if((point < self.start and point < self.end) or (\n point > self.start and point > self.end)):\n return False #point is not between the start and end of self\n \n if(self.getArea(self.start, self.end, point) > c.EPSILON):\n return False #points are not co-linear\n \n return True",
"def is_straight_line(self, arr):\n # First pair of point (x0, y0) \n x0 = arr[0][0]\n y0 = arr[0][1]\n\n # Second pair of point (x1, y1) \n x1 = arr[len(arr) - 1][0]\n y1 = arr[len(arr) - 1][1]\n\n dx = x1 - x0\n dy = y1 - y0\n\n # Loop to iterate over the points \n for i in range(len(arr)):\n x = arr[i][0]\n y = arr[i][1]\n\n if (dx * (y - y1) - dy * (x - x1)) > self.movement_tolerance:\n return False\n\n return True",
"def dans_cercle(self, r, x, y):\r\n self.r_num(r)\r\n valid = (isinstance(x, int) or isinstance(x, float)) and \\\r\n (isinstance(y, int) or isinstance(y, float))\r\n if valid:\r\n if sqrt(x**2+y**2)<self.r:\r\n return True\r\n else:\r\n return False\r\n else:\r\n raise TypeError",
"def is_point_on_curve(self, P):\n x, y, = P[0], P[1]\n left = y * y\n right = (x * x * x) + (self.a * x) + self.b\n return (left - right) % self.p == 0",
"def is_point_exist(point, a_value, b_value, field):\n\n return (\n (point.y_crd ** 2 -\n (point.x_crd ** 3 + a_value *\n point.x_crd + b_value)) % field == 0 and\n 0 <= point.x_crd < field and 0 <= point.y_crd < field)",
"def point_sur_segment(self, pt):\n dp = pt - self.c\n d = dp.length - self.r\n a = atan2(dp.y, dp.x)\n t = (a - self.a0) / self.da\n return t > 0 and t < 1, d, t",
"def segment_segment_intersects(a, b, c, d):\n return (line_ccw(a, c, d) != line_ccw(b, c, d) and\n line_ccw(a, b, c) != line_ccw(a, b, d))",
"def sanity_check(left_line, right_line):\n\n # check horizontal separation distance\n if abs(right_line.line_base_pos - left_line.line_base_pos) > 4.0:\n #print(\"Line base positions too far from each other\")\n return False\n\n # check lines are roughly parallel\n # if base pos and raduius of both lines are ok, it should be enough\n # to check the X distances of a few points with respect to their y positions\n # so slice the Y points into chunks and check\n chunksize = 200\n length = min(len(left_line.ally), len(right_line.ally))\n\n # TODO: error handling\n if (right_line.allx is not None) and (left_line.allx is not None):\n bias = None\n for i in range(0, length, chunksize):\n\n # take x at car as bias\n if bias is None:\n bias = abs(right_line.allx[i] - left_line.allx[i]) * left_line.xm_per_pix\n else:\n if abs(bias - abs(right_line.allx[i] - left_line.allx[i])*left_line.xm_per_pix) > 1.0:\n #print(\"Lines are not parallel\")\n return False\n else:\n return False\n\n # check curvatures -- the curvatures for left and right should be roughly\n # in the same magitude -- check for error\n if abs(left_line.radius_of_curvature - right_line.radius_of_curvature) > 200:\n #print(\"Line radius of curvature too different\")\n return False\n\n return True",
"def pointInSegment(point, segmentPoint1, segmentPoint2):\n\t\tx = point[0]\n\t\ty = point[1]\n\n\t\tif x < segmentPoint1[0] and x < segmentPoint2[0]:\n\t\t\treturn False\n\t\t\n\t\tif x > segmentPoint1[0] and x > segmentPoint2[0]:\n\t\t\treturn False\n\t\t\n\t\tif y < segmentPoint1[1] and y < segmentPoint2[1]:\n\t\t\treturn False\n\t\t\n\t\tif y > segmentPoint1[1] and y > segmentPoint2[1]:\n\t\t\treturn False\n\t\t\n\t\treturn True",
"def is_ate(self, snake_x, snake_y):\n if snake_x == self.x and snake_y == self.y:\n return True",
"def linesegment_plane_intersection(self, p0,p1,point,normal): # only returns lines...intersections through the segment end points are ignored\n\t\tp0dot=numpy.dot(p0-point,normal)\n\t\tp1dot=numpy.dot(p1-point,normal)\n\t\tif (p0dot>0 and p1dot<0) or (p0dot<0 and p1dot>0): \n\t\t\t# if the dot products have opposing signs, then the line intersects the plane\n\t\t\treturn True,p0+(p1-p0)*abs(p0dot)/(abs(p0dot)+abs(p1dot))\n\t\telse:\n\t\t\treturn False",
"def checkStraightLine(coordinates: List[List[int]]) -> bool:\n\t# initializing our comparison slope value\n\tnum = coordinates[1][1] - coordinates[0][1]\n\tden = coordinates[1][0] - coordinates[0][0]\n\tif den == 0:\n\t\tslope = math.inf\n\telse:\n\t\tslope = num / den\n\n\t# checking the initial slope against all other slopes\n\tslope_check = 0\n\tfor i in range(2, len(coordinates)):\n\t\tnum = coordinates[i][1] - coordinates[i-1][1]\n\t\tden = coordinates[i][0] - coordinates[i-1][0]\n\t\tif den == 0:\n\t\t\tslope_check = math.inf\n\t\telse:\n\t\t\tslope_check = num/den\n\n\t\tif slope_check != slope:\n\t\t\treturn False\n\n\treturn True",
"def is_on_line(p0, p1, p2, threshold = 0.01):\n p0, p1, p2 = map(lambda tup : np.array(tup[:2]), [p0, p1, p2])\n p1 -= p0\n p2 -= p0\n return abs((p1[0] / p1[1]) - (p2[0] / p2[1])) < threshold",
"def onSegment(self, p, q, r):\n if ((q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and\n (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))):\n return True\n return False",
"def check_point_right(nodeL, nodeR, city):\n A = get_city_points(city)\n B = get_node_points(nodeL)\n C = get_node_points(nodeR)\n slope = _slope(A, B)\n (F, G) = calibrator(A, B, slope)\n sign = math.copysign(1, ((G[0] - F[0]) * (C[1] - F[1]) - (G[1] - F[1]) * (C[0] - F[0])))\n\n if slope == \"horizontal\":\n if sign == 1:\n if A[0] > B[0]:\n return True\n else:\n return False\n else:\n if A[0] < B[0]:\n return True\n else:\n return False\n\n if slope == \"vertical\":\n if sign == 1:\n if A[1] < B[1]:\n return True\n else:\n return False\n else:\n if A[1] > B[1]:\n return True\n else:\n return False\n\n if slope == \"inclined\":\n if sign == 1:\n if A[1] < B[1]:\n return True\n else:\n return False\n else:\n if A[1] > B[1]:\n return True\n else:\n return False\n\n if slope == \"declined\":\n if sign == 1:\n if A[1] < B[1]:\n return True\n else:\n return False\n else:\n if A[1] > B[1]:\n return True\n else:\n return False"
] | [
"0.779486",
"0.6765233",
"0.6753991",
"0.6690972",
"0.66500854",
"0.65380234",
"0.65158004",
"0.64917606",
"0.6466559",
"0.64534605",
"0.63823503",
"0.63814336",
"0.6377494",
"0.6278903",
"0.62738436",
"0.6271943",
"0.62362576",
"0.6226385",
"0.6216552",
"0.62099683",
"0.62052274",
"0.6194367",
"0.61680937",
"0.6116131",
"0.6106082",
"0.6054897",
"0.6054121",
"0.60322857",
"0.6017895",
"0.598586"
] | 0.7685959 | 1 |
Determines the crossing number of a horizontal positive ray from point with a polygon defined in edges. | def crossing_number(point:tuple, edges:list, include_edges:bool=True)->int:
crossing_number = 0
for edge in edges:
d_y, d_x, b = line_equation(edge)
if include_edges and point_on_line(point, edge, d_y, d_x, b):
return 1
if is_horizontal(edge):
continue
if intersects_right(point, edge, d_y, d_x, b, positive_slope(edge), include_edges):
crossing_number += 1
return crossing_number | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def winding_number(x, y, primitive):\n\n wn = 0\n\n edges = zip(primitive[\"vertices\"][-1:] + primitive[\"vertices\"][:-1],\n primitive[\"vertices\"])\n for edge in edges:\n # check if cuts y parallel line at (x, y) &&\n if (edge[0][0] > x) != (edge[1][0] > x):\n # check what side of the edge is (x, y)\n # side > 0 => point is to de left of the edge\n # side = 0 => point is on the edge\n # side < 0 => point is to de right of the edge\n side = ((y - edge[0][1]) * (edge[1][0] - edge[0][0]) -\n (x - edge[0][0]) * (edge[1][1] - edge[0][1]))\n # if to the left, increase wn\n if side > 0: wn += 1\n # if to the right, decrease wn\n else: wn -= 1\n\n if wn != 0: return True\n return False",
"def ray_trace(x, y, poly):\n\n @vectorize([bool_(float64, float64)])\n def ray(x, y):\n # where xy is a coordinate\n n = len(poly)\n inside = False\n p2x = 0.0\n p2y = 0.0\n xints = 0.0\n p1x, p1y = poly[0]\n for i in range(n + 1):\n p2x, p2y = poly[i % n]\n if y > min(p1y, p2y):\n if y <= max(p1y, p2y):\n if x <= max(p1x, p2x):\n if p1y != p2y:\n xints = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x\n if p1x == p2x or x <= xints:\n inside = not inside\n p1x, p1y = p2x, p2y\n return inside\n\n return ray(x, y)",
"def check_point(point: Point, polygon: List[Point]):\n intersections = 0\n n = len(polygon)\n \n p1 = polygon[-1]\n # Checking every edge of the polygon inside for loop\n for i in range(n):\n p2 = polygon[i]\n # if point higher or lower than edge we immediately go to the next edge\n if min(p1.y, p2.y) <= point.y <= max(p1.y, p2.y):\n # Here goes the check for horizontal edge case\n if abs(point.y - p1.y) <= ATOL:\n if p1.y < p2.y:\n intersections += 1\n \n # Here goes the check for vertical edge case, if point to the left - it's an intersection\n elif abs(p2.x - p1.x) <= ATOL:\n if point.x < p2.x:\n intersections += 1\n # Here goes a \"regular\" edge case\n # Line equation is used to figure out does ray intersect the edge or not\n else:\n k = (p2.y - p1.y) / (p2.x - p1.x) # y = k*x + b -- line equation\n b = p1.y - k * p1.x\n x_of_point_y = (point.y - b) / k\n \n if point.x <= x_of_point_y:\n intersections += 1\n \n p1 = p2\n \n return intersections % 2 == 1",
"def testLocation(point, polygon):\n # begin\n if polygon.first.y == point.y and polygon.first.x == point.x:\n return \"on\" # vertex\n w =0\n for v in polygon.iter():\n if v.next.y == point.y:\n if v.next.x == point.x:\n return \"on\" # vertex\n else:\n if v.y == point.y and (v.next.x > point.x) == (v.x < point.x):\n return \"on\" # edge\n # if crossing horizontal line\n if (v.y < point.y and v.next.y >= point.y)\\\n or (v.y >= point.y and v.next.y < point.y):\n if v.x >= point.x:\n if v.next.x > point.x:\n # modify w\n if v.next.y > v.y: w += 1\n else: w -= 1\n else:\n det = (v.x - point.x) * (v.next.y - point.y) \\\n - (v.next.x - point.x) * (v.y - point.y)\n if det == 0: return \"on\" # edge\n # if right crossing\n if (det > 0 and v.next.y > v.y)\\\n or (det < 0 and v.next.y < v.y):\n # modify w\n if v.next.y > v.y: w += 1\n else: w -= 1\n else:\n if v.next.x > point.x:\n det = (v.x - point.x) * (v.next.y - point.y) \\\n - (v.next.x - point.x) * (v.y - point.y)\n if det == 0: return \"on\" # edge\n # if right crossing\n if (det > 0 and v.next.y > v.y)\\\n or (det < 0 and v.next.y < v.y):\n # modify w\n if v.next.y > v.y: w += 1\n else: w -= 1\n if (w % 2) != 0:\n return \"in\"\n else:\n return \"out\"",
"def is_in_polygon(self, point):\n reference_point = self.get_reference_point()\n \n reference_segment = DirectedEdge(point, reference_point)\n\n num_crossings = 0\n \n left_idx = 0\n while left_idx != len(self):\n right_idx = (left_idx + 1) % len(self)\n \n are_crossing = False\n \n if reference_segment.contains_point(self[left_idx]):\n while reference_segment.contains_point(self[right_idx]):\n right_idx = (right_idx + 1) % len(self)\n \n if right_idx == left_idx:\n break\n \n if left_idx == right_idx:\n left_idx = len(self)\n continue\n \n left_endpoint = self[(left_idx - 1) % len(self)]\n right_endpoint = self[(right_idx + 1) % len(self)]\n \n are_crossing = reference_segment.orientation(left_endpoint) != reference_segment.orientation(right_endpoint)\n left_idx = (right_idx + 1) % len(self) if left_idx < (right_idx + 1) % len(self) else len(self) \n elif reference_segment.contains_point(self[right_idx]):\n left_idx += 1\n continue\n else:\n edge = DirectedEdge(self[left_idx], self[right_idx])\n are_crossing = reference_segment.is_intersecting(edge)\n left_idx += 1\n \n num_crossings = num_crossings + 1 if are_crossing else num_crossings\n \n return num_crossings % 2 == 1",
"def polygon_area(x, y):\n return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))",
"def get_num_vertices(triangles):\n return numpy.amax(numpy.reshape(triangles, -1)) + 1",
"def findTriangles(p):\n triangleCount = 0\n for a in range(3, p//3 + 1):\n for b in range(a+1, p//2):\n c = p - (a+b)\n if (a**2 + b**2) == c**2:\n triangleCount += 1\n return triangleCount",
"def vertex_num(self, x, y):\n width, _ = self.size\n return 1 + (width*y) + x",
"def compute_triangle_area(vertices):\n v01 = vertices[0] - vertices[1]\n v02 = vertices[0] - vertices[2]\n cross_prod = np.cross(v01, v02)\n area = 0.5 * np.linalg.norm(cross_prod)\n return area",
"def edistw_to_line(point, edge, walls):\r\n#\tif min(x1,x2) <= x <= max(x1,x2) and min(y1,y2) <= y <= max(y1,y2):\r\n#\t\treturn 0\r\n\t(x,y) = point\r\n\t((x1,y1),(x2,y2)) = edge\r\n\tif x1 == x2:\r\n\t\tds = [math.sqrt((x1-x)**2 + (y3-y)**2) \\\r\n\t\t\tfor y3 in range(min(y1,y2),max(y1,y2)+1) \\\r\n\t\t\tif not racetrack.crash(((x,y),(x1,y3)), walls)]\r\n\telse:\r\n\t\tds = [math.sqrt((x3-x)**2 + (y1-y)**2) \\\r\n\t\t\tfor x3 in range(min(x1,x2),max(x1,x2)+1) \\\r\n\t\t\tif not racetrack.crash(((x,y),(x3,y1)), walls)]\r\n\tds.append(infinity)\r\n\treturn min(ds)",
"def get_index_under_point(self, event):\r\n xy = np.asarray(list(zip(self.xs, self.ys)))\r\n xyt = self.line.get_transform().transform(xy)\r\n xt, yt = xyt[:, 0], xyt[:, 1]\r\n d = np.sqrt((xt - event.x) ** 2 + (yt - event.y) ** 2)\r\n pt_idx = np.argmin(d)\r\n if d[pt_idx] >= self.max_pixels_from_vertex:\r\n pt_idx = None\r\n return pt_idx",
"def xymaxw_to_line(point, edge, walls):\r\n#\tif min(x1,x2) <= x <= max(x1,x2) and min(y1,y2) <= y <= max(y1,y2):\r\n#\t\treturn 0\r\n\t(x,y) = point\r\n\t((x1,y1),(x2,y2)) = edge\r\n\tif x1 == x2:\r\n\t\tds = [max(abs(x1-x), abs(y3-y)) \\\r\n\t\t\tfor y3 in range(min(y1,y2),max(y1,y2)+1) \\\r\n\t\t\tif not racetrack.crash(((x,y),(x1,y3)), walls)]\r\n\telse:\r\n\t\tds = [max(abs(x3-x), abs(y1-y)) \\\r\n\t\t\tfor x3 in range(min(x1,x2),max(x1,x2)+1) \\\r\n\t\t\tif not racetrack.crash(((x,y),(x3,y1)), walls)]\r\n\tds.append(infinity)\r\n\treturn min(ds)",
"def points_on_lines(hyperplanes):\n intersections = []\n for row in hyperplanes:\n intersections.append(an_intersection(row[:-1], -row[-1]))\n return np.array(intersections)",
"def pinp_crossing(point:tuple, edges:list, include_edges:bool=True)->bool:\n return crossing_number(point, edges, include_edges) % 2 == 1",
"def topography(x,y):\n \n z = -x/10\n \n N = len(x)\n for i in range(N):\n # Step\n if 10 < x[i] < 12:\n z[i] += 0.4 - 0.05*y[i]\n \n # Constriction\n if 27 < x[i] < 29 and y[i] > 3:\n z[i] += 2\n \n # Pole\n if (x[i] - 34)**2 + (y[i] - 2)**2 < 0.4**2:\n z[i] += 2\n \n return z",
"def is_in_polygon(x, y, xs, ys):\n\n xs = [xi - x for xi in xs]\n n = len(xs)\n assert n > 2\n xs.append(xs[0])\n ys = [yi - y for yi in ys]\n assert len(ys) == n\n ys.append(ys[0])\n th = 0\n for i in range(n):\n x1 = xs[i]\n y1 = ys[i]\n x2 = xs[i + 1]\n y2 = ys[i + 1]\n th += sign(x1 * y2 - y1 * x2) * _acos(\n (x1 * x2 + y1 * y2) / (hypot(x1, y1) * hypot(x2, y2))\n )\n return abs(th) > 1",
"def lines_up(x1, y1, x2, y2):\n if x1 == x2 and y1 == y2:\n return 4\n if x1 <= x2 and y1 >= y2:\n return 3\n if x1 >= x2 and y1 <= y2:\n return 2\n if (x2 <= x1 and x1 <= y2) or (x2 <= y1 and y1 <= y2):\n return 1\n if y1 < x2 or y2 < x1:\n return 0\n return 5",
"def len_func(polygon):\n ret=[]\n N=len(polygon)\n for i in range(1,N):\n l = ((polygon[i][0]-polygon[i-1][0])**2 + (polygon[i][1]-polygon[i-1][1])**2 )**0.5\n ret.append(l)\n l = ((polygon[0][0]-polygon[N-1][0])**2 + (polygon[0][1]-polygon[N-1][1])**2 )**0.5\n ret.append(l)\n return ret",
"def cross(p, n):\n # return (p[0] > p[1] and n[0] < n[1]) or (p[0] < p[1] and n[0] > n[1])\n if (p[0] > p[1] and n[0] < n[1]):\n return -1\n elif (p[0] < p[1] and n[0] > n[1]):\n return 1\n\n return 0",
"def edge_num(self,row1,col1,row2,col2):\n\n row = row1\n col = col1\n row_n = row2\n col_n = col2\n \n if row2 < row1 or col2 < col1:\n row = row2\n col = col2\n row_n = row1\n col_n = col1\n \n if not ((row == row_n and col == col_n - 1) or (row == row_n-1 and col == col_n)):\n return -1\n\n if row < 0 or row_n >= self.rows or col < 0 or col_n >= self.cols:\n return -1\n \n node1 = row*self.rows+col+1\n node2 = row_n*self.rows+col_n+1\n edge_number = self.edge2index[(node1,node2)]\n #print \"%s %s: %d\" % (str(node1),str(node2),edge_number)\n \"\"\"\n #THIS DOWN HERE WOULD WORK IF GRAPHILLION NUMBERED EDGES CORRECTLY BUT IT DOESNT\n #print \"(%d,%d) (%d,%d)\" % (row,col,row_n,col_n)\n if row + col < self.cols - 1:\n if col_n == col + 1: \n #print \"(%d,%d) (%d,%d)\" % (row, col, row, col + 1)\n edge_number = self.diags[row + col] + 2 * row\n #edges[edge_number] = 1\n elif row_n == row + 1:\n #print \"(%d,%d) (%d,%d)\" % (row, col, row + 1, col)\n edge_number = self.diags[row + col] + 1 + 2 * row\n #edges[edge_number] = 1\n else:\n col_dist = self.cols - col - 1\n if col_n == col + 1: \n #print \"(%d,%d) (%d,%d)\" % (row, col, row, col + 1)\n edge_number = self.diags[row + col] + 2 * col_dist - 1\n #edges[edge_number] = 1\n elif row_n == row + 1:\n #print \"(%d,%d) (%d,%d)\" % (row, col, row + 1, col)\n edge_number = self.diags[row + col] + 2 * col_dist\n #edges[edge_number] = 1\n \"\"\"\n\n return edge_number",
"def get_count_life_neighbor(arr, x, y, max_x, max_y):\n\tres_count = 0\n\n\tif x > 0 and y > 0:\n\t\tif arr[y-1][x-1]:\n\t\t\tres_count += 1\n\n\tif y > 0:\n\t\tif arr[y-1][x]:\n\t\t\tres_count += 1\n\n\tif y > 0 and x < max_x:\n\t\tif arr[y-1][x+1]:\n\t\t\tres_count += 1\n\n\tif x > 0:\n\t\tif arr[y][x-1]:\n\t\t\tres_count += 1;\n\n\tif x < max_x:\n\t\tif arr[y][x+1]:\n\t\t\tres_count += 1\n\n\tif y < max_y and x > 0:\n\t\tif arr[y+1][x-1]:\n\t\t\tres_count += 1\n\n\tif y < max_y:\n\t\tif arr[y+1][x]:\n\t\t\tres_count += 1\n\n\tif y < max_y and x < max_x:\n\t\tif arr[y+1][x+1]:\n\t\t\tres_count += 1\n\n\treturn res_count",
"def _triangle_areas(self, point):\n vertex_0, vertex_1, vertex_2 = self._vertices(point)\n len_edge_12 = gs.linalg.norm((vertex_1 - vertex_2), axis=-1)\n len_edge_02 = gs.linalg.norm((vertex_0 - vertex_2), axis=-1)\n len_edge_01 = gs.linalg.norm((vertex_0 - vertex_1), axis=-1)\n half_perimeter = 0.5 * (len_edge_12 + len_edge_02 + len_edge_01)\n return gs.sqrt(\n (\n half_perimeter\n * (half_perimeter - len_edge_12)\n * (half_perimeter - len_edge_02)\n * (half_perimeter - len_edge_01)\n ).clip(min=1e-6)\n )",
"def side_point(self, point: array_like) -> int:\n return int(np.sign(self.distance_point_signed(point)))",
"def find_centers(line_complex):\n # There is a line where the flux is at a minimum, i.e., the second\n # derivative is positive.\n diff2 = numpy.diff(numpy.sign(numpy.diff(line_complex)))\n zero_crossings = numpy.where(diff2 > 0.)[0]\n return zero_crossings + 1",
"def isPointInPolygon(xPolygon, yPolygon, xPt, yPt):\n \n # How to tell if a point is inside a polygon:\n # Determine the change in angle made by the point and the vertices\n # of the polygon. Add up the delta(angle)'s from the first (include\n # the first point again at the end). If the point is inside the\n # polygon, then the total angle will be +/-360 deg. If the point is\n # outside, then the total angle will be 0 deg. Points on the edge will\n # outside.\n # This is called the Winding Algorithm\n # http://geomalgorithms.com/a03-_inclusion.html\n\n n = len(xPolygon)\n # Array for the angles\n angle = np.zeros(n)\n\n # add first vertex to the end\n xPolygon1 = np.append( xPolygon, xPolygon[0] )\n yPolygon1 = np.append( yPolygon, yPolygon[0] )\n\n wn = 0 # winding number counter\n\n # Loop through the edges of the polygon\n for i in range(n):\n # if edge crosses upward (includes its starting endpoint, and excludes its final endpoint)\n if yPolygon1[i] <= yPt and yPolygon1[i+1] > yPt:\n # if (P is strictly left of E[i]) // Rule #4\n if isLeft(xPolygon1[i], yPolygon1[i], xPolygon1[i+1], yPolygon1[i+1], xPt, yPt) > 0: \n wn += 1 # a valid up intersect right of P.x\n\n # if edge crosses downward (excludes its starting endpoint, and includes its final endpoint)\n if yPolygon1[i] > yPt and yPolygon1[i+1] <= yPt:\n # if (P is strictly right of E[i]) // Rule #4\n if isLeft(xPolygon1[i], yPolygon1[i], xPolygon1[i+1], yPolygon1[i+1], xPt, yPt) < 0: \n wn -= 1 # a valid up intersect right of P.x\n\n # wn = 0 only when P is outside the polygon\n if wn == 0:\n return False\n else:\n return True",
"def collision_detection(p, poly):\r\n _eps = 0.00001\r\n _huge = sys.float_info.max\r\n _tiny = sys.float_info.min\r\n \r\n def rayintersectseg(p, edge):\r\n ''' takes a point p=Pt() and an edge of two endpoints a,b=Pt() of a line segment returns boolean\r\n '''\r\n a,b = edge\r\n if a.y > b.y:\r\n a,b = b,a\r\n if p.y == a.y or p.y == b.y:\r\n p = Pt(p.x, p.y + _eps)\r\n \r\n intersect = False\r\n \r\n if (p.y > b.y or p.y < a.y) or (\r\n p.x > max(a.x, b.x)):\r\n return False\r\n \r\n if p.x < min(a.x, b.x):\r\n intersect = True\r\n else:\r\n if abs(a.x - b.x) > _tiny:\r\n m_red = (b.y - a.y) / float(b.x - a.x)\r\n else:\r\n m_red = _huge\r\n if abs(a.x - p.x) > _tiny:\r\n m_blue = (p.y - a.y) / float(p.x - a.x)\r\n else:\r\n m_blue = _huge\r\n intersect = m_blue >= m_red\r\n return intersect\r\n \r\n def _odd(x): return x%2 == 1\r\n \r\n def ispointinside(p, poly):\r\n\r\n return _odd(sum(rayintersectseg(p, edge)\r\n for edge in poly.edges ))\r\n \r\n detection = ispointinside(p,poly)\r\n return detection",
"def test_triangle_count_05(self):\n body = {\"direction\": \"IN\", \"degree\": -1}\n code, res = Algorithm().post_triangle_count(body, auth=auth)\n id = res[\"task_id\"]\n if id > 0:\n result = get_task_res(id, 120, auth=auth)\n print(result)\n assert result == {'edges_in': 13, 'vertices_in': 9, 'triangles': 2}\n else:\n assert 0",
"def compute_inters(box, boxes, box_area):\n # Calculate intersection areas\n y1 = np.maximum(box[0], boxes[:, 0])\n y2 = np.minimum(box[2], boxes[:, 2])\n x1 = np.maximum(box[1], boxes[:, 1])\n x2 = np.minimum(box[3], boxes[:, 3])\n return np.divide(np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0),box_area)",
"def trapezoidal_rule(x, y):\r\n index = [i+1 for i in xrange(len(x)-1)]\r\n xdiff = np.array([x[i]-x[i-1] for i in index])\r\n ysum = np.array([y[i]+y[i-1] for i in index])\r\n return(np.dot(xdiff,ysum)/2)"
] | [
"0.6319946",
"0.628875",
"0.61075354",
"0.6013507",
"0.5910155",
"0.56875455",
"0.5654235",
"0.56247514",
"0.5608675",
"0.5508915",
"0.54895514",
"0.54782134",
"0.5462136",
"0.54489154",
"0.54295504",
"0.54053026",
"0.5375274",
"0.5368317",
"0.5356745",
"0.5355982",
"0.5348883",
"0.5348785",
"0.53487045",
"0.5330066",
"0.53199935",
"0.5310517",
"0.52887785",
"0.52854794",
"0.52774495",
"0.5261784"
] | 0.76824135 | 0 |
Select the longest edge from hull that doesn't start with a point in ignore_left_points, with minimum length. Returns | def select_longest_edge(hull:list, ignore_left_points:list, min_sqr_length:int=0)->tuple:
max_sqr_length = None
selected = None
for k in range(0, len(hull) - 1):
if hull[k] in ignore_left_points:
continue
edge_sqr_length = point_sqr_distance(hull[k], hull[k+1])
if edge_sqr_length < min_sqr_length:
ignore_left_points.append(hull[k])
continue
if max_sqr_length is None or edge_sqr_length > max_sqr_length:
max_sqr_length = edge_sqr_length
selected = k
if not(max_sqr_length is None):
return selected, (hull[selected], hull[selected + 1])
else:
return None, None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def sort_hull(hull):\n max_unproc_edge = hull[np.lexsort((-hull.length, hull.is_processed))][0]\n idx = np.where(hull == max_unproc_edge)[0][0]\n\n # shift convex hull to have the longest edge at the beginning\n hull = np.roll(hull, -idx, axis=0)\n\n return hull, max_unproc_edge.length",
"def concave_hull(hull:list, points:list, max_iterations:int=None, min_length_fraction:float=0, min_angle:float=90)->list:\n tweet.info(\"Creating concave hull; minimum side length {}% of average, minimum_angle {}\".format(min_length_fraction * 100, min_angle))\n test_points = set(points)\n ignore_points = []\n avg_sqr_distance = 0\n for k in range(0, len(hull)-1):\n avg_sqr_distance += point_sqr_distance(hull[k], hull[k+1])\n test_points.remove(hull[k])\n avg_sqr_distance /= len(hull) - 1\n min_sqr_length = avg_sqr_distance * (min_length_fraction ** 2) # since we get sqr_length, we square the fraction\n min_cosine = math.cos(math.radians(min_angle))\n \n while (max_iterations is None or max_iterations > 0) and test_points:\n selection, edge = select_longest_edge(hull, ignore_points, min_sqr_length)\n tweet.info(\"Considering edge {}; {} points left\".format(edge, len(test_points)))\n if selection is None:\n break\n selected_point = select_candidate_point(edge, test_points, hull, min_cosine)\n if selected_point is None:\n # This edge has no more candidate points, so we ignore it in the next pass\n ignore_points.append(edge[0])\n tweet.debug(\"No candidate point found.\")\n continue\n tweet.debug(\"Found point {}, inserting new edge.\".format(selected_point))\n if not max_iterations is None:\n max_iterations -= 1\n # We add the point into the concave hull\n hull.insert(selection + 1, selected_point)\n test_points.remove(selected_point)\n return hull",
"def edges_left(self):\n return self._edges_left",
"def jarvis_convex_hull(points):\n start_index = np.argmax(points[:, 0]) # Point with the highest y-coordinate\n start_point = points[start_index]\n # result = [start_index[:]]\n result = [start_index]\n added_points = {start_index}\n while True:\n for ref_index, ref_point in enumerate(points):\n exit_ = True\n if ref_index == start_index or ref_index in added_points:\n continue\n\n signs = 0\n threshold = len(points) - 2\n for compare_index, compare_point in enumerate(points):\n if compare_index == ref_index or compare_index == start_index:\n continue\n check = compare(start_point, ref_point, compare_point)\n if abs(check) < 1e-2:\n dist_start_ref = distance(start_point, ref_point)\n dist_start_compare = distance(start_point, compare_point)\n if dist_start_compare > dist_start_ref:\n threshold = threshold + 1\n else:\n threshold = threshold - 1\n continue\n signs = signs + 1 if check > 0 else signs - 1\n\n if abs(signs) < threshold:\n continue\n\n exit_ = False\n result.append(ref_index[:])\n added_points.add(ref_index)\n start_index = ref_index\n break\n\n if exit_:\n return result",
"def edgecomplete_left_vertex(self, X, w):\n h = self.op_norm(X, w[0])\n if self.K.is_zero(h):\n return None\n h -= w[1]\n if self.variant == NormGraphVariant.NG and w == (X, h):\n return None\n return h",
"def optimize_left(connect):\n if intersect(connect[0], connect[1], connect[2]) == False:\n return connect\n else:\n connect = connect_left(connect[0], connect[2])\n if intersect(connect[0], connect[1], connect[2]) == True:\n return optimize_left(connect)\n else:\n return connect",
"def longest_line(points, inlier_dist, max_separation):\n points = np.asarray(points)\n assert points.ndim == 2 and points.shape[1] == 2\n npts = len(points)\n best = min(1, npts)\n for i in range(npts - 1):\n for j in range(i + 1, npts):\n # draw a line (p_i -> p_j) and find all the inliers for that line\n pi = points[i]\n offs = points - pi[None]\n pj_off = offs[j]\n pj_unit = pj_off / np.linalg.norm(pj_off)\n proj_lens = np.squeeze(offs @ pj_unit[:, None], axis=1)\n assert len(proj_lens) == len(points)\n dists = np.linalg.norm(offs - proj_lens[:, None] * pj_unit, axis=1)\n inlier_inds, = np.nonzero(dists <= inlier_dist)\n if len(inlier_inds) <= best:\n continue\n\n # now that we've found the inliers, find the largest subsequence of\n # inliers that are separated by a distance of at most\n # max_separation along the line\n inlier_proj_lens = proj_lens[inlier_inds]\n inlier_proj_lens.sort()\n seps = np.abs(np.diff(inlier_proj_lens))\n # find longest run of nearby shapes\n all_runs = it.groupby(seps <= max_separation)\n one_run_lens = [len(list(r)) for v, r in all_runs if v]\n max_run = max(one_run_lens, default=0) + 1\n if max_run > best:\n best = max_run\n\n return best",
"def find_hull_vertices(points: np.ndarray) -> np.ndarray:\n M = 3\n N = points.shape[0]\n for i in range(4, N):\n while ccw(points[M], points[M - 1], points[i]) >= 0:\n M -= 1\n\n M += 1\n swap(points, M, i)\n\n return points[1:M + 1]",
"def smallest_r(points, pval):\n\n N = points.shape[0]\n n = points.shape[1]\n\n meshed = [np.meshgrid(points[i, :], points[i, :]) for i in range(N)]\n diffs = np.array([cols-rows for rows, cols in meshed])\n box_cube_condition = (diffs > 0).all(axis=0)\n distsp = (diffs**pval).sum(axis=0)\n\n nolimit_connections = (distsp**(1/pval))*box_cube_condition\n nolimit_connections = np.nan_to_num(nolimit_connections)\n \n maxes, prev = {}, {}\n\n for i in range(n):\n maxes[i] = np.inf\n maxes[n-2] = 0\n \n for u in topo_sort(nolimit_connections): #can replace the top sort with points sorting\n for v in np.nonzero(nolimit_connections[:, u])[0]:\n\n alt = max(maxes[u], nolimit_connections[v, u])\n \n if alt < maxes[v]:\n\n maxes[v] = alt\n prev[v] = u\n\n u = n-1\n\n path=[]\n path.append(u)\n \n if prev.get(u) is not None:\n while u != n-2:\n u = prev[u]\n path.append(u)\n\n return path, maxes[n-1]\n\n else:\n return [], 0.0",
"def get_corner_node_prune(lcurve):\r\n rho, eta = np.zeros(len(lcurve)), np.zeros(len(lcurve))\r\n for lia in range(len(lcurve)):\r\n rho[lia] = lcurve[lia][0]\r\n eta[lia] = lcurve[lia][1]\r\n\r\n if len(rho) != len(eta):\r\n raise ValueError(\"both arrays must have the same size\")\r\n fin = np.isfinite(rho + eta)\r\n nzr = np.array([False]*len(rho))\r\n nzr[np.nonzero(rho*eta)[0]] = True\r\n keep = fin & nzr\r\n if len(keep) < 1:\r\n raise ValueError(\"To few accepted data found\")\r\n if len(keep) < len(rho):\r\n print(\"I had to trim the data due to NaN/Inf or zero values\")\r\n rho = rho[keep]\r\n eta = eta[keep]\r\n if np.any(rho[:-1] < rho[1:]) or np.any(eta[:-1] > eta[1:]):\r\n print(\"Warning: L-curve lacks monotonicity\")\r\n nP = len(rho) # number of points\r\n P = np.log10(np.array([rho, eta])).T # Coordinates of the loglog L-curve\r\n V = P[1:, :] - P[:-1, :] # The vectors defined by these coord\r\n v = np.sqrt(np.sum(V**2, axis=1)) # length of the vectors\r\n # W = V/np.tile(v, (1, 2)); # Normalized vectors.\r\n W = np.zeros(V.shape)\r\n W[:, 0] = V[:, 0]/v\r\n W[:, 1] = V[:, 1]/v\r\n clist = [] # list of condidates\r\n p = np.min([5, nP]) # number of vectors in pruned L-curve\r\n # convex = 0 # Are the pruned L-curves convex\r\n Ind = np.argsort(v)[::-1] # Sort lengths decending\r\n while p < (nP-1)*2:\r\n elmts = np.sort(Ind[:np.min([p, nP-1])])\r\n candidate = Angles(W[elmts, :], elmts)\r\n # print(\"candidate p={}, {}\".format(p, candidate))\r\n if candidate not in clist:\r\n clist.append(candidate)\r\n candidate = Global_Behaviour(P, W[elmts, :], elmts)\r\n if candidate not in clist:\r\n clist.append(candidate)\r\n p = p*2\r\n # print(clist)\r\n if 0 not in clist:\r\n clist.insert(0, 0)\r\n clist = np.sort(clist)\r\n\r\n vz = np.argwhere(np.diff(P[clist, 1]) >= np.abs(np.diff(P[clist, 0])))\r\n if len(vz) > 1:\r\n if vz[0] == 0:\r\n vz = vz[1:]\r\n elif len(vz) == 1:\r\n if vz[0] == 0:\r\n vz = []\r\n if vz == [] or len(vz) == 0:\r\n # if vz.size <= 0:\r\n index = clist[-1]\r\n else:\r\n vects = np.array([P[clist[1:], 0] - P[clist[:-1], 0], P[clist[1:], 1] - P[clist[:-1], 1]]).T\r\n vects = np.dot(np.diag(1/np.sqrt(np.sum(vects**2, 1))), vects)\r\n delta = vects[:-1, 0] * vects[1:, 1] - vects[1:, 0] * vects[:-1, 1]\r\n vv = np.argwhere(delta[vz-1] <= 0)\r\n # print(vv)\r\n # print(vz)\r\n if vv == [] or len(vv) == 0:\r\n # if vv.size <= 0:\r\n index = clist[vz[-1]]\r\n else:\r\n index = clist[vz[vv[0]]]\r\n\r\n try:\r\n retval = int(index)\r\n except TypeError:\r\n print(\"index!!!!: {}\".format(index))\r\n retval = int(index[0])\r\n return retval",
"def _get_minimal_lanes(self):\n return np.argwhere(self.end_of_lanes == np.min(self.end_of_lanes)).flatten()",
"def convex_hull(l):\n\tpass",
"def sort_for_graham_scan(points: np.ndarray, primary: np.ndarray) -> np.ndarray:\n point_slopes = np.array([v[1] / v[0] for v in points])\n sorted_indexes = np.argsort(point_slopes)\n sorted_points = np.array(points)[sorted_indexes]\n hull = np.concatenate(\n (sorted_points[-1:], [primary], sorted_points)\n )\n return hull",
"def get_max_length_diff_in_quad(points):\n leftmost, uppermost, rightmost, bottommost = (points[0, 0] for i in range(4))\n for point in points:\n x = point[0, 0]\n y = point[0, 1]\n if x < leftmost[0]:\n # Point is located on the left side of leftmost point\n leftmost = point[0]\n elif x > rightmost[0]:\n rightmost = point[0]\n elif y < uppermost[1]:\n uppermost = point[0]\n elif y > bottommost[1]:\n bottommost = point[0]\n\n length_diff = [cv2.norm(uppermost - leftmost),\n cv2.norm(rightmost - uppermost),\n cv2.norm(bottommost - rightmost),\n cv2.norm(leftmost - bottommost)]\n return np.max(length_diff)",
"def find_closest_interior_node(arc, hull, nodes):\n lengths = [float(\"inf\") for x in range(len(nodes))]\n for (j, node) in enumerate(nodes):\n if not node.nid in hull:\n i = hull.index(arc[1])\n hull.insert(i, node.nid)\n lengths[j] = (tsputil.get_path_length(nodes, 100, hull))\n hull.pop(i)\n return lengths.index(min(lengths))",
"def select_candidate_point(edge:tuple, points:list, hull:list, min_cosine:float=-1)->tuple:\n min_sqr_distance = None\n selected = None\n for point in points:\n nearest_point = closest_line_point(point, edge)\n if not near_segment(nearest_point, edge):\n # We ignore points that wouldn't be above or below the edge if rotated horizontal\n continue\n sqr_distance = point_sqr_distance(nearest_point, point)\n if not(min_sqr_distance is None) and min_sqr_distance < sqr_distance:\n # We ignore points that aren't a candidate for minimum distance\n continue\n vector_a = vectorize(edge[0], point)\n vector_b = vectorize(edge[1], point)\n cos_angle = vector_cosine_angle(vector_a, vector_b)\n if cos_angle is None or cos_angle > min_cosine:\n # We ignore points that would make an angle smaller (tighter) than the minimum angle.\n continue\n new_segments = [(edge[0], point), (point, edge[1])]\n if segments_intersects_hull(new_segments, hull, edge):\n # We ignore points that would cause the hull to self-intersect\n continue\n selected = point\n min_sqr_distance = sqr_distance\n return selected",
"def _get_potential_left_way(self, lanelet):\n if lanelet.adj_left:\n if lanelet.adj_left_same_direction:\n potential_left_way = self.right_ways.get(lanelet.adj_left)\n else:\n potential_left_way = self.left_ways.get(lanelet.adj_left)\n if potential_left_way:\n adj_left = self.lanelet_network.find_lanelet_by_id(lanelet.adj_left)\n vertices = (\n adj_left.right_vertices\n if lanelet.adj_left_same_direction\n else adj_left.left_vertices[::-1]\n )\n if _vertices_are_equal(lanelet.left_vertices, vertices):\n return potential_left_way\n\n return None",
"def graham_scan(points):\n\n # Find point with smallest y coordinate\n # If two points have equal y coordinates, select the one with the lower x-coordinate\n smallest = points[0]\n for p in points:\n if p[1] < smallest[1]:\n smallest = p\n elif p[1] == smallest[1]:\n if p[0] < smallest[0]:\n smallest = p\n\n # Sort points by angle over smallest to x-axis\n points.sort(key=lambda x: angle(x, smallest))\n\n # Our stack\n hull = [smallest, points[1]]\n i = 2\n while i < len(points):\n # If the last points and the new point form a counter-clockwise triangle,\n # we need the last point. Therefore, push the new point\n if ccw(hull[-2], hull[-1], points[i]) > 0 or len(hull) == 2:\n hull.append(points[i])\n i += 1\n # If the two last points and the new point don't form a counter-clockwise triangle,\n # the we don't need the last point\n else:\n hull.pop()\n return hull",
"def furthest_right_point(list_of_points):\n return max(list_of_points, key = lambda pt: pt.getX())",
"def convex_hull(self):\n nodes = self._datacontroller.get_data('nodes')\n scale = self._datacontroller.get_data('scale')\n hull = tsputil.convex_hull_helper(nodes)\n if hull:\n result = construct_step(hull, 'Most Top Left Node', 'Clockwise', nodes, scale)\n self._datacontroller.commit_change('path', result)",
"def _get_left_height(self):\n if self.left is None:\n return 0\n return 1 + max(\n self.left._get_left_height(),\n self.left._get_right_height(),\n )",
"def shrink_vertex(hull_vertices, inside, shrinking_threshold):\n hull = create_hull(hull_vertices)\n hull, max_edge_length = sort_hull(hull)\n avg_edge_length = average_distance(inside)\n\n if max_edge_length < avg_edge_length:\n # mark current hull as released, compute new hull from remaining points\n new_hull_vertices, inside = convex_hull(inside)\n new_hull_vertices, released = shrink_vertex(new_hull_vertices, inside)\n return new_hull_vertices, np.append(released, hull_vertices, axis=0)\n\n all_points = np.append(inside, hull_vertices, axis=0)\n\n if len(all_points) < 3:\n # nothing to shrink\n return hull.vertex, np.zeros((0, 2))\n\n while max_edge_length >= shrinking_threshold * avg_edge_length:\n V1 = hull[0].vertex\n V2 = hull[1].vertex\n V21 = V2 - V1\n V21dot = np.dot(V21, V21)\n\n edges = list(\n zip(hull.vertex[1:],\n np.append(hull.vertex[2:], [hull.vertex[0]], axis=0)))\n\n candidates = []\n for P in all_points:\n # find closest point from x to the line between V1 and V2:\n # 1) its projection falls between V1 and V2\n # 2) it resides on the left of V1 and V2\n # 3) the perpendicular line from P to the line between V1 and V2\n # doesn't have an intersection with other edges between vertices\n\n PV1 = P - V1\n u = np.dot(PV1, V21) / V21dot\n\n if not (0-eps <= u <= 1+eps):\n # 1) failed\n continue\n\n M = np.vstack((np.array([V1, V2, P]).T,[1,1,1]))\n if np.linalg.det(M) <= 0+eps:\n # 2) failed\n continue\n\n # get projected point\n PP = V1 + u*V21\n PPP = PP - P\n\n num_intersections = 0\n for i, edge in enumerate(edges):\n\n if array_equal(P, edge[0]) or array_equal(P, edge[1]):\n # a point always intersects with its own edge\n continue\n\n has_intersec = seg_intersect(P, PPP, edge[0], edge[1]-edge[0])\n if not has_intersec:\n # no intersection with this edge\n continue\n\n # we found an intersection. These are only allowed if the\n # candidate vertex is either the V_last or V3...\n if array_equal(P, hull[-1].vertex) or \\\n array_equal(P, hull[2].vertex):\n continue\n\n # otherwise this is an invalid intersection\n num_intersections += 1\n if num_intersections > 1:\n # only one intersection is allowed at max\n # (see condition below)\n break\n\n if num_intersections == 0 or \\\n num_intersections == 1 and (0-eps <= u <= 0+eps or\n 1-eps <= u <= 1+eps):\n # add point if it has no intersection or the only intersection\n # is at V1 or V2. This happens if u == 0 or u == 1.\n candidates.append((P, dist(P, PP)))\n\n if len(candidates) == 0:\n # no candidate for shrinking found\n hull[0].is_processed = True\n\n if all(hull.is_processed):\n # finished search\n break\n else:\n # add closest point to hull between V1 and V2\n Q = min(candidates, key = lambda t: t[1])[0]\n # update edge length\n hull[0].length = dist(V1, Q)\n hull = np.insert(hull, 1, (Q, dist(Q, V2), False), axis=0)\n\n hull, max_edge_length = sort_hull(hull)\n\n # the original releasing has not been implemented -> return an empty array\n return hull.vertex, np.zeros((0, 2))",
"def extract_1d_boundaries(xy, NL, KL, BL, PVx, PVy, check=False):\n if PVx is None and PVy is None:\n raise RuntimeError('Not designed to allow openBC networks.')\n # PVx = np.zeros_like(KL, dtype=float)\n # PVy = np.zeros_like(KL, dtype=float)\n\n # If there are dangling points, remove them for now and adjust indices later\n dangles, xy, NL, KL, BL, backtrans = remove_dangling_points(xy, NL, KL, BL, check=check)\n # If no dangling bonds, no need to translate indices at the end\n translate_at_end = len(dangles) > 0\n\n # Initialize the list of boundary indices to be larger than necessary\n boundaries = []\n for boundaryloc in ['top', 'bottom']:\n # Initialize the boundary list to be as long as possible (will truncate later)\n bb = np.zeros(2 * len(xy), dtype=int)\n if boundaryloc == 'top':\n # Start with the topmost point, which is guaranteed to be\n # at the convex hull and thus also at the top outer edge.\n # Then take the first step to be along the minimum angle bond\n rightIND = np.where(xy[:, 1] == np.max(xy[:, 1]))[0]\n # If there are more than one rightmost point, choose one\n if rightIND.size > 1:\n rightIND = rightIND[0]\n else:\n # Start with the bottom most point, which is guaranteed to be\n # at the convex hull and thus also at the bottom outer edge.\n # Then take the first step to be along the minimum angle bond\n rightIND = np.where(xy[:, 1] == np.min(xy[:, 1]))[0]\n # If there are more than one rightmost point, choose one\n if rightIND.size > 1:\n rightIND = rightIND[0]\n\n if check:\n print 'le.extract_1d_boundaries(): Found extremal pt: ', rightIND\n print 'le.extract_1d_boundaries(): with neighbors: ', NL[rightIND]\n print 'le.extract_1d_boundaries(): with connectns: ', KL[rightIND]\n plt.plot(xy[:, 0], xy[:, 1], 'k.')\n plt.plot(xy[rightIND, 0], xy[rightIND, 1], 'bo')\n for ii in range(len(xy)):\n plt.text(xy[ii, 0] + 0.1, xy[ii, 1], str(ii))\n plt.plot(xy[rightIND, 0], xy[rightIND, 1], 'ro')\n plt.pause(0.01)\n\n # Grab the true neighbors of this starting point\n # print 'le.extract_boundary(): NL[rightIND, :] = ', NL[rightIND, :]\n connect = np.argwhere(np.abs(KL[rightIND]).ravel()).ravel()\n neighbors = NL[rightIND, connect]\n if check:\n print 'le.extract_1d_boundaries(): neighbors = ', neighbors\n print 'le.extract_1d_boundaries(): rightIND = ', rightIND\n\n # Compute the angles of the neighbor bonds\n angles = np.mod(np.arctan2(xy[neighbors, 1] - xy[rightIND, 1] + PVy[rightIND, connect],\n xy[neighbors, 0] - xy[rightIND, 0] + PVx[rightIND, connect]).ravel(),\n 2 * np.pi)\n if check:\n print 'le.extract_1d_boundaries(): KL[rightIND] = ', KL[rightIND]\n print 'le.extract_1d_boundaries(): KL[rightIND,0] = ', KL[rightIND, 0]\n print 'le.extract_1d_boundaries(): KL[rightIND,0] ==0 ', KL[rightIND, 0] == 0\n print 'le.extract_1d_boundaries(): np.argwhere(KL[rightIND]) = ', np.argwhere(KL[rightIND])\n print 'le.extract_1d_boundaries(): np.argwhere(KL[rightIND].ravel())= ', np.argwhere(KL[rightIND].ravel())\n print 'le.extract_1d_boundaries(): neighbors = ', neighbors\n print 'le.extract_1d_boundaries(): angles = ', angles\n\n # Assign this pvx and pvy as pvx_prev and pvy_prev for next time around.\n # Note that this must preceed the redefinition of nextIND\n pvx_prev = PVx[rightIND, connect[angles == min(angles)][0]]\n pvy_prev = PVy[rightIND, connect[angles == min(angles)][0]]\n\n # Take the second particle to be the one with the lowest bond angle (will be >= pi/2)\n nextIND = neighbors[angles == min(angles)][0]\n bb[0] = rightIND\n\n dmyi = 1\n # as long as we haven't completed the full outer edge/boundary, add nextIND\n while nextIND != rightIND:\n # print '\\n nextIND = ', nextIND\n # print 'np.argwhere(KL[nextIND]) = ', np.argwhere(KL[nextIND]).ravel()\n bb[dmyi] = nextIND\n connect = np.argwhere(np.abs(KL[nextIND]).ravel())\n n_tmp = NL[nextIND, connect]\n\n # Get position in row of NL where NL == bb[dmyi - 1] (the previous boundary particle/site)\n # and where the PVx and PVy are opposite of the last used PVx and PVy values (to make sure we\n # are looking backwards along the boundary). We will use this to get the 'backward angle' -- the\n # angle of the previous bond in the boundary\n # Note that bb[dmyi - 1] may have been index 0, so there could be multiple matches\n nlpos = np.where(np.logical_and(NL[nextIND] == bb[dmyi - 1],\n np.abs(KL[nextIND]).ravel().astype(bool)))[0]\n if len(nlpos) > 1:\n # There is more than one connection to the previous particle. Check for where PVx and PVy\n # values are opposite the previously used values.\n ind_nlpos = np.where(np.logical_and(PVx[nextIND, nlpos] == -pvx_prev,\n PVy[nextIND, nlpos] == -pvy_prev))[0]\n print 'ind_nlpos = ', ind_nlpos\n nlpos = nlpos[ind_nlpos]\n\n # Exclude previous boundary particle (the copy of that particle in the nlpos position)\n # from the neighbors array, UNLESS IT IS THE ONLY ONE,\n # since its angle with itself is zero!\n\n # Used to remove previous particle, but this assumes that boundary is more than 2\n # particles long, which might not be true for periodic_strip bcs\n if len(n_tmp) == 1:\n print 'le: The bond is a lone bond, not part of a triangle.'\n neighbors = n_tmp\n else:\n print 'n_tmp = ', n_tmp\n neighbors = np.delete(n_tmp, nlpos)\n connect = np.delete(connect, nlpos)\n print 'n_tmp = ', n_tmp\n print 'neighbors = ', neighbors\n\n # print 'le: nlpos = ', nlpos\n forward_angles = np.arctan2(xy[neighbors, 1] - xy[nextIND, 1] + PVy[nextIND, connect],\n xy[neighbors, 0] - xy[nextIND, 0] + PVx[nextIND, connect]).ravel()\n backward_angle = np.arctan2(xy[bb[dmyi - 1], 1] - xy[nextIND, 1] + PVy[nextIND, nlpos],\n xy[bb[dmyi - 1], 0] - xy[nextIND, 0] + PVx[nextIND, nlpos]).ravel()\n if check:\n print 'le: connect = ', connect\n print 'le: forward_angles = ', forward_angles\n print 'le: backward_angle = ', backward_angle\n\n angles = np.mod(forward_angles - backward_angle, 2 * np.pi)\n if check:\n print 'le: angles = ', angles\n print 'le: angles==min--> ', angles == min(angles)\n print 'le: neighbors = ', neighbors\n print 'le.extract_1d_boundaries(): angles==min--> ', angles == min(angles)\n print 'le.extract_1d_boundaries(): neighbors[angles == min(angles)] --> ', neighbors[angles == min(angles)]\n\n # Assign this pvx and pvy as pvx_prev and pvy_prev for next time around.\n # Note that this must preceed the redefinition of nextIND\n pvx_prev = PVx[nextIND, connect[angles == min(angles)][0]]\n pvy_prev = PVy[nextIND, connect[angles == min(angles)][0]]\n # Redefine nextIND to be the new boundary index\n nextIND = neighbors[angles == min(angles)][0]\n # print 'nextIND = ', nextIND\n\n if check:\n # plt.plot(xy[:,0],xy[:,1],'k.')\n XY = np.vstack([xy[bb[dmyi], :], xy[nextIND, :]])\n plt.plot(XY[:, 0], XY[:, 1], 'r-')\n # for i in range(len(xy)):\n # plt.text(xy[i,0]+0.2,xy[i,1],str(i))\n plt.gca().set_aspect('equal')\n plt.pause(0.01)\n\n dmyi += 1\n\n # Truncate the list of boundary indices\n boundary = bb[0:dmyi]\n\n # Since some points were removed from the boundary identification, translate\n # indices back to indices of original xy\n if translate_at_end:\n print 'le.extract_boundary(): Translating boundary points back into original indices...'\n # print 'boundary = ', boundary\n # print 'translation = ', translation\n # print 'backtrans = ', backtrans\n boundary = backtrans[boundary]\n\n boundaries.append(boundary)\n\n return tuple(boundaries)",
"def get_outer_boundary_of_voronoi(self):\n edge = [edge for edge in self.edges if not edge.nxt][0]\n # next(obj for obj in objs if obj.val==5)\n first_vertex = edge.origin\n outer_boundary = []\n while (not edge.get_destination() == first_vertex):\n if(edge.get_destination().is_infinity()):\n edge = edge.twin.nxt\n else:\n outer_boundary.append(edge)\n edge = edge.nxt\n outer_boundary.append(edge)\n return outer_boundary",
"def longest_flight(self):\r\n distance = 0\r\n for code, _list in self.edges.items():\r\n for edge in _list:\r\n if edge.distance > distance:\r\n distance = edge.distance\r\n start = edge.start\r\n destination = edge.destination\r\n return start, destination, distance",
"def _FindHull(s: List[sg.Point2], p: sg.Point2, q: sg.Point2, hull_points: List[sg.Point2]):\n if len(s) == 0:\n return\n seg = sg.Segment2(p, q)\n c = max(s, key=lambda point: sg.squared_distance(seg, point))\n hull_points.insert(hull_points.index(p) + 1, c)\n s.remove(c)\n s1, s2 = split_points_triangle(s, (p, q, c))\n _FindHull(s1, p, c, hull_points)\n _FindHull(s2, c, q, hull_points)",
"def combine_hulls(self, left, right, side, left_most, right_most):\n upper_left = 0\n upper_right = 0\n updated = True\n\n # Worst case this while loop runs max(n, m) times if each hull is an arc\n # i.e. O(n(n+m)) or O(m(n+m)) \n while updated:\n # Worst case 5(n-1 + m-1) + 6 => O(n+m)\n updated = False\n\n # 3 operations in calc_slope\n left_slope = self.calc_slope(left[upper_left], right[upper_right])\n init_upper_left = upper_left\n\n # 5(n-1) => O(n)\n for i in range(init_upper_left+1, len(left)):\n # 3 operations in calc_slope\n left_new_slope = self.calc_slope(left[i], right[upper_right])\n\n # Max 2 operations \n if left_new_slope > left_slope:\n upper_left = i - 1\n break\n else:\n updated = True\n upper_left = i\n left_slope = left_new_slope\n\n # 3 operations in calc_slope\n right_slope = self.calc_slope(left[upper_left], right[upper_right])\n init_upper_right = upper_right\n\n # 5(m-1) => O(m)\n for i in range(init_upper_right+1, len(right)):\n # 3 operations in calc_slope\n right_new_slope = self.calc_slope(left[upper_left], right[i])\n\n # Max 2 operations\n if right_new_slope < right_slope:\n upper_right = i - 1\n break\n else:\n updated = True\n upper_right = i\n right_slope = right_new_slope\n \n # Calculate lower common tangent\n lower_left = 0\n lower_right = 0\n updated = True\n\n # Same as last while loop => O(n(n+m)) or O(m(n+m)) \n while updated:\n updated = False\n left_slope = self.calc_slope(left[-lower_left], right[-lower_right])\n init_lower_left = lower_left\n for i in range(init_lower_left+1, len(left)):\n left_new_slope = self.calc_slope(left[-i], right[-lower_right])\n if left_new_slope < left_slope:\n lower_left = i - 1\n break\n else:\n updated = True\n lower_left = i\n left_slope = left_new_slope\n \n right_slope = self.calc_slope(left[-lower_left], right[-lower_right])\n init_lower_right = lower_right\n for i in range(init_lower_right+1, len(right)):\n right_new_slope = self.calc_slope(left[-lower_left], right[-i])\n if right_new_slope > right_slope:\n lower_right = i - 1\n break\n else:\n updated = True\n lower_right = i\n right_slope = right_new_slope\n\n # Since lower tangents are found in the backwards orientation, adjust them back\n # to the index in the correct orientation\n # Max of 4 operations\n if lower_left != 0:\n lower_left = len(left) - lower_left\n if lower_right != 0:\n lower_right = len(right) - lower_right\n\n # Sort right hulls clockwise, left counter-clockwise\n result = []\n # Total temportal complexity for the right side is\n # n+m+n+m+n = 3n + 2m => O(n+m)\n if side == \"r\":\n # list.extend is O(k) where k are number of elements added\n # thus worst case senario is O(n+m)\n # Reversing the lists ([::-1]) is also O(k) and is worst case\n # Applied to the whole left hull, this O(n)\n result.extend(left[upper_left:left_most+1][::-1])\n if upper_right > lower_right:\n result.extend(right[upper_right:])\n result.extend(right[:lower_right+1])\n else: \n result.extend(right[upper_right:lower_right+1])\n\n # Index function is O(l) (l is length of result at this point)\n # Worst case is O(n+m) if all of left and right are in result\n new_right_most = result.index(right[right_most])\n \n if lower_left != left_most:\n if lower_left > upper_left:\n result.extend(left[left_most+1:lower_left+1][::-1])\n else:\n result.extend(left[:lower_left+1][::-1])\n result.extend(left[left_most+1:][::-1])\n # Temporal complexity of left sides is 3m + 2n = O(m+n) similarly\n # If side is None, default to counter-clockwise\n else:\n result.extend(right[upper_right:right_most+1][::-1])\n if upper_left > lower_left: \n result.extend(left[upper_left:])\n result.extend(left[:lower_left+1][::-1])\n else:\n result.extend(left[upper_left:lower_left+1])\n\n new_left_most = result.index(left[left_most])\n\n if lower_right != right_most:\n if lower_right > upper_right:\n result.extend(right[right_most+1:lower_right+1][::-1])\n else:\n result.extend(right[:lower_right+1][::-1])\n result.extend(right[right_most+1:][::-1])\n if side == \"r\":\n return result, new_right_most\n else:\n return result, new_left_most",
"def convex_hull(L):\r\n CH=list()\r\n if L != []:\r\n P = list(L)\r\n # find the starting point of the algorithm and add it to the convex hull:\r\n ind0 = find_start(P)\r\n CH.append(P.pop(ind0))\r\n # find the next point and add it to the convex hull list CH:\r\n if P != []:\r\n ind1 = next_in_hull(CH[0], np.array([1,0]), P)\r\n CH.append(P.pop(ind1))\r\n # use the hyperplane criterion as function side_points to complete CH:\r\n while P != []:\r\n p = CH[-2]\r\n q = CH[-1]\r\n v = q - p \r\n P = side_points(CH[0], CH[-1] - CH[0], P)\r\n ind = next_in_hull(q, v, P)\r\n if P != []:\r\n CH.append(P.pop(ind))\r\n return CH",
"def QHull(points: List[sg.Point2]) -> List[sg.Segment2]:\n point_list = copy.copy(points)\n hull_points = []\n points.sort(key=lambda point: point.x())\n mn = points[0]\n mx = points[-1]\n hull_points.append(mn)\n hull_points.append(mx)\n point_list.remove(mn)\n point_list.remove(mx)\n seg = sg.Segment2(mn, mx)\n # a line between the left most and right most point\n s1, s2 = split_points(point_list, seg)\n _FindHull(s1, mn, mx, hull_points)\n _FindHull(s2, mx, mn, hull_points)\n return points_to_segment(hull_points)",
"def _is_left_edge(self, ndx):\n if len(self._dims)== 1:\n return ndx == 0\n return ndx < self._dims[1]"
] | [
"0.5784756",
"0.5722361",
"0.57186353",
"0.571596",
"0.561899",
"0.5575985",
"0.5559472",
"0.5450202",
"0.5366452",
"0.5360122",
"0.53597206",
"0.53502905",
"0.53324366",
"0.5321323",
"0.5316823",
"0.5307588",
"0.5303187",
"0.5294098",
"0.52727485",
"0.5253577",
"0.5250945",
"0.52489924",
"0.51993054",
"0.51946425",
"0.5187939",
"0.5145065",
"0.51441514",
"0.51305497",
"0.51233685",
"0.51154494"
] | 0.8255255 | 0 |
Determines if the new edge would intersect the hull at any point. | def segments_intersects_hull(new_edges:list, hull:list, current_edge:tuple)->bool:
new_edge_extent = extent(new_edges[0][0], new_edges[0][1], new_edges[1][1])
for k in range(0, len(hull) - 1):
if new_edges[0][0] == hull[k] or new_edges[0][0] == hull[k+1]:
continue
elif new_edges[0][1] == hull[k] or new_edges[0][1] == hull[k+1]:
continue
elif new_edges[1][1] == hull[k] or new_edges[1][1] == hull[k+1]:
continue
hull_extent = extent(hull[k], hull[k+1])
if rect_overlap(new_edge_extent, hull_extent):
test_edge = (hull[k], hull[k+1])
if segments_intersect(test_edge, new_edges[0]):
return True
elif segments_intersect(test_edge, new_edges[1]):
return True
return False | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def is_new(self):\n c_up = self.upper_binary_tree().single_edge_cut_shapes()\n c_down = self.lower_binary_tree().single_edge_cut_shapes()\n return not any(x in c_up for x in c_down)",
"def check_inside_hull(hull, instance):\n for face in hull:\n if not check_inside(face=face, instance=instance)[0]:\n return False\n return True",
"def is_intersecting(self, directed_edge):\n begin_orientation = self.orientation(directed_edge.begin)\n end_orientation = self.orientation(directed_edge.end)\n \n if(begin_orientation == 0 or end_orientation == 0):\n return self.contains_point(directed_edge.begin) or self.contains_point(directed_edge.end) or directed_edge.contains_point(self.begin) or directed_edge.contains_point(self.end)\n\n directed_begin_orientation = directed_edge.orientation(self.begin)\n directed_end_orientation = directed_edge.orientation(self.end)\n\n return begin_orientation != end_orientation and directed_begin_orientation != directed_end_orientation",
"def is_vertex_inside(self, point):\n return Geometry.polygon_point_intersection(self.get_point_list(), point)",
"def _is_p_inside_points_hull(points, p):\n\n from scipy.spatial import ConvexHull\n\n hull = ConvexHull(points)\n new_points = np.append(points, p, axis=0)\n new_hull = ConvexHull(new_points)\n if list(hull.vertices) == list(new_hull.vertices):\n return True\n else:\n return False",
"def is_intersecting(self, node):\n return node.visited_left and node.visited_right",
"def containsEdge(self, e):\n return any(e.nvt in [self.vertices[i-2], self.vertices[i]] and self.vertices[i-1] == e.pvt for i in range(len(self.vertices)))",
"def intersects(self, other): # -> bool:\n ...",
"def accurate_collision(self, other) -> bool:\r\n if self.collide:\r\n if self.bbox_intersect(other):\r\n offset = round(self.x - other.x), \\\r\n round(self.y - other.y)\r\n if self.mask.overlap(other.mask, offset): # Overlap returns None or 1 point\r\n return True\r\n return False\r\n else:\r\n return False",
"def test_conv_full(self):\n\n points = np.array([[1, 4], [2, 1], [3, 2], [3, 3], [3, 5], [4, 2], [5, 1], [5, 3]]) # example of points \n \n cv_hull = convex_hull.convex_hull(points) # convex hull returned by the function \n\n right_conv_hull = np.array([[2, 1], [5, 1], [5, 3], [3, 5], [1, 4], [2, 1] ]) # right convex hull\n self.assertTrue((right_conv_hull == cv_hull).all())",
"def is_in_polygon(self, point):\n reference_point = self.get_reference_point()\n \n reference_segment = DirectedEdge(point, reference_point)\n\n num_crossings = 0\n \n left_idx = 0\n while left_idx != len(self):\n right_idx = (left_idx + 1) % len(self)\n \n are_crossing = False\n \n if reference_segment.contains_point(self[left_idx]):\n while reference_segment.contains_point(self[right_idx]):\n right_idx = (right_idx + 1) % len(self)\n \n if right_idx == left_idx:\n break\n \n if left_idx == right_idx:\n left_idx = len(self)\n continue\n \n left_endpoint = self[(left_idx - 1) % len(self)]\n right_endpoint = self[(right_idx + 1) % len(self)]\n \n are_crossing = reference_segment.orientation(left_endpoint) != reference_segment.orientation(right_endpoint)\n left_idx = (right_idx + 1) % len(self) if left_idx < (right_idx + 1) % len(self) else len(self) \n elif reference_segment.contains_point(self[right_idx]):\n left_idx += 1\n continue\n else:\n edge = DirectedEdge(self[left_idx], self[right_idx])\n are_crossing = reference_segment.is_intersecting(edge)\n left_idx += 1\n \n num_crossings = num_crossings + 1 if are_crossing else num_crossings\n \n return num_crossings % 2 == 1",
"def has_hit_edge(self):\n return self.will_hit_edge(self._direction)",
"def in_hull(p, hull, border= True, tol = 0 ):\n if not isinstance(hull,Delaunay):\n hull = Delaunay(hull)\n \n if border:\n return hull.find_simplex(p,tol = tol)>=0\n else:\n return hull.find_simplex(p,tol = tol)>0",
"def is_inside(self, p) -> bool:\r\n h = self.wedge\r\n inside = False\r\n if lefton(h, p):\r\n while not h.nexthedge is self.wedge:\r\n h = h.nexthedge\r\n if not lefton(h, p):\r\n return False\r\n return True\r\n else:\r\n return False",
"def isOnInteriorSide(self, v):\n n = self.normalVect()\n return n.dotProduct(vector(self.vertices[0]) - vector(v)) > 0",
"def is_point_inside_hypercube(point: List[float], c: List[float], r: float) -> bool:\n diff = np.subtract(point, c)\n return np.all(np.absolute(diff) <= r)",
"def __contains__(self, other):\n x, y = other\n return self.radius >= sqrt((x - self.x) ** 2 + (y - self.y) ** 2)",
"def faceIntersection(self, face):\n # Test wether both ends of the edge are in the same half space\n # (relative to <face>'s plane).\n normal = face.normalVect()\n v0 = vector(face.vertices[0])\n vp = vector(self.pvt)\n vn = vector(self.nvt)\n p = normal.dotProduct(vp - v0) * normal.dotProduct(vn - v0)\n if p > 0:\n return False\n elif abs(p) <= COMPARISON_EPSILON or abs(normal.dotProduct(vp - vn) / (normal.norm() * (vp - vn).norm())) <= COMPARISON_EPSILON:\n # print('ah')\n return False\n else:\n interVect = vn + (normal.dotProduct(v0 - vn) /\n normal.dotProduct(vp - vn)) * (vp - vn)\n lastCross = ((vector(face.vertices[-1]) - interVect) *\n (vector(face.vertices[0]) - interVect))\n for i in range(len(face.vertices)):\n cross = ((vector(face.vertices[i]) - interVect) *\n (vector(face.vertices[(i + 1) % len(face.vertices)]) -\n interVect))\n p = cross.dotProduct(lastCross)\n if p < 0:\n return False\n elif p == 0 and cross.norm() != 0:\n if cross.norm() > COMPARISON_EPSILON:\n warnings.warn(\"Cross product's norm is very low\")\n lastCross = cross\n return interVect.coords()",
"def check_convexity(hull, used_pivots):\n for instance in used_pivots:\n if not check_inside_hull(hull, instance):\n return False\n return True",
"def is_intersecting(self, ray):\n\n intersecting_point = self._sympy_plane.intersection(ray.sympy_line)[0]\n\n if 'x' in self._name:\n\n if self._within_y_bounds(intersecting_point.y) and self._within_z_bounds(intersecting_point.z):\n return True, np.array(map(float, [intersecting_point.x, intersecting_point.y, intersecting_point.z]))\n\n\n\n elif 'y' in self._name:\n\n if self._within_x_bounds(intersecting_point.x) and self._within_z_bounds(intersecting_point.z):\n return True, np.array(map(float, [intersecting_point.x, intersecting_point.y, intersecting_point.z]))\n\n\n\n elif 'z' in self._name:\n\n if self._within_y_bounds(intersecting_point.y) and self._within_x_bounds(intersecting_point.x):\n return True, np.array(map(float, [intersecting_point.x, intersecting_point.y, intersecting_point.z]))\n\n return False, None",
"def doBoundingBoxesIntersect(self, other):\n if(self.upperLeft.x <= other.lowerRight.x and\n self.lowerRight.x >= other.upperLeft.x and\n self.upperLeft.y >= other.lowerRight.y and\n self.lowerRight.y <= other.upperLeft.y):\n return True\n return False",
"def intersects(self):\n match = False\n for i in range(len(self.__points) - 1):\n p1 = self.__points[i]\n p2 = self.__points[i + 1]\n bounds = self.__line_segment(p1, p2)\n if not bounds is None:\n xmin = bounds[0]\n ymin = bounds[1]\n xmax = bounds[0]\n ymax = bounds[1]\n for j in range(len(bounds)):\n if not (j % 2):\n if bounds[j] < xmin:\n xmin = bounds[j]\n elif bounds[j] > xmax:\n xmax = bounds[j]\n else:\n if bounds[j] < ymin:\n ymin = bounds[j]\n elif bounds[j] > ymax:\n ymax = bounds[j]\n x = self.x\n y = self.y\n # TODO: Determine direction, and check two leading edge points; ie. last vector ----> then points are x+width,y+width x+width,y-width\n if x > xmin and x < xmax and y > ymin and y < ymax:\n match = True\n break\n return match",
"def origin_is_inside_hitbox(self, hitbox):\n if self.hitdetection.accurate:\n max_x = max(hitbox, key = lambda index: abs(index[0]))[0]\n max_y = max(hitbox, key = lambda index: abs(index[1]))[1]\n \n m = max(max_x, max_y)\n \n num_intersections = 0\n for i in range(0, len(hitbox), 1):\n if self.hitdetection.module.does_intersect([[m, m], [0, 0]], [hitbox[i], hitbox[(i + 1) % len(hitbox)]]):\n num_intersections += 1\n return [False, True][num_intersections % 2]\n else:\n has_smaller = False\n has_bigger = False\n for hx, hy in hitbox:\n if hx > 0 and hy > 0:\n has_bigger = True\n if hx < 0 and hy < 0:\n has_smaller = True\n return has_smaller and has_bigger",
"def point_in_poly(x_point: float, y_point: float) -> bool:\n\n # Semi-F47 extended states all devices should be able to ride out a sag of up to 1 cycle.\n if x_point <= 1:\n return False\n\n point = shapely.geometry.Point(x_point, y_point)\n return POLYGON.contains(point) or POLYGON.intersects(point)",
"def contains(outer, inner):\n return inner.tl.x >= outer.tl.x and inner.tl.y >= outer.tl.y and \\\n inner.br.x <= outer.br.x and inner.br.y <= outer.br.y",
"def intersects(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\r\n return False",
"def __contains__(self, point, e=10e-10):\n v1 = self.vector\n v2 = Vector.createFromTwoPoints(self.point, point)\n return abs(v1.angle - v2.angle) < e",
"def collision(self, model, new_location):\n\n within_bounds = all(model.boundaries[0] <= new_location) and all(new_location <= model.boundaries[1])\n\n if not within_bounds:\n\n collide = True\n\n elif self.neighbourhood(model, new_location):\n\n collide = True\n\n else:\n\n collide = False\n\n return collide",
"def _intersects_1D(A, B):\n return False if (B[1] <= A[0]) or (B[0] >= A[1]) else True",
"def __contains__(self, edge):\n return edge in self._edges"
] | [
"0.6484378",
"0.63872766",
"0.62879694",
"0.6258108",
"0.6223334",
"0.62019885",
"0.6185283",
"0.6149708",
"0.6138869",
"0.61183757",
"0.6070646",
"0.60460234",
"0.6039633",
"0.6038786",
"0.6038608",
"0.6034174",
"0.5997268",
"0.59944534",
"0.59907645",
"0.5983716",
"0.59789616",
"0.5963634",
"0.5960287",
"0.59564966",
"0.5947071",
"0.59386253",
"0.5934843",
"0.59344006",
"0.59322596",
"0.59155923"
] | 0.7658259 | 0 |
Creates a concave hull. | def concave_hull(hull:list, points:list, max_iterations:int=None, min_length_fraction:float=0, min_angle:float=90)->list:
tweet.info("Creating concave hull; minimum side length {}% of average, minimum_angle {}".format(min_length_fraction * 100, min_angle))
test_points = set(points)
ignore_points = []
avg_sqr_distance = 0
for k in range(0, len(hull)-1):
avg_sqr_distance += point_sqr_distance(hull[k], hull[k+1])
test_points.remove(hull[k])
avg_sqr_distance /= len(hull) - 1
min_sqr_length = avg_sqr_distance * (min_length_fraction ** 2) # since we get sqr_length, we square the fraction
min_cosine = math.cos(math.radians(min_angle))
while (max_iterations is None or max_iterations > 0) and test_points:
selection, edge = select_longest_edge(hull, ignore_points, min_sqr_length)
tweet.info("Considering edge {}; {} points left".format(edge, len(test_points)))
if selection is None:
break
selected_point = select_candidate_point(edge, test_points, hull, min_cosine)
if selected_point is None:
# This edge has no more candidate points, so we ignore it in the next pass
ignore_points.append(edge[0])
tweet.debug("No candidate point found.")
continue
tweet.debug("Found point {}, inserting new edge.".format(selected_point))
if not max_iterations is None:
max_iterations -= 1
# We add the point into the concave hull
hull.insert(selection + 1, selected_point)
test_points.remove(selected_point)
return hull | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def convex_hull(self):\n return self._geomgen(capi.geom_convex_hull)",
"def convex_hull(points):\n\n # Sort the points lexicographically (tuples are compared lexicographically).\n # Remove duplicates to detect the case we have just one unique point.\n points = sorted(set(points))\n\n # Boring case: no points or a single point, possibly repeated multiple times.\n if len(points) <= 1:\n return points\n\n # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n # Returns a positive value, if OAB makes a counter-clockwise turn,\n # negative for clockwise turn, and zero if the points are collinear.\n def cross(o, a, b):\n return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])\n\n # Build lower hull\n lower = []\n for p in points:\n cont = 1\n while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:\n print(\"antes \"), print(cont), print(lower)\n lower.pop()\n print(\"despues \"),print(lower)\n cont += 1\n lower.append(p)\n xlower ,ylower = getlists(lower)\n plt.plot(xlower,ylower,color=\"yellow\")\n # Build upper hull\n upper = []\n for p in reversed(points):\n while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:\n upper.pop()\n upper.append(p)\n print(upper)\n print(\"hello2 \")\n print(cross((2,0),(2,4),(2.5,3)))\n\n xupper ,yupper = getlists(upper)\n plt.plot(xupper,yupper,color=\"blue\")\n\n\n return lower[:-1] + upper[:-1]",
"def _convex_hull(points):\n\n # Sort the points lexicographically (tuples are compared lexicographically).\n # Remove duplicates to detect the case we have just one unique point.\n points = sorted(set(points))\n\n # Boring case: no points or a single point, possibly repeated multiple times.\n if len(points) <= 1:\n return points\n\n # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n # Returns a positive value, if OAB makes a counter-clockwise turn,\n # negative for clockwise turn, and zero if the points are collinear.\n def cross(o, a, b):\n return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])\n\n # Build lower hull\n lower = []\n for p in points:\n while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:\n lower.pop()\n lower.append(p)\n\n # Build upper hull\n upper = []\n for p in reversed(points):\n while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:\n upper.pop()\n upper.append(p)\n\n # Concatenation of the lower and upper hulls gives the convex hull.\n # Last point of each list is omitted because it is repeated at the beginning of the other list.\n return lower[:-1] + upper[:-1]",
"def convex_hull(l):\n\tpass",
"def convex_hull(self):\n if isinstance(self.crs, GeographicalCRS):\n raise CRSError(\"not implemented for geographical coordinate \"\n \"systems. Project to a projected coordinate system.\")\n\n points = [pt for pt in self]\n\n # Find the lowermost (left?) point\n pt0 = points[0]\n idx = 0\n for i, pt in enumerate(points[1:]):\n if (pt.y < pt0.y) or ((pt.y == pt0.y) and (pt.x < pt0.x)):\n pt0 = pt\n idx = i+1\n points.pop(idx)\n\n # Sort CCW relative to pt0, and drop all but farthest of any duplicates\n points.sort(key=lambda pt: pt0.distance(pt))\n points.sort(key=lambda pt: _cvectorgeo.polarangle(pt0.vertex, pt.vertex))\n alpha = -1\n drop = []\n for i,pt in enumerate(points):\n a = _cvectorgeo.polarangle(pt0.vertex, pt.vertex)\n if a == alpha:\n drop.append(i)\n else:\n alpha = a\n\n if len(drop) != 0:\n for i in drop[::-1]:\n points.pop(i)\n\n # initialize convex hull\n if len(points) == 2:\n return Polygon([pt0, points[0], points[1]])\n elif len(points) == 1:\n raise GeometryError(\"convex polygon not defined for two points\")\n else:\n\n S = [pt0, points[0], points[1]]\n for pt in points[2:]:\n while not _cvectorgeo.isleft(S[-2].vertex, S[-1].vertex, pt.vertex):\n S.pop()\n S.append(pt)\n\n return Polygon(S, crs=self.crs)",
"def give_convex_hull(rand_points):\n return ConvexHull(rand_points)",
"def convex_hull(points):\n\n # Sort the points lexicographically (tuples are compared lexicographically).\n # Remove duplicates to detect the case we have just one unique point.\n points = sorted(set(points))\n\n # Boring case: no points or a single point, possibly repeated multiple times.\n if len(points) <= 1:\n return points\n\n # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.\n # Returns a positive value, if OAB makes a counter-clockwise turn,\n # negative for clockwise turn, and zero if the points are collinear.\n def cross(o, a, b):\n return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])\n\n # Build lower hull \n lower = []\n for p in points:\n while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:\n lower.pop()\n lower.append(p)\n\n # Build upper hull\n upper = []\n for p in reversed(points):\n while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:\n upper.pop()\n upper.append(p)\n\n # Concatenation of the lower and upper hulls gives the convex hull.\n # Last point of each list is omitted because it is repeated at the beginning of the other list. \n return lower[:-1] + upper[:-1]",
"def convex_hull(points):\n pointList = ExtendedTupleList(points)\n complete_ranges = pointList.range_within(0, 1)\n # Filters for four quadrants\n filters = [\n ((0, complete_ranges[1][\"max\"][2], \">=\"), (1, complete_ranges[0][\"max\"][2], \">=\")), #Q1\n ((0, complete_ranges[1][\"max\"][1], \"<=\"), (1, complete_ranges[0][\"min\"][2], \">=\")), #Q2\n ((0, complete_ranges[1][\"min\"][1], \"<=\"), (1, complete_ranges[0][\"min\"][1], \"<=\")), #Q3\n ((0, complete_ranges[1][\"min\"][2], \">=\"), (1, complete_ranges[0][\"max\"][1], \"<=\")) #Q4\n ]\n # Sorting reversals (True means Desc sort, False means Asc sort. Y sort given first)\n sorts = [\n (True, True),\n (True, False),\n (False, False),\n (False, True),\n ]\n hull = ExtendedTupleList([])\n # In CW order of quadrants...\n for index in [0, 3, 2, 1]:\n # Find all the relevant points\n quad_points = ExtendedTupleList([point for point in pointList.filter(filters[index])])\n # Sort them properly\n quad_points.double_sort(1, 0, reverse_outside=sorts[index][0], reverse_inside=sorts[index][1])\n # Build a convex line segment\n line_segment = convex_line_segment(quad_points, sorts[index][0], sorts[index][1])\n # Reverse it, if we need to\n if index % 2 == 1:\n line_segment.reverse()\n # Add all the points in, avoiding repeated points.\n hull.extend(line_segment, avoid_repeats=True)\n return hull",
"def convex_hull(*args):\n from point import Point\n from line import Segment\n from polygon import Polygon\n\n def uniquify(a):\n # not order preserving\n return list(set(a))\n\n p = args[0]\n if isinstance(p, Point):\n p = uniquify(args)\n\n if len(p) == 1:\n return p[0]\n elif len(p) == 2:\n return Segment(p[0], p[1])\n\n def orientation(p, q, r):\n '''Return positive if p-q-r are clockwise, neg if ccw, zero if\n collinear.'''\n return (q[1] - p[1])*(r[0] - p[0]) - (q[0] - p[0])*(r[1] - p[1])\n\n # scan to find upper and lower convex hulls of a set of 2d points.\n U = []\n L = []\n p.sort()\n for p_i in p:\n while len(U) > 1 and orientation(U[-2], U[-1], p_i) <= 0:\n U.pop()\n while len(L) > 1 and orientation(L[-2], L[-1], p_i) >= 0:\n L.pop()\n U.append(p_i)\n L.append(p_i)\n U.reverse()\n convexHull = tuple(L + U[1:-1])\n\n if len(convexHull) == 2:\n return Segment(convexHull[0], convexHull[1])\n return Polygon(convexHull)",
"def convex_hull(self):\n nodes = self._datacontroller.get_data('nodes')\n scale = self._datacontroller.get_data('scale')\n hull = tsputil.convex_hull_helper(nodes)\n if hull:\n result = construct_step(hull, 'Most Top Left Node', 'Clockwise', nodes, scale)\n self._datacontroller.commit_change('path', result)",
"def getContourRep(self):\n\t\tvertex1 = [[self.startX, self.startY]]\n\t\tvertex2 = [[self.startX, self.endY]]\n\t\tvertex3 = [[self.endX, self.startY]]\n\t\tvertex4 = [[self.endX, self.endY]]\n\t\tvertices = [vertex1, vertex2, vertex3, vertex4]\n\t\treturn convexHull(np.asarray(vertices, dtype = np.int32))",
"def convex(points):\r\n if isinstance(points, np.ndarray):\r\n points = np.unique(points, axis=0)\r\n else:\r\n pts = []\r\n points = [pts.append(i) for i in points if i not in pts] # Remove duplicates\r\n del pts\r\n if len(points) <= 1:\r\n return points\r\n # Build lower hull\r\n lower = []\r\n for p in points:\r\n while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:\r\n lower.pop()\r\n lower.append(p)\r\n # Build upper hull\r\n upper = []\r\n for p in reversed(points):\r\n while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:\r\n upper.pop()\r\n upper.append(p)\r\n #print(\"lower\\n{}\\nupper\\n{}\".format(lower, upper))\r\n return np.array(lower[:-1] + upper) # upper[:-1]) # for open loop\r",
"def convex_hull(points):\n\n # Sort the points lexicographically (tuples are compared lexicographically).\n # Remove duplicates to detect the case we have just one unique point.\n points = sorted(set(points))\n\n # Boring case: no points or a single point, possibly repeated multiple times.\n if len(points) <= 1:\n return points\n\n # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross\n # product. Returns a positive value, if OAB makes a counter-clockwise turn,\n # negative for clockwise turn, and zero if the points are collinear.\n def cross(o, a, b):\n return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])\n\n # Build lower hull\n lower = []\n for p in points:\n while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:\n lower.pop()\n lower.append(p)\n\n # Build upper hull\n upper = []\n for p in reversed(points):\n while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:\n upper.pop()\n upper.append(p)\n\n return lower, upper",
"def convex_hull(self):\n return _property_geo(arctern.ST_ConvexHull, self)",
"def convex_hull(self):\n if self._faces is None:\n if self._vertices is None:\n return None\n self.triangulate()\n return self._convex_hull",
"def make_convex_hull(self):\n hull_points_d = []\n try:\n print \"self.V_bar_list_d******************\", self.V_bar_list_d\n hull = ConvexHull(self.V_bar_list_d)\n hull_vertices = hull.vertices\n\n for i in hull_vertices:\n hull_points_d.append(self.V_bar_list_d[i])\n\n except scipy.spatial.qhull.QhullError:\n hull_points_d = self.V_bar_list_d\n\n return hull_points_d",
"def convex_hull(points):\n points = np.array(points)\n hull = ConvexHull(points)\n return points[hull.vertices, :]",
"def convexHull(points):\n points = np.append(points, [[0, 0, 0]], axis=0) # All points plus origin\n hull = ConvexHull(points) # Visible points plus possible origin. Use its vertices property.\n\n return hull",
"def construct_convex_hull(vertices: Sequence[Point]) -> Polyhedron:\n coords = np.zeros((len(vertices),3))\n for i,vertex in enumerate(vertices):\n coords[i,:] = vertex.coordinates\n hull = qconvex(\"i\", coords)\n n_facets = int(hull[0])\n facets = []\n for facet_vertices_str in hull[1:]:\n facet_vertices_idx = [int(x) for x in facet_vertices_str.split(' ')]\n facet_vertices = [vertices[i] for i in facet_vertices_idx]\n facet = Facet([Contour.from_vertices(facet_vertices)])\n facets.append(facet)\n polyhedron = Polyhedron(facets)\n return polyhedron",
"def create_hull(vertices):\n dt = np.dtype([('vertex', np.float64, (2,)),\n ('length', np.float64),\n ('is_processed', bool)])\n\n hull = np.empty(len(vertices), dtype=dt)\n for i, v in enumerate(vertices):\n j = 0 if i == len(vertices)-1 else i+1\n hull[i] = (v, dist(v, vertices[j]), False)\n\n return np.rec.array(hull)",
"def convex_hull(image):\n\n corners = find_corners(image)\n\n\n vertices = [corners[0]]\n\n for i in range(len(corners)):\n vertices.extend(\n _convex_hull_side(\n image, corners[i], corners[(i + 1) % len(corners)]))\n\n return vertices",
"def convex_hull(L):\r\n CH=list()\r\n if L != []:\r\n P = list(L)\r\n # find the starting point of the algorithm and add it to the convex hull:\r\n ind0 = find_start(P)\r\n CH.append(P.pop(ind0))\r\n # find the next point and add it to the convex hull list CH:\r\n if P != []:\r\n ind1 = next_in_hull(CH[0], np.array([1,0]), P)\r\n CH.append(P.pop(ind1))\r\n # use the hyperplane criterion as function side_points to complete CH:\r\n while P != []:\r\n p = CH[-2]\r\n q = CH[-1]\r\n v = q - p \r\n P = side_points(CH[0], CH[-1] - CH[0], P)\r\n ind = next_in_hull(q, v, P)\r\n if P != []:\r\n CH.append(P.pop(ind))\r\n return CH",
"def convex_hull(self, other):\n hull_vertices = self.vertices() + other.vertices()\n hull_rays = self.rays() + other.rays()\n hull_lines = self.lines() + other.lines()\n hull_field = self.coerce_field(other)\n return Polyhedron(vertices=hull_vertices, \n rays=hull_rays, lines=hull_lines, \n field=hull_field)",
"def hull_convex(ob, me, selected_only, precision = 0.1):\n # find convex hull\n vertices, triangles = pyffi.utils.quickhull.qhull3d(\n [tuple(v.co) for v in me.verts if v.sel or not selected_only],\n precision = precision)\n # create convex mesh\n box = Blender.Mesh.New('convexpoly')\n for vert in vertices:\n box.verts.extend(*vert)\n for triangle in triangles:\n box.faces.extend(triangle)\n # link mesh to scene and set transform\n scn = Blender.Scene.GetCurrent()\n boxob = scn.objects.new(box, 'convexpoly')\n boxob.setMatrix(ob.getMatrix('worldspace'))\n # set bounds type\n boxob.drawType = Blender.Object.DrawTypes['BOUNDBOX']\n boxob.rbShapeBoundType = 5 # convex hull shape not in blender Python API; Blender.Object.RBShapes['CONVEXHULL']?\n boxob.drawMode = Blender.Object.DrawModes['WIRE']",
"def _convex_hull_side(image, start, end):\n\n convex_points = [start]\n\n x_start, y_start = start\n x_end, y_end = end\n\n side = (x_start <= x_end, y_start <= y_end)\n\n\n ranges = {\n (True, True): [\n [x_start + 1, x_end + 1],\n [y_start, y_end + 1],\n False\n ],\n (False, True): [\n [y_start + 1, y_end + 1],\n [x_start, x_end - 1, -1],\n True\n ],\n (False, False): [\n [x_start - 1, x_end - 1, -1],\n [y_start, y_end - 1, -1],\n False\n ],\n (True, False): [\n [y_start - 1, y_end - 1, -1],\n [x_start, x_end + 1],\n True\n ]\n }\n\n prev = 0\n\n for outer in range(*ranges[side][0]):\n\n curr_pixel = None\n\n for inner in range(*ranges[side][1]):\n if ranges[side][2] and image[outer, inner] == 0:\n curr_pixel = (inner, outer)\n break\n elif not ranges[side][2] and image[inner, outer] == 0:\n curr_pixel = (outer, inner)\n break\n\n if curr_pixel is None:\n continue\n\n while True:\n # slope infinite for first point\n prev_slope = (\n float(\"-inf\") if prev == 0\n else slope(\n convex_points[prev - 1],\n convex_points[prev],\n ranges[side][2]))\n\n # remove previous point if it yields concave segment\n if prev_slope > slope(\n convex_points[prev],\n curr_pixel,\n ranges[side][2]\n ):\n convex_points.pop(prev)\n prev -= 1\n # add point to hull if it yields convex segment\n else:\n convex_points.append(curr_pixel)\n prev += 1\n break\n\n return convex_points[1:]",
"def test_conv_full(self):\n\n points = np.array([[1, 4], [2, 1], [3, 2], [3, 3], [3, 5], [4, 2], [5, 1], [5, 3]]) # example of points \n \n cv_hull = convex_hull.convex_hull(points) # convex hull returned by the function \n\n right_conv_hull = np.array([[2, 1], [5, 1], [5, 3], [3, 5], [1, 4], [2, 1] ]) # right convex hull\n self.assertTrue((right_conv_hull == cv_hull).all())",
"def __CalculateConvexHull(self, contour):\r\n return cv2.convexHull(contour)",
"def coords_to_chull(coords, shape):\n matrix = np.zeros(shape[:2], dtype='uint8')\n matrix[coords[:, 0], coords[:, 1]] = 1\n return convex_hull_image(matrix)",
"def cull(self):",
"def main():\n points = np.array(\n [[1, 1], [2, 5], [3, 2], [4, 4], [5, 2], [6, 3], [2, 3], [3, 4], [5, 3]]\n )\n hull = graham_scan(points)\n hull = np.concatenate((hull, [hull[0]]))\n\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.scatter(points[:, 0], points[:, 1])\n ax.plot(hull[:, 0], hull[:, 1], 'r')\n ax.set_title('Convex Hull using Graham Scan')\n plt.show()"
] | [
"0.7206272",
"0.71888036",
"0.71256506",
"0.7085061",
"0.7075677",
"0.7031924",
"0.69883245",
"0.6819022",
"0.68025535",
"0.67614084",
"0.6739058",
"0.6691165",
"0.667362",
"0.6638784",
"0.65221596",
"0.6512171",
"0.646188",
"0.64251655",
"0.6401495",
"0.6394388",
"0.6354288",
"0.6292076",
"0.6234977",
"0.6203397",
"0.6197563",
"0.6194786",
"0.6144196",
"0.6121846",
"0.6036059",
"0.60317904"
] | 0.7279524 | 0 |
Provides the next sample to take. After this method is called, the self.inputInfo should be ready to be sent to the model @ In, model, model instance, an instance of a model @ In, myInput, list, a list of the original needed inputs for the model (e.g. list of files, etc.) @ Out, None | def localGenerateInput(self, model, myInput):
if self.counter < 2:
MCMC.localGenerateInput(self, model, myInput)
else:
self._localReady = False
for key, value in self._updateValues.items():
# update value based on proposal distribution
newVal = value + self._proposal[key].rvs() * self._scaling
self.values[key] = newVal
if key in self.distDict:
## check the lowerBound and upperBound
lowerBound = self.distDict[key].lowerBound
upperBound = self.distDict[key].upperBound
if lowerBound is not None and self.values[key] < lowerBound:
self.values[key] = lowerBound
if upperBound is not None and self.values[key] > upperBound:
self.values[key] = upperBound
self.inputInfo['SampledVarsPb'][key] = self.distDict[key].pdf(newVal)
else:
self.inputInfo['SampledVarsPb'][key] = self._priorFuns[key].evaluate("pdf", self.values)
self.inputInfo['ProbabilityWeight-' + key] = 1.
self.inputInfo['PointProbability'] = 1.0
self.inputInfo['ProbabilityWeight' ] = 1.0
self.inputInfo['SamplerType'] = 'Metropolis'
self.inputInfo['LogPosterior'] = self.netLogPosterior
self.inputInfo['AcceptRate'] = self._acceptRate | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def input(self):\n try:\n return self.inputs[-1]\n except IndexError:\n pass\n raise ValueError(\"The sample method has not been called\")",
"def test_prepare_sample_to_forward(self):\n sample = [\n {\"src\": \"ola mundo\", \"ref\": \"hi world\", \"mt\": \"hey world!\", \"score\": 0.8},\n {\"src\": \"ola mundo\", \"ref\": \"hi world\", \"mt\": \"hey world!\", \"score\": 0.8},\n ]\n\n model_input, target = self.estimator.prepare_sample(sample)\n model_output = self.estimator(**model_input)\n self.assertTrue(model_output[\"score\"].shape[0] == 2)\n self.assertTrue(model_output[\"score\"].shape[1] == 1)",
"def sample(self, state, model_args, model_kwargs):\n raise NotImplementedError",
"def localGenerateInput(self, model, myInput):\n # create values dictionary\n weight = 1.0\n for key in sorted(self.distDict):\n # check if the key is a comma separated list of strings\n # in this case, the user wants to sample the comma separated variables with the same sampled value => link the value to all comma separated variables\n totDim = self.variables2distributionsMapping[key]['totDim']\n dist = self.variables2distributionsMapping[key]['name']\n reducedDim = self.variables2distributionsMapping[key]['reducedDim']\n weight = 1.0\n if totDim == 1:\n if self.samplingType == 'uniform':\n distData = self.distDict[key].getCrowDistDict()\n if ('xMin' not in distData.keys()) or ('xMax' not in distData.keys()):\n self.raiseAnError(IOError,\"In the Monte-Carlo sampler a uniform sampling type has been chosen;\"\n + \" however, one or more distributions have not specified either the lowerBound or the upperBound\")\n lower = distData['xMin']\n upper = distData['xMax']\n rvsnum = lower + (upper - lower) * randomUtils.random()\n # TODO (wangc): I think the calculation for epsilon need to be updated as following\n # epsilon = (upper-lower)/(self.limit+1) * 0.5\n epsilon = (upper-lower)/self.limit\n midPlusCDF = self.distDict[key].cdf(rvsnum + epsilon)\n midMinusCDF = self.distDict[key].cdf(rvsnum - epsilon)\n weight *= midPlusCDF - midMinusCDF\n else:\n rvsnum = self.distDict[key].rvs()\n for kkey in key.split(','):\n self.values[kkey] = np.atleast_1d(rvsnum)[0]\n self.inputInfo['SampledVarsPb'][key] = self.distDict[key].pdf(rvsnum)\n self.inputInfo['ProbabilityWeight-' + key] = 1.\n elif totDim > 1:\n if reducedDim == 1:\n if self.samplingType is None:\n rvsnum = self.distDict[key].rvs()\n coordinate = np.atleast_1d(rvsnum).tolist()\n else:\n coordinate = np.zeros(totDim)\n for i in range(totDim):\n lower = self.distDict[key].returnLowerBound(i)\n upper = self.distDict[key].returnUpperBound(i)\n coordinate[i] = lower + (upper - lower) * randomUtils.random()\n if reducedDim > len(coordinate):\n self.raiseAnError(IOError, \"The dimension defined for variables drew from the multivariate normal distribution is exceeded by the dimension used in Distribution (MultivariateNormal) \")\n probabilityValue = self.distDict[key].pdf(coordinate)\n self.inputInfo['SampledVarsPb'][key] = probabilityValue\n for var in self.distributions2variablesMapping[dist]:\n varID = utils.first(var.keys())\n varDim = var[varID]\n for kkey in varID.strip().split(','):\n self.values[kkey] = np.atleast_1d(rvsnum)[varDim-1]\n self.inputInfo[f'ProbabilityWeight-{dist}'] = 1.\n else:\n self.raiseAnError(IOError, \"Total dimension for given distribution should be >= 1\")\n\n if len(self.inputInfo['SampledVarsPb'].keys()) > 0:\n self.inputInfo['PointProbability'] = reduce(mul, self.inputInfo['SampledVarsPb'].values())\n else:\n self.inputInfo['PointProbability'] = 1.0\n if self.samplingType == 'uniform':\n self.inputInfo['ProbabilityWeight' ] = weight\n else:\n self.inputInfo['ProbabilityWeight' ] = 1.0 # MC weight is 1/N => weight is one\n self.inputInfo['SamplerType'] = 'MonteCarlo'",
"def get_next_sample(self):",
"def run_sample(self):\n # there will be validation failures for sample data\n self.validate_req(ignore_failure=True)\n runner_fn = self.model_runner.execute_model_for_sample_data\n return self.do_handle_request(runner_fn)",
"def sample_input(self, loader, is_test=False):\n pass",
"def sample(self):\r\n raise NotImplementedError",
"def sample(self):\n raise NotImplementedError",
"def sample(self):\n raise NotImplementedError",
"def _construct_sample_from_input(self):\n xi = T.matrix()\n xo = T.matrix()\n irs = self.ir_steps\n oputs = [self.obs_transform(self.s0)]\n oputs.extend([self.obs_transform(self.si[i]) for i in range(irs)])\n _, hi_zmuv = self._construct_zmuv_samples(xi, 1)\n sample_func = theano.function(inputs=[xi, xo], outputs=oputs, \\\n givens={ self.x_in: xi, \\\n self.x_out: xo, \\\n self.hi_zmuv: hi_zmuv }, \\\n updates=self.scan_updates)\n def conditional_sampler(XI, XO=None, guided_decoding=False):\n XI = to_fX( XI )\n if XO is None:\n XO = XI\n XO = to_fX( XO )\n # set model to desired generation mode\n old_switch = self.train_switch.get_value(borrow=False)\n if guided_decoding:\n # take samples from guide policies (i.e. variational q)\n self.set_train_switch(switch_val=1.0)\n else:\n # take samples from model's generative policy\n self.set_train_switch(switch_val=0.0)\n # draw guided/unguided conditional samples\n model_samps = sample_func(XI, XO)\n # set model back to either training or generation mode\n self.set_train_switch(switch_val=old_switch)\n return model_samps\n return conditional_sampler",
"def _get_input_data_for_model(self, extra_data=None):\n extra_data = {} if extra_data is None else extra_data\n if self.metadata['sample_rate'] is not None:\n if self.audio_signal.sample_rate != self.metadata['sample_rate']:\n self.audio_signal.resample(self.metadata['sample_rate'])\n\n self.audio_signal.stft_params = self.metadata['stft_params']\n self.audio_signal.stft()\n\n data = {'mix': self.audio_signal}\n data.update(extra_data)\n data = self.transform(data)\n\n for key in data:\n if torch.is_tensor(data[key]):\n data[key] = data[key].unsqueeze(0).to(self.device).float()\n if self.metadata['num_channels'] == 1:\n # then each channel is processed indep\n data[key] = data[key].transpose(0, self.channel_dim)\n self.input_data = data\n return self.input_data",
"def process_sample_train(self):\n raise NotImplementedError",
"def run(self):\n\n # How to retrieve your input data.\n input_1_data = self.in_data['input_1']\n\n # How to retrieve your params value.\n param_1 = self.param['param_1']\n\n # How to process data.\n # Just write any number of methods you want and use them here.\n sample_out_data = self.sample_method(input_1_data, param_1)\n\n # Go to the definition of this method to see how to log.\n self.demo_log()\n\n # This is how to set output data.\n self.out_data['output_1'] = sample_out_data",
"def input(self):",
"def sample(self, number_samples: int = 1) -> List[Any]:\n # if prompt is provided, use it\n if self.prompt:\n item = self.model(batch_size=number_samples, prompt=self.prompt)\n else:\n item = self.model(batch_size=number_samples)\n\n # To support old diffusers versions (<0.6.0)\n if DIFFUSERS_VERSION_LT_0_6_0 or self.model_type in [\"geodiff\"]:\n item = item[\"sample\"]\n else:\n item = item.images\n\n return item",
"def _create_generate_input(self):\n self.keep_prob = 1.",
"def _sample(self, rnn_output, temperature):\n pass",
"def sample(self):\n raise NotImplementedError(\"Override me!\")",
"def input(self):\r\n pass",
"def sample(self):",
"def simulate(self, data):\n # Get the current timestep\n now = data.current_timestep\n self.logger.info(\"{model_name_cap}Wrapper received inputs in %s\", now)\n\n # Get model parameters\n {model_parameters}\n # Get model inputs\n {model_inputs}\n # Write results to data handler\n {model_outputs}\n self.logger.info(\"{model_name_cap}Wrapper produced outputs in %s\", now)",
"def call(self, inputs, training=True):\n pass",
"def sample(self, params):\r\n old_model_trace = poutine.trace(self.model)(self.args, self.kwargs)\r\n traces = []\r\n t = 0\r\n i = 0\r\n while t < self.burn + self.lag * self.samples:\r\n i += 1\r\n # q(z' | z)\r\n new_guide_trace = poutine.block(\r\n poutine.trace(self.model))(old_model_trace, self.args, self.kwargs)\r\n # p(x, z')\r\n new_model_trace = poutine.trace(\r\n poutine.replay(self.model, new_guide_trace))(self.args, self.kwargs)\r\n # q(z | z')\r\n old_guide_trace = poutine.block(\r\n poutine.trace(\r\n poutine.replay(self.guide, old_model_trace)))(new_model_trace,\r\n self.args, self.kwargs)\r\n # p(x, z') q(z' | z) / p(x, z) q(z | z')\r\n logr = new_model_trace.log_pdf() + new_guide_trace.log_pdf() - \\\r\n old_model_trace.log_pdf() - old_guide_trace.log_pdf()\r\n rnd = pyro.sample(\"mh_step_{}\".format(i),\r\n Uniform(torch.zeros(1), torch.ones(1)))\r\n\r\n if torch.log(rnd).data[0] < logr.data[0]:\r\n # accept\r\n t += 1\r\n old_model_trace = new_model_trace\r\n if t <= self.burn or (t > self.burn and t % self.lag == 0):\r\n yield (new_model_trace, new_model_trace.log_pdf())",
"def predict(self, sample, **kwargs):\r\n return self.model.predict(sample, **kwargs)",
"def step(self):\n if self.Y.shape[0]<self.initial_design_numdata:\n self.suggested_sample = initial_design('random', self.space, 1)\n else:\n self.suggested_sample = self._compute_next_evaluations()\n\n self.X = np.vstack((self.X,self.suggested_sample))\n\n # --- Update current evaluation time and function evaluations\n self.num_acquisitions += 1\n\n if self.verbosity:\n print(\"num acquisition: {}\".format(self.num_acquisitions))\n\n return np.array(self.suggested_sample[0,:])",
"def processInputs(self):",
"def output(self):\n try:\n return self.outputs[-1]\n except IndexError:\n pass\n raise ValueError(\"The sample method has not been called\")",
"def sample(self, like_params):\n\t\traise NotImplementedError",
"def reconstruct_input_ext(self, model_in):"
] | [
"0.70868576",
"0.6604615",
"0.65657943",
"0.6411239",
"0.6372315",
"0.63269866",
"0.62161213",
"0.61675435",
"0.6153169",
"0.6153169",
"0.61334926",
"0.6080559",
"0.607126",
"0.5985408",
"0.59807396",
"0.5938614",
"0.5915001",
"0.5886959",
"0.5884955",
"0.58460677",
"0.5823079",
"0.5786147",
"0.57705957",
"0.57556987",
"0.575046",
"0.57449263",
"0.5739417",
"0.57390296",
"0.5738344",
"0.5718422"
] | 0.6721474 | 1 |
General function (available to all samplers) that finalize the sampling calculation just ended. In this case, The function is aimed to check if all the batch calculations have been performed @ In, jobObject, instance, an instance of a JobHandler @ In, model, model instance, it is the instance of a RAVEN model @ In, myInput, list, the generating input @ Out, None | def localFinalizeActualSampling(self, jobObject, model, myInput):
MCMC.localFinalizeActualSampling(self, jobObject, model, myInput) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def can_finalize_job_record(self):\n pass",
"def has_full_batch(self) -> bool:",
"def finalize(self):\n\t\tself.logger.info(\"Please wait while finalizing the operation.. Thank you\")\n\t\tself.save_checkpoint()\n\t\tself.summary_writer.export_scalars_to_json(\"{}all_scalars.json\".format(self.config.summary_dir))\n\t\tself.summary_writer.close()\n\t\tself.data_loader.finalize()\n\t\tif self.config.output_model == True:\n\t\t\ttry:\n\t\t\t\tself.logger.info('Saving model for external usage.')\n\t\t\t\tself.load_checkpoint('model_best.pth.tar')\n\t\t\t\ttraced = torch.jit.trace(self.model,self.data_loader.train_loader.dataset[:2][0].float().to(self.device))\n\t\t\t\ttraced.save(self.config.output_model_path)\n\t\t\texcept IOError:\n\t\t\t\tself.logger.info('Output model path not found.')",
"def _check_for_finished_job(self):\n raise NotImplementedError",
"def on_batch_end(self, batch, logs=None):",
"def on_test_batch_end(self, batch, logs=None):",
"def on_eval_batch_end(self, step, logs=None):",
"def finalize_integration(self, **kwargs):",
"def val_batch_end(self, batch_data, running_val_data):\n pass",
"def batch_end(self, batch_data, train_step_data):\n pass",
"def finish_training(self, error: bool = False, **info):\n pass",
"def on_train_batch_end(self, step, logs=None):",
"def finish_learning(self):\n pass",
"def on_validation_batch_end(\n self,\n trainer: 'pl.Trainer',\n pl_module: 'pl.LightningModule',\n outputs: Optional[STEP_OUTPUT],\n batch: Any,\n batch_idx: int,\n dataloader_idx: int,\n ) -> None:\n if trainer.global_step % self.every_n_steps == 0:\n if self.multi_optim:\n x = outputs[0]['x']\n xrec = outputs[0]['xrec']\n else:\n x = outputs['x']\n xrec = outputs['xrec']\n x_grid = torchvision.utils.make_grid(\n tensor=x,\n nrow=self.nrow,\n padding=self.padding,\n normalize=self.normalize,\n value_range=self.norm_range,\n scale_each=self.scale_each,\n pad_value=self.pad_value,\n ) \n xrec_grid = torchvision.utils.make_grid(\n tensor=xrec,\n nrow=self.nrow,\n padding=self.padding,\n normalize=self.normalize,\n value_range=self.norm_range,\n scale_each=self.scale_each,\n pad_value=self.pad_value,\n ) \n if self.use_wandb:\n trainer.logger.experiment.log({\n \"val/input\": wandb.Image(x_grid),\n \"val/reconstruction\": wandb.Image(xrec_grid), \n \"global_step\": trainer.global_step\n })\n else: \n x_title = \"val/input\"\n trainer.logger.experiment.add_image(x_title, x_grid, global_step=trainer.global_step)\n xrec_title = \"val/reconstruction\"\n trainer.logger.experiment.add_image(xrec_title, xrec_grid, global_step=trainer.global_step)",
"def _handler_autosample_exit(self, *args, **kwargs):\n if self._scheduler is not None:\n try:\n self._remove_scheduler(ScheduledJob.SAMPLE)\n except KeyError:\n log.debug('_remove_scheduler count not find: %s', ScheduledJob.SAMPLE)",
"def finish(self):\n for metric in self.metricList:\n if metric.name == 'simulation':\n metric.finish()",
"def on_train_end(self):",
"def finalize_worker():\n if SAMPLER_POOL is not None:\n for _ in range(NUM_SAMPLER_WORKERS):\n SAMPLER_POOL.apply_async(_exit)\n time.sleep(0.1) # This is necessary but I don't know why\n SAMPLER_POOL.close()",
"def _is_done(self, observations):\n raise NotImplementedError()",
"def _is_done(self, observations):\n raise NotImplementedError()",
"def _is_done(self, observations):\n raise NotImplementedError()",
"def _is_done(self, observations):\n raise NotImplementedError()",
"def _is_done(self, observations):\n raise NotImplementedError()",
"def _is_done(self, observations):\n raise NotImplementedError()",
"def check_all_done(self, label: str):\n all_converged = True\n if not self.output[label]['convergence']:\n for job_type, spawn_job_type in self.job_types.items():\n if spawn_job_type and not self.output[label]['job_types'][job_type] \\\n and not ((self.species_dict[label].is_ts and job_type in ['scan', 'conformers'])\n or (self.species_dict[label].number_of_atoms == 1\n and job_type in ['conformers', 'opt', 'fine', 'freq', 'rotors', 'bde'])\n or job_type == 'bde' and self.species_dict[label].bdes is None\n or job_type == 'conformers'\n or job_type == 'irc'\n or job_type == 'tsg'):\n logger.debug(f'Species {label} did not converge.')\n all_converged = False\n break\n if all_converged:\n self.output[label]['convergence'] = True\n if self.species_dict[label].is_ts:\n self.species_dict[label].make_ts_report()\n logger.info(self.species_dict[label].ts_report + '\\n')\n zero_delta = datetime.timedelta(0)\n conf_time = extremum_list([job.run_time for job in self.job_dict[label]['conformers'].values()],\n return_min=False) \\\n if 'conformers' in self.job_dict[label].keys() else zero_delta\n tsg_time = extremum_list([job.run_time for job in self.job_dict[label]['tsg'].values()], return_min=False) \\\n if 'tsg' in self.job_dict[label].keys() else zero_delta\n opt_time = sum_time_delta([job.run_time for job in self.job_dict[label]['opt'].values()]) \\\n if 'opt' in self.job_dict[label].keys() else zero_delta\n comp_time = sum_time_delta([job.run_time for job in self.job_dict[label]['composite'].values()]) \\\n if 'composite' in self.job_dict[label].keys() else zero_delta\n other_time = extremum_list([sum_time_delta([job.run_time for job in job_dictionary.values()])\n for job_type, job_dictionary in self.job_dict[label].items()\n if job_type not in ['conformers', 'opt', 'composite']], return_min=False) \\\n if any([job_type not in ['conformers', 'opt', 'composite']\n for job_type in self.job_dict[label].keys()]) else zero_delta\n self.species_dict[label].run_time = self.species_dict[label].run_time \\\n or (conf_time or zero_delta) + \\\n (tsg_time or zero_delta) + \\\n (opt_time or zero_delta) + \\\n (comp_time or zero_delta) + \\\n (other_time or zero_delta)\n logger.info(f'\\nAll jobs for species {label} successfully converged. '\n f'Run time: {self.species_dict[label].run_time}')\n # Todo: any TS which did not converged (any rxn not calculated) should be reported here with full status: Was the family identified? Were TS guesses found? IF so, what's wrong?\n elif not self.species_dict[label].is_ts or self.species_dict[label].ts_guesses_exhausted:\n job_type_status = {key: val for key, val in self.output[label]['job_types'].items()\n if key in self.job_types and self.job_types[key]\n and (key != 'irc' or self.species_dict[label].is_ts)}\n logger.error(f'Species {label} did not converge. Job type status is: {job_type_status}')\n # Update restart dictionary and save the yaml restart file:\n self.save_restart_dict()",
"def training_end(self):\n pass",
"def finished(self):\n hit_max_evals = len(self.rounds) >= self.max_evals\n\n if len(self.rounds) < self.conv_check_iters:\n hit_conv = False\n else:\n last_rounds = self.rounds[-self.conv_check_iters:]\n a = zip(*last_rounds)[1]\n a_sd = np.std(a, axis=0)\n hit_conv = (a_sd < self.conv_action_eps).all()\n\n hit_max_time = self.duration > self.max_time\n\n return hit_max_evals or hit_conv or hit_max_time",
"def _check_results(self):\n if not 'EXECUTION OF GAMESS TERMINATED NORMALLY' in self.file_dic['output']:\n print self.job_name + \" didn't finish\"\n raise TypeError('Calculation didn\\'t finish')",
"def on_validation_batch_end(self, outputs, batch, batch_idx, dataloader_idx):\n for callback in self.callbacks:\n callback.on_validation_batch_end(self, self.get_model(), outputs, batch, batch_idx, dataloader_idx)",
"def generateFinishOutput(self, job):\n return []"
] | [
"0.6187927",
"0.5795619",
"0.5728285",
"0.56815076",
"0.56358445",
"0.5633501",
"0.5633048",
"0.5577172",
"0.55352855",
"0.55237323",
"0.5502523",
"0.5490598",
"0.54837555",
"0.54806143",
"0.5472647",
"0.5471663",
"0.5465032",
"0.5452882",
"0.54441124",
"0.54441124",
"0.54441124",
"0.54441124",
"0.54441124",
"0.54441124",
"0.54230696",
"0.54123247",
"0.53799623",
"0.53693944",
"0.5366135",
"0.5359494"
] | 0.6751163 | 0 |
Used to feedback the collected runs within the sampler @ In, newRlz, dict, new generated realization @ In, currentRlz, dict, the current existing realization @ Out, netLogPosterior, float, the accepted probabilty | def _useRealization(self, newRlz, currentRlz):
netLogPosterior = 0
# compute net log prior
for var in self._updateValues:
newVal = newRlz[var]
currVal = currentRlz[var]
if var in self.distDict:
dist = self.distDict[var]
netLogPrior = dist.logPdf(newVal) - dist.logPdf(currVal)
else:
fun = self._priorFuns[var]
netLogPrior = np.log(fun.evaluate("pdf", newRlz)) - np.log(fun.evaluate("pdf", currentRlz))
netLogPosterior += netLogPrior
if not self._logLikelihood:
netLogLikelihood = np.log(newRlz[self._likelihood]) - np.log(currentRlz[self._likelihood])
else:
netLogLikelihood = newRlz[self._likelihood] - currentRlz[self._likelihood]
netLogPosterior += netLogLikelihood
netLogPosterior = min(0.0, netLogPosterior)
return netLogPosterior | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def inference_spa(flow_lik,\n flow_post,\n prior,\n simulator,\n optimizer_lik,\n optimizer_post,\n decay_rate_post,\n x_o,\n x_o_batch_post,\n dim_post,\n prob_prior,\n nbr_lik,\n nbr_epochs_lik,\n nbr_post,\n nbr_epochs_post,\n batch_size,\n batch_size_post,\n epochs_hot_start=10,\n validation_fraction=0.1,\n early_stopping=True,\n stop_after_epochs=20):\n\n nbr_iter = len(prob_prior)\n\n print(\"start full training\")\n\n models_lik = []\n models_post = []\n\n scheduler_post = torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer_post, gamma=decay_rate_post)\n\n for i in range(nbr_iter):\n\n # decay post lr\n if i >= 1 and decay_rate_post > 0:\n scheduler_post.step()\n\n # print iter info\n print(\"Iteration: \" + str(i + 1))\n print(\"optimizer_post_lr: \" + str(scheduler_post.get_last_lr()))\n print(\"prob_prior: \" + str(prob_prior[i]))\n\n # update likelihood model\n\n nbr_lik_prior = int(prob_prior[i] * nbr_lik[i])\n nbr_like_post = int((1 - prob_prior[i]) * nbr_lik[i])\n\n theta_prior = prior.sample(sample_shape=(nbr_lik_prior,))\n\n if nbr_like_post == 0: # this is to avoid concatunate a tensor with grad to the theta tensor\n theta_full = theta_prior\n else:\n theta_post = flow_post.sample(nbr_like_post, context=x_o) # .reshape(1,dim)\n theta_post = theta_post.reshape((nbr_like_post, dim_post))\n # not sure if this is valid.... Is ok since we sample from a mixture\n theta_prior_check = prior.log_prob(theta_post)\n\n # print(theta_prior_check.shape)\n idx_save = (~torch.isinf(theta_prior_check)).nonzero()\n\n # print(idx_save.shape)\n\n if idx_save.shape[0] > 0:\n theta_post = theta_post[idx_save.reshape(-1), :]\n theta_full = torch.cat([theta_prior, theta_post.detach()], dim=0)\n else:\n theta_full = theta_prior\n\n # remove thetas that are outside of prior\n\n x_full = simulator(theta_full)\n\n _train_like(x_full, theta_full, nbr_epochs_lik[i], batch_size, flow_lik, optimizer_lik,\n validation_fraction, early_stopping, stop_after_epochs)\n\n # update posterior model\n\n # 2' step: train posterior model from prior predictive first, only used to get a hot start\n if i == 0:\n _train_post_prior_pred(x_full, theta_full, epochs_hot_start, batch_size, flow_post, optimizer_post,\n validation_fraction)\n # models_post.append(copy.deepcopy(flow_post))\n\n # Sample training data from posterior\n\n _train_post_sim_fly(nbr_post[i], nbr_epochs_post[i], batch_size_post, flow_post, flow_lik, optimizer_post,\n prior, x_o_batch_post, dim_post, x_o, validation_fraction, early_stopping,\n stop_after_epochs)\n\n # save trained model for each iter\n models_lik.append(copy.deepcopy(flow_lik))\n models_post.append(copy.deepcopy(flow_post))\n\n return models_lik, models_post",
"def run():\n trials = 100\n\n multipliers = [0.25, 0.3, 0.35, 0.5, 0.75, 1, 1.25, 1.45, 1.5, 1.55, 1.6] # Coefficients for learning rate\n\n mean_penalty = []\n median_penalty = []\n std_penalty = []\n\n mean_trial_time = []\n median_trial_time = []\n std_trial_time = []\n\n mean_success_rate = []\n median_success_rate = []\n std_success_rate = []\n\n for m in multipliers:\n all_penalties = [] # All penalties from trail sets\n all_average_trial_time = []\n all_success_rates = []\n\n for i in range(0, 20):\n # print \"Trial set:\", i\n # Set up environment and agent\n e = Environment() # create environment (also adds some dummy traffic)\n agent = e.create_agent(LearnerAgent) # create agent\n agent.mult = m\n e.set_primary_agent(agent, enforce_deadline=True) # specify agent to track\n\n # Now simulate it\n sim = Simulator(e, update_delay=0.0, display=False) # create simulator (uses pygame when display=True, if available)\n\n sim.run(n_trials=trials) # run for a specified number of trials\n\n all_penalties.append(agent.all_trails_penalties)\n all_average_trial_time.append(agent.time/float(trials))\n all_success_rates.append(float(trials-agent.aborted_trials)/trials)\n\n mean_penalty.append(np.mean(all_penalties))\n median_penalty.append(np.median(all_penalties))\n std_penalty.append(np.std(all_penalties))\n\n mean_trial_time.append(np.mean(all_average_trial_time))\n median_trial_time.append(np.median(all_average_trial_time))\n std_trial_time.append(np.std(all_average_trial_time))\n\n mean_success_rate.append(np.mean(all_success_rates))\n median_success_rate.append(np.median(all_success_rates))\n std_success_rate.append(np.std(all_success_rates))\n\n for i in range(0, len(multipliers)):\n print \"\"\n print \"Multiplier:\", multipliers[i]\n print \"\"\n print \"Mean penalty per {} trials:\".format(trials), mean_penalty[i]\n print \"Median penalty per {} trials:\".format(trials), median_penalty[i]\n print \"Std.Dev. penalty per {} trials:\".format(trials), std_penalty[i]\n\n print \"\"\n print \"Mean trial time:\", mean_trial_time[i]\n print \"Median trial time:\", median_trial_time[i]\n print \"Std.Dev. trial time:\", std_trial_time[i]\n\n print \"\"\n print \"Mean success rate per {} trials:\".format(trials), mean_success_rate[i]\n print \"Median success rate per {} trials:\".format(trials), median_success_rate[i]\n print \"Std.Dev. success rate per {} trials:\".format(trials), std_success_rate[i]",
"def update(self):\n with torch.no_grad():\n self.preprocess_rollout()\n \n # DEEP-RL TUTORIALS: КОСТЫЛЬ\n #self.advantages = self.returns[:-1] - self.values[:-1]\n #self.advantages = (self.advantages - self.advantages.mean()) / (self.advantages.std() + 1e-5)\n \n # going through rollout several (config.epochs) times:\n for epoch in range(self.config.epochs):\n # TODO: drop last = False? What if there is 1 sample?\n sampler = BatchSampler(SubsetRandomSampler(range(self.env.num_envs * self.config.rollout)), self.config.batch_size, drop_last=False)\n \n for indices in sampler:\n # retrieving new batch as part of rollout\n self.returns_b = self.returns.view(-1, *self.config.value_repr_shape)[indices]\n self.old_values_b = self.values.view(-1, *self.config.value_repr_shape)[indices]\n self.old_action_log_probs_b = self.action_log_probs.view(-1)[indices]\n #self.advantages_b = self.advantages.view(-1)[indices] # КОСТЫЛЬ\n \n # calculating current value, action_log_prob, entropy\n dist, self.values_b = self.policy(self.observations.view(-1, *self.config.observation_shape)[indices])\n self.values_b = self.values_b.squeeze() # IMPORTANT ([32] - [32, 1] problem)\n self.action_log_probs_b = dist.log_prob(self.actions.view(-1, *self.config.actions_shape)[indices])#.sum(dim=-1) \n self.entropy_b = dist.entropy()#.sum(dim=-1)\n \n # performing step\n self.gradient_ascent_step()",
"def run_and_store(self):\n # Initialization assumptions\n z = self.draw_normal_initial()\n gradient = self.cv_gradient_initial(z)\n gradient[np.isnan(gradient)] = 0\n variance = np.power(gradient,2) \n final_parameters = self.current_parameters()\n final_samples = 1\n\n # Create optimizer\n if self.optimizer == 'ADAM':\n self.optim = ADAM(final_parameters, variance, self.learning_rate, 0.9, 0.999)\n elif self.optimizer == 'RMSProp':\n self.optim = RMSProp(final_parameters, variance, self.learning_rate, 0.99)\n\n # Stored updates\n stored_means = np.zeros((self.iterations,len(final_parameters)/2))\n stored_predictive_likelihood = np.zeros(self.iterations)\n\n # Record elbo\n if self.record_elbo is True:\n elbo_records = np.zeros(self.iterations)\n else:\n elbo_records = None\n\n for i in range(self.iterations):\n gradient = self.cv_gradient(self.draw_normal())\n gradient[np.isnan(gradient)] = 0\n new_parameters = self.optim.update(gradient)\n self.change_parameters(new_parameters)\n\n stored_means[i] = self.optim.parameters[::2]\n stored_predictive_likelihood[i] = self.neg_posterior(stored_means[i])\n\n if self.printer is True:\n self.print_progress(i,self.optim.parameters[::2])\n\n # Construct final parameters using final 10% of samples\n if i > self.iterations-round(self.iterations/10):\n final_samples += 1\n final_parameters = final_parameters+self.optim.parameters\n\n if self.record_elbo is True:\n elbo_records[i] = self.get_elbo(self.optim.parameters[::2])\n\n final_parameters = final_parameters/float(final_samples)\n self.change_parameters(final_parameters)\n final_means = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2==0])\n final_ses = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2!=0])\n\n if not self.quiet_progress:\n print(\"\")\n print(\"Final model ELBO is \" + str(-self.neg_posterior(final_means)-self.create_normal_logq(final_means)))\n return self.q, final_means, final_ses, stored_means, stored_predictive_likelihood, elbo_records",
"def run_and_store(self):\n # Initialization assumptions\n z = self.draw_normal_initial()\n gradient = self.cv_gradient_initial(z)\n gradient[np.isnan(gradient)] = 0\n variance = np.power(gradient,2) \n final_parameters = self.current_parameters()\n final_samples = 1\n\n # Create optimizer\n if self.optimizer == 'ADAM':\n self.optim = ADAM(final_parameters, variance, self.learning_rate, 0.9, 0.999)\n elif self.optimizer == 'RMSProp':\n self.optim = RMSProp(final_parameters, variance, self.learning_rate, 0.99)\n\n # Stored updates\n stored_means = np.zeros((self.iterations,len(final_parameters)/2))\n stored_predictive_likelihood = np.zeros(self.iterations)\n\n # Record elbo\n if self.record_elbo is True:\n elbo_records = np.zeros(self.iterations)\n else:\n elbo_records = None\n\n for i in range(self.iterations):\n gradient = self.cv_gradient(self.draw_normal())\n gradient[np.isnan(gradient)] = 0\n new_parameters = self.optim.update(gradient)\n self.change_parameters(new_parameters)\n\n stored_means[i] = self.optim.parameters[::2]\n stored_predictive_likelihood[i] = self.neg_posterior(stored_means[i])\n\n if self.printer is True:\n self.print_progress(i,self.optim.parameters[::2])\n\n # Construct final parameters using final 10% of samples\n if i > self.iterations-round(self.iterations/10):\n final_samples += 1\n final_parameters = final_parameters+self.optim.parameters\n\n if self.record_elbo is True:\n elbo_records[i] = self.get_elbo(self.optim.parameters[::2])\n\n final_parameters = final_parameters/float(final_samples)\n self.change_parameters(final_parameters)\n final_means = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2==0])\n final_ses = np.array([final_parameters[el] for el in range(len(final_parameters)) if el%2!=0])\n\n if not self.quiet_progress:\n print(\"\")\n print(\"Final model ELBO is \" + str(-self.full_neg_posterior(final_means)-self.create_normal_logq(final_means)))\n return self.q, final_means, final_ses, stored_means, stored_predictive_likelihood, elbo_records",
"def update_policy(self):\n # this is update_policy \n # sample batch of 32 from the memory\n batch_of_samples = self.replay_memory.sample(batch_size=32)\n current_state_samples = batch_of_samples['current_state_samples']\n next_state_samples = batch_of_samples['next_state_samples']\n #print type(current_state_samples[0])\n #print current_state_samples\n\n # fetch stuff we need from samples 32*84*84*4\n current_state_images = np.zeros([1, 84, 84, 4])\n #print current_state_samples\n current_state_images[0,...] = np.dstack([sample.state for sample in current_state_samples])\n\n next_state_images = np.zeros([1, 84, 84, 4])\n next_state_images[0,...] = np.dstack([sample.state for sample in next_state_samples])\n\n # preprocess\n current_state_images = self.preprocessor.process_batch(current_state_images)\n next_state_images = self.preprocessor.process_batch(next_state_images)\n # print \"current_state_images {} max {} \".format(current_state_images.shape, np.max(current_state_images))\n #print current_state_images.shape\n q_current = self.q_network.predict(current_state_images,batch_size=self.batch_size) # 32*num_actions\n q_next = self.q_network.predict(next_state_images,batch_size=self.batch_size)\n\n # targets\n y_targets_all = q_current #1*num_actions\n #print y_targets_all.shape # [1,6]\n idx = 0 \n last_sample = current_state_samples[-1]\n if last_sample.is_terminal:\n y_targets_all[idx, last_sample.action] = last_sample.reward\n else:\n if self.mode == 'vanilla':\n y_targets_all[idx, last_sample.action] = np.float32(last_sample.reward) + self.gamma*np.max(q_next[idx])\n if self.mode == 'double': \n y_targets_all[idx, last_sample.action] = np.float32(last_sample.reward) + self.gamma*q_next[idx, np.argmax(q_current[idx])] \n\n loss = self.q_network.train_on_batch(current_state_images, np.float32(y_targets_all))\n\n with tf.name_scope('summaries'):\n self.tf_log_scaler(tag='train_loss', value=loss, step=self.iter_ctr)\n\n if not (self.iter_ctr % self.log_loss_every_nth):\n self.dump_train_loss(loss)\n\n # if (self.iter_ctr > (self.num_burn_in+1)) and not(self.iter_ctr%self.target_update_freq):\n # # copy weights\n # print \"Iter {} Updating target Q network\".format(self.iter_ctr)\n # self.target_q_network.set_weights(self.q_network.get_weights())\n # [self.target_q_network.trainable_weights[i].assign(self.q_network.trainable_weights[i]) \\\n # for i in range(len(self.target_q_network.trainable_weights))]",
"def learn(self):\r\n \r\n # take a mini-batch from replay experience\r\n cur_batch_size = min(len(self.replay_exp), self.batch_size)\r\n mini_batch = random.sample(self.replay_exp, cur_batch_size)\r\n \r\n # batch data\r\n sample_states = np.ndarray(shape = (cur_batch_size, self.state_size)) # replace 128 with cur_batch_size\r\n sample_actions = np.ndarray(shape = (cur_batch_size, 1))\r\n sample_rewards = np.ndarray(shape = (cur_batch_size, 1))\r\n sample_next_states = np.ndarray(shape = (cur_batch_size, self.state_size))\r\n sample_dones = np.ndarray(shape = (cur_batch_size, 1))\r\n\r\n temp=0\r\n for exp in mini_batch:\r\n sample_states[temp] = exp[0]\r\n sample_actions[temp] = exp[1]\r\n sample_rewards[temp] = exp[2]\r\n sample_next_states[temp] = exp[3]\r\n sample_dones[temp] = exp[4]\r\n temp += 1\r\n \r\n \r\n sample_qhat_next = self.brain_target.predict(sample_next_states)\r\n \r\n # set all Q values terminal states to 0\r\n sample_qhat_next = sample_qhat_next * (np.ones(shape = sample_dones.shape) - sample_dones)\r\n # choose max action for each state\r\n sample_qhat_next = np.max(sample_qhat_next, axis=1)\r\n \r\n sample_qhat = self.brain_policy.predict(sample_states)\r\n \r\n for i in range(cur_batch_size):\r\n a = sample_actions[i,0]\r\n sample_qhat[i,int(a)] = sample_rewards[i] + self.gamma * sample_qhat_next[i]\r\n \r\n q_target = sample_qhat\r\n \r\n self.brain_policy.fit(sample_states, q_target, epochs = 1, verbose = 0)\r\n \r\n \r\n \r\n \"\"\"\r\n \r\n for state, action, reward, next_state, done in mini_batch:\r\n target_Q_s_a = 0 # new target for Q(s,a)\r\n state = np.reshape(state, [1, state_size])\r\n next_state = np.reshape(next_state, [1, state_size])\r\n \r\n # if it is not the terminal state\r\n if not done:\r\n qhat_next = self.brain_target.predict(next_state) # estimate Q(s',a')\r\n target_Q_s_a = reward + self.gamma * np.amax(qhat_next[0]) # because the output is m * n, so we need to consider the dimension [0]\r\n else:\r\n target_Q_s_a = reward\r\n \r\n target_output = self.brain_policy.predict(state) # we will replace target of Q(s,a) for specific a later\r\n target_output[0][action] = target_Q_s_a # new target for state s and action a\r\n \r\n self.brain_policy.fit(state, target_output, epochs = 1, verbose = 0)\r\n \r\n \"\"\"",
"def learn(self):\n \n # target parameter update\n # target parameter update\n if self.learn_step_counter % self.nu_iter == 0:\n self.target_net.load_state_dict(self.eval_net.state_dict())\n #testing the preformace of the network\n if self.learn_step_counter == 0:\n print('As referece this first test on dev data. Is maded with the Q networks, initialized randomly : ' )\n else:\n print(\"\\n Lets copy the Q-value Net in to Q-target net!. And test the performace on the dev data: \")\n \n current_bleu = self.dev_network()\n print(\"Current Bleu score is: \", current_bleu)\n \n self.learn_step_counter += 1\n\n \n long_Batch = self.sample_size*3\n # Sampling the higgest rewards values\n b_memory_big = self.memory[np.argsort(-self.memory[:-self.max_output_length, self.state_size+1])][:long_Batch]\n \n sample_index = np.random.choice(long_Batch, self.sample_size)\n b_memory = b_memory_big[sample_index, :]\n\n b_s = torch.FloatTensor(b_memory[:, :self.state_size])\n b_a = torch.LongTensor(b_memory[:, self.state_size:self.state_size+1].astype(int))\n b_r = torch.FloatTensor(b_memory[:, self.state_size+1:self.state_size+2])\n b_s_ = torch.FloatTensor(b_memory[:, self.state_size+2: self.state_size+2 + self.state_size])\n\n b_is_eos = torch.FloatTensor(b_memory[:, self.size_memory1-1:]).view(self.sample_size, 1)\n #print(b_a, b_a.size)\n #print(b_is_eos)\n #Activate the eval_net\n unfreeze_model(self.eval_net)\n \n # q_eval w.r.t the action in experience\n q_eval = self.eval_net(b_s).gather(1, b_a) # shape (batch, 1)\n q_next = self.target_net(b_s_).detach() # detach from graph, don't backpropagate\n #taking the most likely action.\n b_a_ = torch.LongTensor(q_next.max(1)[1].view(self.sample_size, 1).long())\n #b_a_ = q_next.max(1)[0].view(self.sample_size, 1).long() # shape (batch, 1)\n q_eval_next = self.eval_net(b_s_).gather(1, b_a_) # shape (batch, 1)\n \n #If eos q_target = reward. \n q_target = b_r + self.gamma * b_is_eos* q_eval_next.view(self.sample_size, 1) # shape (batch, 1)\n #version 0\n #q_target = b_r + self.gamma * q_next.max(1)[0].view(self.sample_size, 1) # shape (batch, 1)\n \n loss = self.loss_func(q_eval, q_target)\n \n self.tb_writer.add_scalar(\"learn/learn_batch_loss\",\n loss.data, self.learn_step_counter)\n\n self.optimizer.zero_grad()\n loss.backward()\n self.optimizer.step()\n\n #desctivate the eval_net\n freeze_model(self.eval_net)",
"def retr_metr(gdat, indxvaluthis=None, strgvarbthis=None):\n\n metr = np.zeros((gdat.numbepoc, 2, 3 )) - 1\n\n loss = np.empty(gdat.numbepoc)\n numbepocchec = 5\n \n print gdat.modl.summary()\n for y in gdat.indxepoc:\n print 'Training epoch %d...' % y\n histinpt = gdat.inpttran[:, :, None]\n hist = gdat.modl.fit(histinpt, gdat.outptran, epochs=1, batch_size=gdat.numbdatabtch, verbose=1)\n loss[y] = hist.history['loss'][0]\n indxepocloww = max(0, y - numbepocchec)\n \n for layr in gdat.modl.layers:\n func = keras.backend.function([gdat.modl.input, keras.backend.learning_phase()], [layr.output])\n \n listweigbias = layr.get_weights()\n #assert len(listweigbias) == 2\n print 'listweigbias'\n for n in range(len(listweigbias)):\n print 'n'\n print n\n print 'listweigbias[n]'\n summgene(listweigbias[n])\n stat = func([histinpt, 1.])\n print 'type(stat)'\n print type(stat)\n print 'len(stat)'\n print len(stat)\n for n in range(len(stat)):\n print 'stat[n]'\n summgene(stat[n])\n print\n print\n\n\n if y == gdat.numbepoc - 1 and 100. * (loss[indxepocloww] - loss[y]):\n print 'Warning! The optimizer may not have converged.'\n print 'loss[indxepocloww]\\n', loss[indxepocloww], '\\nloss[y]\\n', loss[y], '\\nloss\\n', loss\n\n for r in gdat.indxrtyp:\n if r == 0:\n inpt = gdat.inpttran\n outp = gdat.outptran\n numdatatemp = gdat.numbdatatran\n else:\n inpt = gdat.inpttest\n outp = gdat.outptest\n numbdatatemp = gdat.numbdatatest\n inpt = inpt[:, :, None]\n \n outppredsigm = gdat.modl.predict(inpt)\n outppred = (outppredsigm > 0.5).astype(int)\n matrconf = confusion_matrix(outp, outppred)\n if matrconf.size == 1:\n matrconftemp = np.copy(matrconf)\n matrconf = np.empty((2, 2))\n matrconf[0, 0] = matrconftemp\n trne = matrconf[0, 0]\n flpo = matrconf[0, 1]\n flne = matrconf[1, 0]\n trpo = matrconf[1, 1]\n \n if float(trpo + flpo) > 0:\n metr[y, r, 0] = trpo / float(trpo + flpo) # precision\n else:\n pass\n #print ('No positive found...')\n #raise Exception('')\n metr[y, r, 1] = float(trpo + trne) / (trpo + flpo + trne + flne) # accuracy\n if float(trpo + flne) > 0:\n metr[y, r, 2] = trpo / float(trpo + flne) # recall\n else:\n print 'No relevant sample!'\n #raise Exception('')\n \n print 'metr[y, r, :]'\n print metr[y, r, :]\n print \n return metr",
"def train(self, game_life):\n rewards = [obs.get('reward') for obs in game_life]\n cum_rewards = sum(rewards)\n\n # manage the graphics\n self.reward_graph.append(cum_rewards)\n plt.plot(self.reward_graph)\n x, y, z = peri_bounding_box\n\n # The amound of nudge\n if cum_rewards:\n displacement = cum_rewards * self.displacement\n else:\n displacement = 0 - self.displacement\n\n # Store observations and perturbed predictions\n data, targets = [], []\n\n for obs in game_life:\n\n # Perturb action\n action, prediction = obs.get('action')\n if self.epsilon and (random.uniform(0, 1.0) < self.epsilon):\n action = random.randrange(18)\n\n # Copy\n update = list(prediction)\n\n # Update only the target action\n update[0][action] = update[0][action] + displacement\n\n\n data.append(\n # Apply bounding box before appending\n np.array(obs.get('observation')[x[0]:x[1], y[0]:y[1], :])\n )\n\n\n update = np.array(update).reshape(1,18),\n targets.append(update)\n\n if data and len(data) > 15:\n # Image processing\n datagen = preprocessing.image.ImageDataGenerator(\n featurewise_center=True,\n featurewise_std_normalization=True,\n rotation_range=20,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=True)\n datagen.fit(data)\n\n # Training data generator\n train = datagen.flow(np.array(data), np.squeeze(np.array(targets)),\n batch_size=16)\n\n # Finally train\n self.graph.fit_generator(train, steps_per_epoch=len(data)/16,\n epochs=30, verbose=0,\n callbacks=[\n callbacks.EarlyStopping(monitor='acc'),\n # callbacks.ModelCheckpoint() ?\n ]\n )",
"def update_recurrent_weights_step(self):\n \n # update weights: hebbian term\n self.delta_Wee=self.learn_rate*(self.rr[0:self.N_e]-self.input_mean)*\\\n (self.rr[0:self.N_e].T-self.input_mean)\n \n self.W_ee+=self.dt*self.delta_Wee\n\n # update weights: normalize to fixed mean of incoming and outgoing weights\n self.W_ee-=(self.W_ee.mean(axis=1)-self.W_av_star)[:,np.newaxis]\n self.W_ee-=(self.W_ee.mean(axis=0)-self.W_av_star)[np.newaxis,:]\n \n # clip weights \n self.W_ee=np.clip(self.W_ee,0,self.W_max_ee)\n \n # update excitatory weights in the big weight matrix\n self.W[:self.N_e,:self.N_e]=self.W_ee",
"def update_policy(self, current_sample):\n # current_sample = current_sample.img\n batch_size = self.batch_size\n\n if self.no_experience:\n states = np.stack([current_sample.state])\n next_states = np.stack([current_sample.next_state])\n rewards = np.asarray([current_sample.reward])\n mask = np.asarray([1 - int(current_sample.is_terminal)])\n\n action_mask = np.zeros((1, self.num_actions))\n action_mask[0, current_sample.action] = 1.0\n else:\n samples = self.memory.sample(batch_size)\n samples = self.atari_processor.process_batch(samples)\n\n states = np.stack([x.state for x in samples])\n actions = np.asarray([x.action for x in samples])\n action_mask = np.zeros((batch_size, self.num_actions))\n action_mask[range(batch_size), actions] = 1.0\n\n next_states = np.stack([x.next_state for x in samples])\n mask = np.asarray([1 - int(x.is_terminal) for x in samples])\n rewards = np.asarray([x.reward for x in samples])\n\n if self.no_target:\n next_qa_value = self.q_network.predict_on_batch(next_states)\n else:\n next_qa_value = self.target_network.predict_on_batch(next_states)\n\n if self.enable_ddqn:\n qa_value = self.q_network.predict_on_batch(next_states)\n max_actions = np.argmax(qa_value, axis = 1)\n next_qa_value = next_qa_value[range(batch_size), max_actions]\n else:\n next_qa_value = np.max(next_qa_value, axis = 1)\n target = rewards + self.gamma * mask * next_qa_value\n\n return self.final_model.train_on_batch([states, action_mask], target), np.mean(target)",
"def learn(self):\n # Calculate prior probabilities.\n self.priorpos = len(self.posdata) / (len(self.posdata) + len(self.negdata))\n self.priorneg = len(self.negdata) / (len(self.posdata) + len(self.negdata))\n print(\"Prior probability positive: \")\n print(self.priorpos)\n print(\"Prior probability negative: \")\n print(self.priorneg)\n\n # Calculate negative likelihood/conditional probability.\n occurpos = self.occurence(self.posvec)\n self.condpos = self.condprob(occurpos)\n occurneg = self.occurence(self.negvec)\n self.condneg = self.condprob(occurneg)",
"def learn(self):\n batch = self.agent.replay_buffer.sample(self.batch_size)\n states = torch.tensor([x.state for x in batch], dtype=torch.float32).to(self.agent.device) # shape == (batch_size, 3, 6, 7)\n actions = [x.action for x in batch]\n rewards = torch.tensor([x.reward for x in batch], dtype=torch.float32).to(self.agent.device)\n next_states = torch.tensor([x.next_state for x in batch], dtype=torch.float32).to(self.agent.device)\n dones = [x.done for x in batch]\n\n self.optimizer.zero_grad()\n\n\n q_vals = self.agent.policy_net(states)[range(len(actions)), actions] # Q vals for actions taken\n q_next_vals = self.agent.target_net(next_states).detach() # we don't care about grad wrt target net\n q_next_vals[dones] = 0.0 # terminal states have no future expected value\n q_targets = rewards + self.gamma * torch.max(q_next_vals, dim=1)[0]\n\n # all_q_vals = self.agent.policy_net(states)\n # print()\n # print('actions')\n # print(actions)\n # print()\n # print('original all q vals')\n # print(self.agent.policy_net(states)) \n # print(self.agent.policy_net(states).shape)\n # print()\n # print('QVALS:', q_vals)\n # print(q_vals.shape)\n # print('\\n\\n')\n # print('QTARGETS:', q_targets)\n # print(q_targets.shape)\n\n # breakpoint()\n\n loss = self.loss_fn(q_targets, q_vals).to(self.agent.device)\n loss.backward()\n \n # for layer in self.agent.policy_net.named_parameters():\n \n # # print(f'layer: {layer[0]}')\n # # print(f'grad:', layer[1].grad)\n\n # # print('loss', loss)\n # # print('q_vals grad:', q_vals.grad)\n # # print('states:', )\n\n self.optimizer.step()\n\n self.agent.learning_iters += 1\n if self.agent.learning_iters % self.target_update_freq == 0:\n self.agent.update_target_net()\n # logger.info('Updated target net')",
"def lr_experiment():\n\n print(\"LR_EXPERIMENT\\n\")\n\n # set the name of the experiment\n now = datetime.datetime.now()\n experiment_id = str(now.day) + \"_\" + str(now.month) + \"_\" + str(now.hour) + \".\" + str(now.minute)\n experiment_name = 'lr_' + str(experiment_id)\n\n # define if you want to use preprocessed data from file\n use_prep_data = False\n if use_prep_data:\n set_params(preproc_data_id='16_5_10.16.47')\n else:\n set_params(use_preproc_data=False)\n\n # define the changing parameter and its value\n changing_param_name = 'lr'\n changing_param_value = [0.00001, 0.00003, 0.0001, 0.0003, 0.001, 0.003, 0.01, 0.03, 0.1]\n\n # set constant parameters\n set_params(use_word_emb=1)\n set_params(epochs=20)\n\n # save constant parameters to a new \"experiment_..\" file\n save_constant_parameters(experiment_name, changing_param_name)\n\n # run experiment for every parameter value\n for value in changing_param_value:\n # update the changing parameter value\n set_params(lr = value)\n\n # update the model_id for this new model\n now = datetime.datetime.now()\n new_model_id = str(now.day) + \"_\" + str(now.month) + \"_\" + str(now.hour) + \".\" + str(now.minute) + \".\" + str(now.second)\n set_params(model_id = new_model_id)\n\n # evaluate the new model and save the results in the experiment file\n oneExperiment = Process(target=run_experiment, args=(experiment_name, new_model_id, changing_param_name, value,))\n oneExperiment.start()\n oneExperiment.join()\n\n if value == changing_param_value[0]:\n set_params(preproc_data_id=new_model_id)",
"def simulationTwoDrugsDelayedTreatment(numTrials):\n #Initialization\n delayList = [300, 150, 75, 0]\n #delayList = [150]\n #Patient init variables\n numViruses = 100\n maxPop = 1000\n #Virus init variables\n maxBirthProb = 0.1\n clearProb = 0.05\n #clearProb = 0.10\n resistances = { 'guttagonol': False, 'grimpex' : False }\n #mutProb = 0.005\n mutProb = 0.010\n \n results = {}\n \n for n in delayList:\n cured = 0\n popList = []\n print \"Running trials for delay %(delay)d\" % {'delay' : n}\n for i in range(numTrials):\n #print \"Trial: \" + str(i)\n pop = runTrialTwoDrugs(n, numViruses, maxPop, maxBirthProb, clearProb, resistances, mutProb)\n popList.append(pop)\n if pop < 50:\n cured +=1\n results[n] = popList\n #print popList\n print \"Delay : %(delay)d Percentage cured %(percent)2f\" % {\"delay\" : n, \"percent\" : cured/float(numTrials) }\n \n\n drawHist(results, numTrials)",
"def after_run(self, run_context, run_values):\n train_step = run_values.results\n if train_step < 40000:\n self._lrn_rate = 0.1\n elif train_step < 60000:\n self._lrn_rate = 0.01\n elif train_step < 80000:\n self._lrn_rate = 0.001\n else:\n self._lrn_rate = 0.0001",
"def run_optimization(self):\n # Get batch\n (obs, action, old_logp, old_value, return_, advantage) = self.buffer.eject()\n\n # Train pi\n print(\"-\" * 20 + \"\\nPi Update\" + \"\\n\" + \"-\" * 20)\n (policy_loss, entropy,\n kl_divergence, clipping_fraction, steps) = self.update_actor(obs, action, old_logp, advantage)\n\n # Train value function\n print(\"-\" * 20 + \"\\nValue Function Update\" + \"\\n\" + \"-\" * 20)\n (value_loss,\n explained_variance) = self.update_critic(obs, old_value, return_)\n\n # Logging\n self.update_counter += 1\n self.log_update(policy_loss, entropy, kl_divergence, clipping_fraction,\n value_loss, explained_variance, steps)\n\n # Update learning rate\n self.decay_lr()\n\n # Save current weights (overwrites previous weights)\n self.save_weights()\n\n # Empty scenario counter\n self.scenario_counter = dict.fromkeys(self.scenario_counter, 0)",
"def update(self):\n\n # get states, actions, rewards and total timesteps from memory\n states, actions, R, T = self.memory.get()\n n_ep = len(R)\n\n # compute value estimates for the states\n v = self.critic(states)\n\n # compute advantages (using GAE) and rewards to go\n A, rtg = utils.gae_rtg((R, v, T), self.gam, self.lam)\n\n # store the initial version of both the policy and the log probs of the\n # actions for later comparison with the future versions (needed for PPO)\n policy_old = copy.deepcopy(self.policy)\n log_probs_old = policy_old(states).log_prob(actions)\n\n # sample from a batch of experiences\n # (\"_\" subscript indicates \"sampled from\")\n for (v_, A_, rtg_, log_probs_old_), i in utils.sample_batch((v, A, rtg, log_probs_old), self.batch_size, self.policy_updates):\n log_probs_ = self.policy(states).log_prob(actions)[i]\n\n # estimate ratio between the new log probs and the old ones\n r_ = torch.exp(log_probs_ - log_probs_old_)\n\n l_1 = r_ * A_\n l_2 = torch.clamp(r_, 1-self.eps, 1+self.eps) * A_\n\n # TODO: implement entropy\n # TODO: merge policy and critic\n\n # surragate loss function for PPO\n l_clip = -torch.mean(torch.min(l_1, l_2))\n\n # update the policy\n self.policy_optimizer.zero_grad()\n l_clip.backward(retain_graph=True)\n self.policy_optimizer.step()\n\n # sample a batch of value estimates and the corresponding rewards to go\n # to update the value function.\n for (v_, rtg_), _ in utils.sample_batch((v, rtg), self.batch_size, self.v_updates):\n # compute the loss\n critic_loss = F.mse_loss(v_, rtg_)\n\n # update the critic\n self.critic_optimizer.zero_grad()\n critic_loss.backward(retain_graph=True)\n self.critic_optimizer.step()\n\n # clear the memory. PPO is an On-Policy method so we don't need these\n # memories anymore\n self.memory.clear()\n\n # return the loss of the value function for display\n return F.mse_loss(v, rtg)",
"def gen_ran_res_params(self):\n gen = Generator(device = self.device).manual_seed(self.random_seed)\n n = self.n_nodes_\n self.accept = rand(n, n, **self.tensorArgs, generator = gen)\n self.reservoir_pre_weights = rand(n, n, **self.tensorArgs, generator = gen) * 2 - 1",
"def active_learning(data, n_iter, n_sample, epochs):\n evaluation = []\n weights = []\n for i in range(n_iter):\n print(\"Iteration: {}\".format(i+1)) \n if i == 0:\n sampled_data, data = sample_random(n_sample,data)\n training_data = sampled_data \n model =LogisticRegression()\n print(\"Start training\")\n model.fit(training_data[:,:2], training_data[:,2], epochs=epochs, verbose=0, shuffle=True)\n print(\"End training\")\n eval_i = model.evaluate(data[:,:2], data[:,2])[1]\n evaluation.append(eval_i)\n print(\"Accuracy: {}\".format(eval_i)) \n weights.append(model.get_weights())\n sampled_data, rest_data = sample_highest_margin(model, data,n_sample)\n data = rest_data\n# import pdb; pdb.set_trace()\n training_data = np.concatenate([training_data, sampled_data]) \n print(\"---------------------------\")\n return evaluation, weights, training_data",
"def feed_dict(self):\n return {self.lr_tensor: self.lr()}",
"def update_learning_rate(self, it):\n self.scheduler.step()\n for param_group in self.optimizer.param_groups:\n v = param_group['lr']\n self.tb_logger.add_scalar('train/lr', v, it)",
"def callback(_locals, _globals):\n global n_steps, best_mean_reward\n # Print stats every 1000 calls\n if (n_steps + 1) % 1000 == 0:\n # Evaluate policy training performance\n x, y = ts2xy(load_results(log_dir), 'timesteps')\n if len(x) > 0:\n mean_reward = np.mean(y[-100:])\n print(x[-1], 'timesteps')\n print(\"Best mean reward: {:.2f} - Last mean reward per episode: {:.2f}\".format(best_mean_reward, mean_reward))\n\n # New best model, you could save the agent here\n if mean_reward > best_mean_reward:\n best_mean_reward = mean_reward\n # Example for saving best model\n print(\"Saving new best model\")\n _locals['self'].save(log_dir + str(x[-1])+'best_model.pkl')\n n_steps += 1\n return True",
"def simulationDelayedTreatment(numTrials):\n \n #Initialization\n #delayList = [300, 150, 75, 0]\n delayList = [150]\n #Patient init variables\n numViruses = 100\n maxPop = 1000\n #Virus init variables\n maxBirthProb = 0.1\n clearProb = 0.05\n #clearProb = 0.10\n resistances = { 'guttagonol': True }\n mutProb = 0.005\n \n results = {}\n \n for n in delayList:\n cured = 0\n popList = []\n for i in range(numTrials):\n pop = runTrial(n, numViruses, maxPop, maxBirthProb, clearProb, resistances, mutProb)\n popList.append(pop)\n if pop == 0:\n cured +=1\n results[n] = popList\n #print popList\n print \"Delay : %(delay)d Percentage cured %(percent)2f\" % {\"delay\" : n, \"percent\" : cured/float(numTrials) }\n \n\n drawHist(results, numTrials)",
"def callback(_locals, _globals):\n global n_steps\n # Print stats every 20 calls\n if (n_steps + 1) % 1 == 0:\n # Evaluate policy training performance\n episode_rewards, episode_lengths = evaluate_policy(_locals['self'], eval_real_env,\n n_eval_episodes=n_eval_episodes,\n render=False,\n deterministic=False,\n return_episode_rewards=False)\n print(\"Last mean reward per episode at target: {:.2f}\".format(episode_rewards))\n\n episode_rewards_grnd, episode_lengths_grnd = evaluate_policy(_locals['self'], eval_grnd_env,\n n_eval_episodes=n_eval_episodes,\n render=False,\n deterministic=False,\n return_episode_rewards=False)\n print(\"Last mean reward per episode at grounded environment: {:.2f}\".format(episode_rewards_grnd))\n\n with open(os.path.join(log_dir, 'eval_at_target.txt'), 'a') as f:\n f.write(\"{}, {}, {}\\n\".format(n_steps, episode_rewards, episode_lengths/n_eval_episodes))\n f.close()\n with open(os.path.join(log_dir, 'eval_at_grnd.txt'), 'a') as f:\n f.write(\"{}, {}, {}\\n\".format(n_steps, episode_rewards_grnd, episode_lengths_grnd/n_eval_episodes))\n f.close()\n n_steps += 1\n return True",
"def posterior_sample(self):\n pass",
"def _on_step(self) -> None:\n self._n_calls += 1\n # Account for multiple environments\n # each call to step() corresponds to n_envs transitions\n if self._n_calls % max(self.target_update_interval // self.n_envs, 1) == 0:\n polyak_update(self.q_net.parameters(), self.q_net_target.parameters(), self.tau)\n # Copy running stats, see GH issue #996\n polyak_update(self.batch_norm_stats, self.batch_norm_stats_target, 1.0)\n\n self.exploration_rate = self.exploration_schedule(self._current_progress_remaining)\n self.logger.record(\"rollout/exploration_rate\", self.exploration_rate)",
"def eval(self, sample):\n '''\n jv = sample.get(JOINT_VELOCITIES)\n eepv = sample.get(END_EFFECTOR_POINT_VELOCITIES)\n\n boxpos = jv[:, 2:5]\n fingerpos = eepv[:, 7:10]\n tgtpos = np.zeros((100,3))\n for i in range(100):\n tgtpos[i] = [0.6, 0.2, 0.1]\n \n fetchdist = np.sum((boxpos - fingerpos) ** 2, axis=1)\n liftdist = np.sum((boxpos - tgtpos) ** 2, axis=1)\n \n l = fetchdist + liftdist\n '''\n\n eept = sample.get(END_EFFECTOR_POINTS)\n eepv = sample.get(END_EFFECTOR_POINT_VELOCITIES)\n sample_u = sample.get_U()\n cfrc_ext = np.concatenate((eept[:, 13:56], eepv[:, 0:41]), axis = 1)\n # vec = eepv[:, 64:66] \n # dist = np.sum(np.square(vec), axis=1) / 5\n forward_reward = eepv[:, 53]\n scaling = 150\n ctrl_cost = 0.5 * 1e-2 * np.sum(np.square(sample_u / scaling), axis = 1)\n # contact_cost = 0.5 * 1e-3 * np.sum(np.square(cfrc_ext), axis = 1)\n # survive_reward = 0.5\n \n l = -forward_reward + ctrl_cost\n\n prefix=''\n logger.record_tabular('PolReturn', -sum(l))\n\n ave_vel = np.mean(forward_reward)\n min_vel = np.min(forward_reward)\n max_vel = np.max(forward_reward)\n std_vel = np.std(forward_reward)\n logger.record_tabular(prefix+'PolAverageVelocity', ave_vel)\n logger.record_tabular(prefix+'PolMinVelocity', min_vel)\n logger.record_tabular(prefix+'PolMaxVelocity', max_vel)\n logger.record_tabular(prefix+'PolStdVelocity', std_vel)\n logger.dump_tabular(with_prefix=False)\n \n lx, lu, lxx, luu, lux = 0, 0, 0, 0, 0\n\n '''\n # Compute weighted sum of each cost value and derivatives.\n weight = self._weights[0]\n l = l * weight\n lx = lx * weight\n lu = lu * weight\n lxx = lxx * weight\n luu = luu * weight\n lux = lux * weight\n for i in range(1, len(self._costs)):\n pl, plx, plu, plxx, pluu, plux = self._costs[i].eval(sample)\n weight = self._weights[i]\n l = l + pl * weight\n lx = lx + plx * weight\n lu = lu + plu * weight\n lxx = lxx + plxx * weight\n luu = luu + pluu * weight\n lux = lux + plux * weight\n '''\n \n return l, lx, lu, lxx, luu, lux",
"def learn(\n self, env, MAX_UPDATES=2000000, MAX_EP_STEPS=100, warmupBuffer=True,\n warmupQ=False, warmupIter=10000, doneTerminate=True, runningCostThr=None,\n curUpdates=None, checkPeriod=50000, plotFigure=True, storeFigure=False,\n showBool=False, vmin=-1, vmax=1, numRndTraj=200, storeModel=True,\n storeBest=False, outFolder=\"RA\", verbose=True\n ):\n # == Warmup Buffer ==\n startInitBuffer = time.time()\n if warmupBuffer:\n self.initBuffer(env)\n endInitBuffer = time.time()\n\n # == Warmup Q ==\n startInitQ = time.time()\n if warmupQ:\n self.initQ(\n env, warmupIter=warmupIter, outFolder=outFolder,\n plotFigure=plotFigure, storeFigure=storeFigure, vmin=vmin, vmax=vmax\n )\n endInitQ = time.time()\n\n # == Main Training ==\n startLearning = time.time()\n trainingRecords = []\n runningCost = 0.0\n trainProgress = []\n checkPointSucc = 0.0\n ep = 0\n if curUpdates is not None:\n self.cntUpdate = curUpdates\n print(\"starting from {:d} updates\".format(self.cntUpdate))\n\n if storeModel:\n modelFolder = os.path.join(outFolder, \"model\")\n os.makedirs(modelFolder, exist_ok=True)\n if storeFigure:\n figureFolder = os.path.join(outFolder, \"figure\")\n os.makedirs(figureFolder, exist_ok=True)\n\n while self.cntUpdate <= MAX_UPDATES:\n s = env.reset()\n epCost = 0.0\n ep += 1\n # Rollout\n for step_num in range(MAX_EP_STEPS):\n # Select action\n actionIdx, actionIdxTuple = self.select_action(s, explore=True)\n\n # Interact with env\n s_, r, done, info = env.step(actionIdxTuple)\n epCost += r\n\n # Store the transition in memory\n self.store_transition(s, actionIdx, r, s_, info)\n s = s_\n\n # Check after fixed number of gradient updates\n if self.cntUpdate != 0 and self.cntUpdate % checkPeriod == 0:\n self.Q_network.eval()\n _, results, _ = env.simulate_trajectories(\n self.Q_network, T=MAX_EP_STEPS, num_rnd_traj=numRndTraj,\n keepOutOf=False, toEnd=False\n )\n success = np.sum(results == 1) / numRndTraj\n failure = np.sum(results == -1) / numRndTraj\n unfinish = np.sum(results == 0) / numRndTraj\n trainProgress.append([success, failure, unfinish])\n if verbose:\n lr = self.optimizer.state_dict()[\"param_groups\"][0][\"lr\"]\n print(\"\\n\\nAfter [{:d}] updates:\".format(self.cntUpdate))\n print(\n \" - eps={:.2f}, gamma={:.6f}, lr={:.1e}.\".format(\n self.EPSILON, self.GAMMA, lr\n )\n )\n print(\n \" - success/failure/unfinished ratio: \"\n + \"{:.3f}, {:.3f}, {:.3f}\".format(success, failure, unfinish)\n )\n\n if storeModel:\n if storeBest:\n if success > checkPointSucc:\n checkPointSucc = success\n self.save(self.cntUpdate, modelFolder)\n else:\n self.save(self.cntUpdate, modelFolder)\n\n if plotFigure or storeFigure:\n self.Q_network.eval()\n if showBool:\n env.visualize(self.Q_network, vmin=0, boolPlot=True)\n else:\n env.visualize(\n self.Q_network, vmin=vmin, vmax=vmax, cmap=\"seismic\"\n )\n if storeFigure:\n figurePath = os.path.join(\n figureFolder, \"{:d}.png\".format(self.cntUpdate)\n )\n plt.savefig(figurePath)\n if plotFigure:\n plt.show()\n plt.pause(0.001)\n plt.clf()\n plt.close('all')\n\n # Perform one step of the optimization (on the target network)\n lossC = self.update()\n trainingRecords.append(lossC)\n self.cntUpdate += 1\n self.updateHyperParam()\n\n # Terminate early\n if done and doneTerminate:\n break\n\n # Rollout report\n runningCost = runningCost*0.9 + epCost*0.1\n if verbose:\n print(\n \"\\r[{:d}-{:d}]: \".format(ep, self.cntUpdate)\n + \"This episode gets running/episode cost = \"\n + \"({:3.2f}/{:.2f}) after {:d} steps.\".\n format(runningCost, epCost, step_num + 1),\n end=\"\",\n )\n\n # Check stopping criteria\n if runningCostThr is not None:\n if runningCost <= runningCostThr:\n print(\n \"\\n At Updates[{:3.0f}] Solved!\".format(self.cntUpdate)\n + \" Running cost is now {:3.2f}!\".format(runningCost)\n )\n env.close()\n break\n endLearning = time.time()\n timeInitBuffer = endInitBuffer - startInitBuffer\n timeInitQ = endInitQ - startInitQ\n timeLearning = endLearning - startLearning\n self.save(self.cntUpdate, modelFolder)\n print(\n \"\\nInitBuffer: {:.1f}, InitQ: {:.1f}, Learning: {:.1f}\".format(\n timeInitBuffer, timeInitQ, timeLearning\n )\n )\n trainingRecords = np.array(trainingRecords)\n trainProgress = np.array(trainProgress)\n return trainingRecords, trainProgress"
] | [
"0.6228127",
"0.61634594",
"0.6074014",
"0.6050275",
"0.6050275",
"0.59674543",
"0.5956656",
"0.5953617",
"0.58580154",
"0.58394265",
"0.5830465",
"0.5820498",
"0.57669336",
"0.5730289",
"0.5701165",
"0.5655382",
"0.56536853",
"0.56534696",
"0.56493",
"0.5646722",
"0.56436014",
"0.564263",
"0.5642274",
"0.5635942",
"0.5623559",
"0.55814886",
"0.5569997",
"0.5568572",
"0.5562039",
"0.55414027"
] | 0.73664874 | 0 |
Gets the applicable_job_statuses of this Lifecycle. Job status needs to be in this list in order for the action to be performed! | def applicable_job_statuses(self):
return self._applicable_job_statuses | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def applicable_job_statuses(self, applicable_job_statuses):\n allowed_values = []\n if applicable_job_statuses not in allowed_values:\n raise ValueError(\n \"Invalid value for `applicable_job_statuses` ({0}), must be one of {1}\"\n .format(applicable_job_statuses, allowed_values)\n )\n\n self._applicable_job_statuses = applicable_job_statuses",
"def available_statuses(self):\n return self.pipeline.get(self.status, ())",
"def available_statuses(self):\n return self.pipeline.get(self.status, ())",
"def job_status(self) -> JobStatus:\n statuses = set()\n with self._jobs.lock:\n\n # No jobs present\n if not self._jobs:\n return JobStatus.DONE\n\n statuses = set()\n for job in self._jobs.values():\n if job:\n statuses.add(job.status())\n\n # If any jobs are in non-DONE state return that state\n for stat in [\n JobStatus.ERROR,\n JobStatus.CANCELLED,\n JobStatus.RUNNING,\n JobStatus.QUEUED,\n JobStatus.VALIDATING,\n JobStatus.INITIALIZING,\n ]:\n if stat in statuses:\n return stat\n\n return JobStatus.DONE",
"def asset_statuses(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['ZoneAssetStatusArgs']]]]:\n return pulumi.get(self, \"asset_statuses\")",
"def _get_status(self, context, object_list=None):\n status = self.request.GET.get(\"status\", \"\").upper()\n\n if object_list is not None:\n return self._get_object_list(\n object_list, status != \"\" and JobStatus.is_member(status), status=status\n )\n\n options = list(map(lambda s: (s.name, s.value), JobStatus))\n\n return {\n **context,\n \"status_options\": sorted(options, key=lambda x: x[0]),\n \"status\": status,\n }",
"def all_statuses(cls):\n return list(cls.pipeline.keys())",
"def all_statuses(cls):\n return list(cls.pipeline.keys())",
"def jobs(self) -> List[Job]:\n return self._jobs.values()",
"def approved_jobs(self):\n\n return Job.objects.filter(\n house=self.house,\n approved=True,\n )",
"def _get_job_status(self):\n total_hits = session.query(BoxHit).filter_by(training_job_id=self.id).count()\n num_hits_left = session.query(BoxHit).filter_by(training_job_id=self.id, outstanding=True).count()\n total_urls = self.num_urls\n num_urls_left = session.query(VideoTrainingURL).filter_by(job=self, processed=False).count()\n faces_obtained = MTurkBox.query.filter_by(label=self.evaluator.target_label, result=True).count()\n return '\\n'.join([\n '------------- Stats for Job ID: %s -------------' % str(self.id) ,\n 'Job for Label : %s' % self.label.name,\n 'Total URLs : %d' % total_urls,\n 'Total HITs : %d' % total_hits,\n 'unprocessed URLS : %d' % num_urls_left,\n 'outstanding Hits : %d' % num_hits_left,\n 'Job Finish Status : %s' % self.finished,\n 'Faces Obtained : %d' % faces_obtained,\n ]) + '\\n'",
"def get_jobs(self):\n return list(self._jobs.values())",
"def status(self):\n return self.job_proto.status",
"def status_enum(self):\n return self.valid_statuses()",
"def job_status(self, job_id):\n\n response = self.batch_client.describe_jobs(jobs=[job_id])\n return response[\"jobs\"][0][\"status\"]",
"def service_statuses(self) -> Optional[pulumi.Input['ServiceStatusesArgs']]:\n return pulumi.get(self, \"service_statuses\")",
"def valid_statuses(self):\n return [\n \"dish_maintenance\",\n \"dish_ok\",\n \"RF_maintenance\",\n \"RF_ok\",\n \"digital_maintenance\",\n \"digital_ok\",\n \"calibration_maintenance\",\n \"calibration_ok\",\n \"calibration_triage\",\n ]",
"def get_waiting_jobs(self):\n open_jobs = []\n with closing(self._conn.cursor()) as cursor:\n for row in cursor.execute( \"select job_name, job_version from jobs where job_state in ('\"\n + JobState.WAITING.value + \"','\" + JobState.WAITING_PRED.value + \"','\" + JobState.RUNNING.value +\"')\"):\n open_jobs.append((row[0], row[1]))\n return open_jobs",
"def do_status(self, args):\n status = self._leet.job_status\n\n for job in self.finished_jobs:\n status.append({\"id\" : job.id,\n \"hostname\" : job.machine.hostname,\n \"plugin\": job.plugin_instance.LEET_PG_NAME,\n \"status\" : job.status})\n if status:\n pretty_jobs_status(status)\n else:\n print(\"***No jobs pending\")",
"def get_completed_incore_jobs(self):\n self.completed_incore_jobs = list()\n for label, job_names in self.running_jobs.items():\n for job_name in job_names:\n i = get_i_from_job_name(job_name)\n if i is None:\n job_type = '_'.join(job_name.split('_')[:-1]) # Consider job types such as 'directed_scan'.\n job = self.job_dict[label][job_type][job_name]\n elif 'conformer' in job_name:\n job = self.job_dict[label]['conformers'][i]\n elif 'tsg' in job_name:\n job = self.job_dict[label]['tsg'][i]\n else:\n raise ValueError(f'Did not recognize job {job_name} of species {label}.')\n if job.execution_type == 'incore' and job.job_status[0] == 'done':\n self.completed_incore_jobs.append(job.job_id)",
"def active_jobs(self):\n \n active_jobs = []\n for job in self._jobs:\n if job.active:\n job.backend.status( job )\n active_jobs.append( job )\n\n self._active_jobs = active_jobs[:]\n\n return active_jobs",
"def status(self) -> ExperimentStatus:\n if all(\n len(container) == 0\n for container in [\n self._result_data,\n self._jobs,\n self._job_futures,\n self._analysis_callbacks,\n self._analysis_futures,\n self._figures,\n self._analysis_results,\n ]\n ):\n return ExperimentStatus.EMPTY\n\n # Return job status is job is not DONE\n try:\n return {\n JobStatus.INITIALIZING: ExperimentStatus.INITIALIZING,\n JobStatus.QUEUED: ExperimentStatus.QUEUED,\n JobStatus.VALIDATING: ExperimentStatus.VALIDATING,\n JobStatus.RUNNING: ExperimentStatus.RUNNING,\n JobStatus.CANCELLED: ExperimentStatus.CANCELLED,\n JobStatus.ERROR: ExperimentStatus.ERROR,\n }[self.job_status()]\n except KeyError:\n pass\n\n # Return analysis status if Done, cancelled or error\n try:\n return {\n AnalysisStatus.DONE: ExperimentStatus.DONE,\n AnalysisStatus.CANCELLED: ExperimentStatus.CANCELLED,\n AnalysisStatus.ERROR: ExperimentStatus.ERROR,\n }[self.analysis_status()]\n except KeyError:\n return ExperimentStatus.POST_PROCESSING",
"def _job_state_from_jobs(jobs):\n job_states = []\n for job in jobs:\n mongo_rec = job.to_mongo().to_dict()\n mongo_rec[\"_id\"] = str(job.id)\n mongo_rec[\"job_id\"] = str(job.id)\n mongo_rec[\"created\"] = int(job.id.generation_time.timestamp() * 1000)\n mongo_rec[\"updated\"] = int(job.updated * 1000)\n if job.estimating:\n mongo_rec[\"estimating\"] = int(job.estimating * 1000)\n if job.queued:\n mongo_rec[\"queued\"] = int(job.queued * 1000)\n if job.running:\n mongo_rec[\"running\"] = int(job.running * 1000)\n if job.finished:\n mongo_rec[\"finished\"] = int(job.finished * 1000)\n job_states.append(mongo_rec)\n return job_states",
"def get_job_status(self, job, context=None):\n return self._client.call_method(\n 'UserAndJobState.get_job_status',\n [job], self._service_ver, context)",
"def jobs(self):\n return self.get_jobs()",
"def job_ids(self):\n return self.get_job_ids()",
"def get_approval_statuses(self):\n approval_statuses = self.session.query(Approval).all()\n return approval_statuses",
"def jobs(self):\n return self._jobs",
"def get_statuses(self):\n return self.statuses",
"def get_job_list(self):\n return self.job_list"
] | [
"0.6967596",
"0.6617357",
"0.6617357",
"0.61123466",
"0.5901221",
"0.58656716",
"0.5798119",
"0.5798119",
"0.5790288",
"0.57691395",
"0.57252294",
"0.5707428",
"0.5665692",
"0.5640539",
"0.5625412",
"0.55947644",
"0.55841506",
"0.5555595",
"0.5541644",
"0.5536113",
"0.552849",
"0.552333",
"0.5489659",
"0.54779285",
"0.5452325",
"0.5446166",
"0.5443044",
"0.5432253",
"0.54300976",
"0.54220337"
] | 0.8614955 | 0 |
Sets the applicable_job_statuses of this Lifecycle. Job status needs to be in this list in order for the action to be performed! | def applicable_job_statuses(self, applicable_job_statuses):
allowed_values = []
if applicable_job_statuses not in allowed_values:
raise ValueError(
"Invalid value for `applicable_job_statuses` ({0}), must be one of {1}"
.format(applicable_job_statuses, allowed_values)
)
self._applicable_job_statuses = applicable_job_statuses | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def applicable_job_statuses(self):\n return self._applicable_job_statuses",
"def __init__(self, applicable_job_statuses=None, action_time=None, action=None, type=None):\n self.swagger_types = {\n 'applicable_job_statuses': 'list[str]',\n 'action_time': 'datetime',\n 'action': 'str',\n 'type': 'str'\n }\n\n self.attribute_map = {\n 'applicable_job_statuses': 'applicableJobStatuses',\n 'action_time': 'actionTime',\n 'action': 'action',\n 'type': 'type'\n }\n\n self._applicable_job_statuses = applicable_job_statuses\n self._action_time = action_time\n self._action = action\n self._type = type",
"def set_statuses(self, statuses):\n if not all((s in USBDeviceQuery.VALID_STATUSES) for s in statuses):\n raise ApiError(\"One or more invalid status values\")\n self._update_criteria(\"status\", statuses)\n return self",
"def job_status(self, job_status):\n\n self._job_status = job_status",
"def set_re_analysis_status(self, status_list):\n self.multiple_items_selection_from_kendo_dropdown(self.multiselect_status_dropdown_locator, status_list)",
"def set_job_status_for_interaction_model_v1(self, job_id, update_job_status_request, **kwargs):\n # type: (str, UpdateJobStatusRequest_f2d8379d, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, ValidationErrors_d42055a1]\n operation_name = \"set_job_status_for_interaction_model_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'job_id' is set\n if ('job_id' not in params) or (params['job_id'] is None):\n raise ValueError(\n \"Missing the required parameter `job_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_job_status_request' is set\n if ('update_job_status_request' not in params) or (params['update_job_status_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_job_status_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/jobs/{jobId}/status'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'job_id' in params:\n path_params['jobId'] = params['job_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'update_job_status_request' in params:\n body_params = params['update_job_status_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No content; Confirms that the fields are updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.jobs.validation_errors.ValidationErrors\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def set_multiple_status(self, status_list):\n self.multiple_items_selection_from_kendo_dropdown(self.status_kendo_dropdown_locator, status_list)\n self.wait_for_ajax_spinner_load()\n buy_page_title_element = self.wait().until(EC.element_to_be_clickable(self.buy_page_title_locator), 'buy page title locator not found before specified time out')\n buy_page_title_element.click()",
"def set_statement_status_for_search(self, status_list):\n self.multiple_items_selection_from_kendo_dropdown(self.statement_status_dropdown_locator, status_list)\n self.wait_for_ajax_spinner_load()",
"def _update_status(self, status: dict):\n with generate_retry_session() as session:\n session.headers.update({\n 'Authorization': 'Bearer {}'.format(self.platform_auth_token)\n })\n url = '{}/training/definitions/{}/jobs/{}/status'.format(\n ORGANIZATION_ENDPOINT, self.job_definition_name, self.training_job_id)\n res = session.put(url, json=status)\n res.raise_for_status()",
"def assert_update_job_statuses(self, processor, expected_job_statuses):\n actual_job_statuses = (map(lambda x: x['status'],\n processor.update_job_calls))\n self.assertEqual(expected_job_statuses, actual_job_statuses)",
"def update_status(self):\n\n # first get the instances we need to check\n monitor_jobs = {}\n for _, job_node in self.get_executions_iterator():\n if job_node.is_job:\n for job_instance in job_node.instances:\n if not job_instance.simulate:\n if job_instance.host in monitor_jobs:\n monitor_jobs[job_instance.host]['names'].append(\n job_instance.name)\n else:\n monitor_jobs[job_instance.host] = {\n 'config': job_instance.monitor_config,\n 'type': job_instance.monitor_type,\n 'workdir': job_instance.workdir,\n 'names': [job_instance.name],\n 'period': job_instance.monitor_period\n }\n else:\n job_instance.set_status('COMPLETED')\n\n # nothing to do if we don't have nothing to monitor\n if not monitor_jobs:\n return\n\n # then look for the status of the instances through its name\n states = self.jobs_requester.request(monitor_jobs, self.logger)\n\n # finally set job status\n for inst_name, state in states.iteritems():\n self.job_instances_map[inst_name].set_status(state)\n\n # We wait to slow down the loop\n sys.stdout.flush() # necessary to output work properly with sleep\n time.sleep(LOOP_PERIOD)",
"def status_ids(self, status_ids):\n\n self._status_ids = status_ids",
"def __set_job_status(self, job: Job):\n\n self.redis_client.set(f'jobstatus:{job.id}:{str(job.status)}', f'job:{job.id}')",
"def _set_status(self, action, status):\n raise NotImplementedError(\"Base class: cannot be called directly\")",
"def setAllowedStatus(self, allowedStatus: dict):\n self._allowedStatus = allowedStatus",
"def populate_deployment_statuses():\n _set_latest_execution()\n _set_installation_status()\n _set_deployment_status()",
"def set_adjustment_folder_status(self, adjustment_folder_status_list):\n self.multiple_items_selection_from_kendo_dropdown(self.adjustment_folder_status_kendo_dropdown_locator, adjustment_folder_status_list)\n self.wait_for_ajax_spinner_load()",
"def status(self, status):\n allowed_values = [\"I\", \"A\", \"S\", \"T\", \"D\"]\n if status not in allowed_values:\n raise ValueError(\n \"Invalid value for `status`, must be one of {0}\"\n .format(allowed_values)\n )\n self._status = status",
"def setup_jobs_for_status_check(cls, sess, submission_id):\n job_values = {\n 'uploadFinished': [FILE_TYPE_DICT['award'], JOB_STATUS_DICT['finished'],\n JOB_TYPE_DICT['file_upload'], None, None, None],\n 'recordRunning': [FILE_TYPE_DICT['award'], JOB_STATUS_DICT['running'],\n JOB_TYPE_DICT['csv_record_validation'], None, None, None],\n 'awardFin': [FILE_TYPE_DICT['award_financial'], JOB_STATUS_DICT['ready'],\n JOB_TYPE_DICT['csv_record_validation'], \"awardFin.csv\", 100, 100],\n 'appropriations': [FILE_TYPE_DICT['appropriations'], JOB_STATUS_DICT['ready'],\n JOB_TYPE_DICT['csv_record_validation'], \"approp.csv\", 2345, 567],\n 'program_activity': [FILE_TYPE_DICT['program_activity'], JOB_STATUS_DICT['ready'],\n JOB_TYPE_DICT['csv_record_validation'], \"programActivity.csv\", None, None],\n 'cross_file': [None, JOB_STATUS_DICT['finished'], JOB_TYPE_DICT['validation'], 2, None, None, None]\n }\n job_id_dict = {}\n approp_job = None\n\n for job_key, values in job_values.items():\n job = FileTests.insert_job(\n sess,\n filetype=values[0],\n status=values[1],\n type_id=values[2],\n submission=submission_id,\n filename=values[3],\n file_size=values[4],\n num_rows=values[5]\n )\n job_id_dict[job_key] = job.job_id\n if job_key == 'appropriations':\n approp_job = job\n elif job_key == 'cross_file':\n cross_file_job = job\n\n # For appropriations job, create an entry in file for this job\n file_rec = File(\n job_id=job_id_dict[\"appropriations\"],\n filename=\"approp.csv\",\n file_status_id=FILE_STATUS_DICT['complete'],\n headers_missing=\"missing_header_one, missing_header_two\",\n headers_duplicated=\"duplicated_header_one, duplicated_header_two\")\n sess.add(file_rec)\n\n cross_file = File(\n job_id=job_id_dict[\"cross_file\"],\n filename=\"approp.csv\",\n file_status_id=FILE_STATUS_DICT['complete'],\n headers_missing=\"\",\n headers_duplicated=\"\")\n sess.add(cross_file)\n\n # Put some entries in error data for approp job\n rule_error = ErrorMetadata(\n job_id=job_id_dict[\"appropriations\"],\n filename=\"approp.csv\",\n field_name=\"header_three\",\n error_type_id=ERROR_TYPE_DICT['rule_failed'],\n occurrences=7,\n rule_failed=\"Header three value must be real\",\n original_rule_label=\"A1\",\n file_type_id=FILE_TYPE_DICT['appropriations'],\n target_file_type_id=FILE_TYPE_DICT['award'],\n severity_id=RULE_SEVERITY_DICT['fatal']\n )\n approp_job.number_of_errors += 7\n sess.add(rule_error)\n\n warning_error = ErrorMetadata(\n job_id=job_id_dict[\"appropriations\"],\n filename=\"approp.csv\",\n field_name=\"header_three\",\n error_type_id=ERROR_TYPE_DICT['rule_failed'],\n occurrences=7,\n rule_failed=\"Header three value looks odd\",\n original_rule_label=\"A2\",\n file_type_id=FILE_TYPE_DICT['appropriations'],\n target_file_type_id=FILE_TYPE_DICT['award'],\n severity_id=RULE_SEVERITY_DICT['warning']\n )\n approp_job.number_of_warnings += 7\n sess.add(warning_error)\n\n req_error = ErrorMetadata(\n job_id=job_id_dict[\"appropriations\"],\n filename=\"approp.csv\",\n field_name=\"header_four\",\n error_type_id=ERROR_TYPE_DICT['required_error'],\n occurrences=5,\n rule_failed=\"This field is required for all submissions but was not provided in this row.\",\n severity_id=RULE_SEVERITY_DICT['fatal']\n )\n approp_job.number_of_errors += 5\n sess.add(req_error)\n\n cross_error = ErrorMetadata(\n job_id=job_id_dict[\"cross_file\"],\n filename=\"approp.csv\",\n field_name=\"header_four\",\n error_type_id=ERROR_TYPE_DICT['required_error'],\n occurrences=5,\n rule_failed=\"This field is required for all submissions but was not provided in this row.\",\n file_type_id=FILE_TYPE_DICT['appropriations'],\n target_file_type_id=FILE_TYPE_DICT['award'],\n severity_id=RULE_SEVERITY_DICT['fatal']\n )\n cross_file_job.number_of_errors += 5\n sess.add(cross_error)\n\n sess.commit()\n return job_id_dict",
"def update(self) -> None:\n self.previous_status = self.status\n\n jobs = self._client.describe_jobs(jobs = [ self.id ])[\"jobs\"]\n\n try:\n self.state = jobs[0]\n except IndexError:\n raise ValueError(\"Invalid or unknown job id %s\" % self.id) from None",
"def update_job_status(jid, new_status):\n jrd.hset(_generate_job_key(jid), 'status', new_status)",
"def set_status(self, scenario_id, status):\n self.cur.execute(\n \"UPDATE execute_list SET status = %s WHERE id = %s\",\n (status, scenario_id),\n )",
"def execute_jobs(job_statuses:list, verbose:bool=False):\n\tBaseModel._meta.database.close()\n\tBaseModel._meta.database = get_db()\n\tfor j in tqdm(\n\t\tjob_statuses\n\t\t, desc = \"🔮 Training Models 🔮\"\n\t\t, ncols = 100\n\t):\n\t\tif (j['result_id'] is None):\n\t\t\tJob.run(id=j['job_id'], verbose=verbose, repeat_index=j['repeat_index'])",
"def _set_status(self, status):\n with self.status_lock:\n if (status in _ENDING_STATUSES) or (not self.status in _ENDING_STATUSES):\n self.status = status",
"def update_job_status(jid, new_status):\n rd.hset(_generate_job_key(jid), 'status', new_status)",
"def status(self, status):\n allowed_values = [\"REQUESTED\", \"CREATE_IN_PROGRESS\", \"AVAILABLE\", \"UPDATE_IN_PROGRESS\", \"UPDATE_REQUESTED\", \"UPDATE_FAILED\", \"CREATE_FAILED\", \"ENABLE_SECURITY_FAILED\", \"PRE_DELETE_IN_PROGRESS\", \"DELETE_IN_PROGRESS\", \"DELETE_FAILED\", \"DELETE_COMPLETED\", \"STOPPED\", \"STOP_REQUESTED\", \"START_REQUESTED\", \"STOP_IN_PROGRESS\", \"START_IN_PROGRESS\", \"START_FAILED\", \"STOP_FAILED\", \"WAIT_FOR_SYNC\", \"MAINTENANCE_MODE_ENABLED\"]\n if status not in allowed_values:\n raise ValueError(\n \"Invalid value for `status` ({0}), must be one of {1}\"\n .format(status, allowed_values)\n )\n\n self._status = status",
"def setStatuses(self, urgency, status, comment, newOwner, currentUser, ruleUIDs, searchID, reviewTime, existing_statuses, capabilities, session_key):\n\n # Print a log message noting that an operation is about to happen\n if ruleUIDs is not None and searchID is not None:\n logger.info(\"About to edit events matching search %s (though only %d events are to be modified)\", searchID, len(ruleUIDs))\n if searchID is None and (ruleUIDs is not None and len(ruleUIDs) > 0):\n logger.info(\"About to edit events by ID (%d events are to be modified)\", searchID, len(ruleUIDs))\n else:\n logger.info(\"About to edit events matching all events matching search %s\", searchID)\n\n # Refresh the correlation searches list so we don't have to later\n self.refreshCorrelationSearches(session_key)\n\n # Perform the changes\n if searchID is None:\n result = self.setStatusByIDs(ruleUIDs, urgency, status, comment, newOwner, reviewTime, session_key, currentUser, existing_statuses=existing_statuses)\n logger.info(\"Done editing events\")\n return result\n else:\n result = self.setStatusBySearchID(searchID, urgency, status, comment, newOwner, reviewTime, capabilities, session_key, currentUser, force_refresh=False, rule_ids_to_change=ruleUIDs, existing_statuses=existing_statuses)\n logger.info(\"Done editing events matching search %s\", searchID)\n return result",
"def do_status(self, args):\n status = self._leet.job_status\n\n for job in self.finished_jobs:\n status.append({\"id\" : job.id,\n \"hostname\" : job.machine.hostname,\n \"plugin\": job.plugin_instance.LEET_PG_NAME,\n \"status\" : job.status})\n if status:\n pretty_jobs_status(status)\n else:\n print(\"***No jobs pending\")",
"def change_status(self, status):\n for option in status:\n response = requests.patch(self.base_url + 'settings', headers=self.headers, json={option: status.get(option)})\n print(f'[Mudando {option}] {response.status_code} - {response.ok}')",
"def apply_all(self):\n\n print(\"Are you sure? Enter 'y' if so\")\n\n if input() == 'y':\n\n for job in self.old_jobs:\n if job.is_relevant:\n job.reject('a') # 0 for apply\n self.jobs_save(self.old_jobs, 'overwrite')\n print('All relevant jobs have been marked as applied')\n\n else:\n print('returning to main menu')"
] | [
"0.6695411",
"0.5844042",
"0.5563415",
"0.5545432",
"0.5485883",
"0.5475218",
"0.5449763",
"0.5404465",
"0.5384887",
"0.53246635",
"0.53229064",
"0.5294377",
"0.52781755",
"0.52380747",
"0.5186252",
"0.5116745",
"0.50967646",
"0.5069076",
"0.50412786",
"0.502424",
"0.4990202",
"0.4987599",
"0.49841887",
"0.49797165",
"0.49660715",
"0.49211708",
"0.4906674",
"0.48774192",
"0.4837081",
"0.47992128"
] | 0.8249736 | 0 |
Gets the action_time of this Lifecycle. The time at which the job and files will be deleted, regardless of whether it has been retrieved or not. Maximal time is 1 day from job creation | def action_time(self):
return self._action_time | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def time_consumed(self) -> int:\n if not self.actions:\n return 0\n else:\n return self.actions[-1].time_end",
"def delete_time(self) -> str:\n return pulumi.get(self, \"delete_time\")",
"def delete_time(self) -> str:\n return pulumi.get(self, \"delete_time\")",
"def deleted_time(self) -> str:\n return pulumi.get(self, \"deleted_time\")",
"def run_time_sec(self):\n if self.job_updated_at is not None:\n return (self.job_updated_at - self.created_at).total_seconds()\n\n return None",
"def scheduled_deletion_time(self) -> Optional[datetime.datetime]:\n if not self.temporary:\n return None\n\n delta = Project.TEMPORARY_PROJECT_LIFESPANS.get(\n self.account.name, Project.TEMPORARY_PROJECT_LIFESPANS.get(\"default\")\n )\n return self.created + delta",
"def destroy_time(self) -> str:\n return pulumi.get(self, \"destroy_time\")",
"def action(self):\n return self.rowTime.activity",
"def ExpireTime(self):\n if self.force_auto_sync:\n self.get('ExpireTime')\n return self._ExpireTime",
"def last_time(self) -> datetime:\n return self.activities[-1].timestamp",
"def execution_time_sec(self):\n if self.job_started_at is not None:\n if self.job_completed_at is not None:\n return (self.job_completed_at -\n self.job_started_at).total_seconds()\n return None",
"def destroy_event_time(self) -> str:\n return pulumi.get(self, \"destroy_event_time\")",
"def when(self):\n\n # current UTC time\n now = datetime.datetime.utcnow()\n # calculate timedelta and return\n return now - self.creation_time",
"def get_last_action(self):\n return self.a_",
"def getPostJobSubmitTime(self):\n ent = self.getPostJob()\n if ent is None:\n return None\n return ent.submitTime",
"def get_time(self):\n return self.block.create_time",
"def get_time(self):\n # if the job is being processed or the CC had a crash return None\n if self.status <= 0:\n return None\n\n if self.status in (STATUS_FINISHED, 21):\n return self.resultTime\n\n return None",
"def submit_time(self) -> datetime:\n return self._submit_time",
"def get_time(self):\n return self._time",
"def get_time(self):\n return self._time",
"def get_time(self):\n return self._time",
"def completion_time(self) -> datetime:\n return self._completion_time",
"def update_last_triggered_time(self):\n returned_time = time.time() - self._last_triggered_time\n self._last_triggered_time = time.time()\n return returned_time",
"def time(self) -> int:\n return store.app.time",
"def get_time(self):\n return self.__time",
"def action_get_timestamp(action: TaxableAction) -> Timestamp:\n if isinstance(action, (Trade, AssetMovement, EthereumTransaction, DefiEvent)):\n return action.timestamp\n elif isinstance(action, (MarginPosition, Loan)):\n return action.close_time\n\n raise AssertionError(f'TaxableAction of unknown type {type(action)} encountered')",
"def get_time(self):\n return self.time",
"def create_time(self):\n return self._create_time",
"def create_time(self):\n return self._create_time",
"def create_time(self):\n return self._create_time"
] | [
"0.6351681",
"0.6334942",
"0.6334942",
"0.6254808",
"0.62357366",
"0.615849",
"0.61072457",
"0.6091936",
"0.6077282",
"0.60503584",
"0.59982574",
"0.5907601",
"0.5900668",
"0.58995885",
"0.5868122",
"0.5856616",
"0.5840132",
"0.57963824",
"0.57763684",
"0.57763684",
"0.57763684",
"0.577094",
"0.57696056",
"0.5759759",
"0.5751375",
"0.57499784",
"0.57287884",
"0.5717308",
"0.5717308",
"0.5717308"
] | 0.78159416 | 0 |
Sets the action_time of this Lifecycle. The time at which the job and files will be deleted, regardless of whether it has been retrieved or not. Maximal time is 1 day from job creation | def action_time(self, action_time):
self._action_time = action_time | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def action_time(self):\n return self._action_time",
"def on_action_time_changed(self, content):\n time = parse_iso_dt(content['time']).time()\n self.set_guarded(time=time)",
"def action(self, action):\n allowed_values = [\"DELETE\", \"NONE\"]\n if action not in allowed_values:\n raise ValueError(\n \"Invalid value for `action` ({0}), must be one of {1}\"\n .format(action, allowed_values)\n )\n\n self._action = action",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def create_time(self, create_time):\n\n self._create_time = create_time",
"def set_action(self,action):\n self.__action = action",
"def set_action(self, action):\n self._action = action\n return self",
"def creation_time(self, creation_time):\n\n self._creation_time = creation_time",
"def creation_time(self, creation_time):\n\n self._creation_time = creation_time",
"def setAction(self, action):\n self.action = action\n return self",
"def set_time(self, time):\n self._time = time",
"def set_remain_time(self, time):\n for task in self.tasks:\n task.remain_time = time",
"def set_creation_time(self, t: int) -> None:\n self.metadata.data[\"creation_time\"] = t",
"def submit_time(self, submit_time: datetime):\n\n self._submit_time = submit_time",
"def set_time(self, set_time):\n\n self._set_time = set_time",
"def expire_time(self, expire_time):\n\n self._expire_time = expire_time",
"def set_imeastime(self, time):\n self.itime = time",
"def set_action(self, action):\n self.action = action",
"def set_action(self, action):\n self.action = action",
"def _rescheduleFromRun(self, newTime):\n if newTime is None:\n self.deleteFromStore()\n else:\n self.time = newTime",
"def set_exec_time(self, time):\n for task in self.tasks:\n task.exec_time = time",
"def change_time(self, new_time):\r\n self.when = new_time"
] | [
"0.60692436",
"0.6039037",
"0.5710749",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55339384",
"0.55103743",
"0.5410098",
"0.53928286",
"0.53928286",
"0.5351073",
"0.5344618",
"0.53365284",
"0.53334916",
"0.5331133",
"0.53202665",
"0.530209",
"0.52992654",
"0.52817297",
"0.52817297",
"0.5281124",
"0.52786696",
"0.5255192"
] | 0.7611136 | 0 |
Sets the action of this Lifecycle. The action to perform. Currently only delete is supported | def action(self, action):
allowed_values = ["DELETE", "NONE"]
if action not in allowed_values:
raise ValueError(
"Invalid value for `action` ({0}), must be one of {1}"
.format(action, allowed_values)
)
self._action = action | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_action(self, action):\n self._action = action\n return self",
"def setAction(self, action):\n self.action = action\n return self",
"def set_action(self, action):\n self.action = action",
"def set_action(self, action):\n self.action = action",
"def set_action(self,action):\n self.__action = action",
"def action(self, action):\n if action is None:\n raise ValueError(\"Invalid value for `action`, must not be `None`\") # noqa: E501\n\n self._action = action",
"def setAction(self, value):\n return self._set(action=value)",
"def action(self, action):\n self._action = action",
"def action(self, action):\n\n self._action = action",
"def _set_action(self, v, load=False):\n try:\n t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_type=\"dict_key\", restriction_arg={u'Drop': {}, u'NativelyForward': {}, u'SendMapRequest': {}, u'NoAction': {}},), is_leaf=True, yang_name=\"action\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True)\n except (TypeError, ValueError):\n raise ValueError(\"\"\"action must be of a type compatible with base=RestrictedClassType(base_type=unicode, restriction_type=\"dict_key\", restriction_arg={u'Drop': {}, u'NativelyForward': {}, u'SendMapRequest': {}, u'NoAction': {}},), is_leaf=True, yang_name=\"action\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True\"\"\")\n self.__action = t\n if hasattr(self, '_set'):\n self._set()",
"def _set_action(self, action):\n raise NotImplementedError()",
"def _set_action(self, action):\n raise NotImplementedError()",
"def _set_action(self, action):\n raise NotImplementedError()",
"def _set_action(self, action):\n raise NotImplementedError()",
"def _set_action(self, action):\n raise NotImplementedError()",
"def _set_action(self, action):\n raise NotImplementedError()",
"def _act(self, action):\n self._set_action(action)",
"def set_action(self, action):\n if action not in self.images:\n raise Exception('Action not defined for {}'.format(\n self.__name__\n ))\n self._action_i = 0\n self._action = action",
"def action(self, action):\n allowed_values = [\"Start\", \"Pause\", \"Resume\", \"Retry\",\n \"Cancel\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and action not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `action` ({0}), must be one of {1}\" # noqa: E501\n .format(action, allowed_values))\n\n self._action = action",
"def action(self, action):\n allowed_values = [\"APPLY\", \"PRECHECK\"]\n if action not in allowed_values:\n raise ValueError(\n \"Invalid value for `action`, must be one of {0}\"\n .format(allowed_values)\n )\n self._action = action",
"def add_action(self, action):\n self.action = action",
"def add_action(self, action):\n self.action = action",
"def setAction(self, func):\n\t\tself.action = func",
"def _set_action(self, action):\n\n rospy.logdebug(\"Start Set Action ==>\"+str(action))\n # We convert the actions to speed movements to send to the parent class of Parrot\n linear_speed_vector = Vector3()\n angular_speed = 0.0\n\n if action == 0: # FORWARDS\n linear_speed_vector.x = self.linear_forward_speed\n self.last_action = \"FORWARDS\"\n elif action == 1: # BACKWARDS\n linear_speed_vector.x = -1*self.linear_forward_speed\n self.last_action = \"BACKWARDS\"\n elif action == 2: # STRAFE_LEFT\n linear_speed_vector.y = self.linear_forward_speed\n self.last_action = \"STRAFE_LEFT\"\n elif action == 3: # STRAFE_RIGHT\n linear_speed_vector.y = -1*self.linear_forward_speed\n self.last_action = \"STRAFE_RIGHT\"\n elif action == 4: # UP\n linear_speed_vector.z = self.linear_forward_speed\n self.last_action = \"UP\"\n elif action == 5: # DOWN\n linear_speed_vector.z = -1*self.linear_forward_speed\n self.last_action = \"DOWN\"\n\n # We tell drone the linear and angular speed to set to execute\n self.move_base(linear_speed_vector,\n angular_speed,\n epsilon=0.05,\n update_rate=10)\n\n rospy.logdebug(\"END Set Action ==>\"+str(action))",
"def action_flow(self, action_flow):\n\n self._action_flow = action_flow",
"def receiveAction(self, action):\n self.action = action",
"def set_sample_action(self, sample_action):\n\n self.sample_action = sample_action",
"def add_action(self, action):\n self._actions.append(action)",
"def do_action(self, action, **kwargs):\r\n print(action)\r\n action_method = getattr(self, action._method.__name__)\r\n if action_method:\r\n action_method(**kwargs)",
"def get_action(self, action=None):\n if action:\n self.action = action\n\n if self.action not in AjaxResponseAction.choices:\n raise ValueError(\n \"Invalid action selected: '{}'\".format(self.action))\n\n return self.action"
] | [
"0.798209",
"0.7937381",
"0.78521293",
"0.78521293",
"0.77787465",
"0.7659929",
"0.7434554",
"0.7401559",
"0.73724025",
"0.7369807",
"0.72310543",
"0.72310543",
"0.72310543",
"0.72310543",
"0.72310543",
"0.72310543",
"0.70674974",
"0.699461",
"0.6960725",
"0.6901665",
"0.67269754",
"0.67269754",
"0.65749985",
"0.61473775",
"0.6065236",
"0.60366935",
"0.59507054",
"0.58983266",
"0.58731747",
"0.5867936"
] | 0.7996904 | 0 |
Sets the type of this Lifecycle. Determine when to delete the job and associated files. RETRIEVAL means delete directly after retrieving the PDF file. When the file has not been retrieved before the action time, it will be deleted regardless. Time means, delete on specific time, regardless of whether it has been processed | def type(self, type):
allowed_values = ["RETRIEVAL", "TIME"]
if type not in allowed_values:
raise ValueError(
"Invalid value for `type` ({0}), must be one of {1}"
.format(type, allowed_values)
)
self._type = type | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def __init__(__self__, *,\n duration: pulumi.Input[str],\n object_type: pulumi.Input[str]):\n pulumi.set(__self__, \"duration\", duration)\n pulumi.set(__self__, \"object_type\", 'AbsoluteDeleteOption')",
"def ExpireType(self):\n if self.force_auto_sync:\n self.get('ExpireType')\n return self._ExpireType",
"def __init__(__self__, *,\n duration: str,\n object_type: str):\n pulumi.set(__self__, \"duration\", duration)\n pulumi.set(__self__, \"object_type\", 'AbsoluteDeleteOption')",
"def job_type(self, job_type):\n self._job_type = job_type",
"def _rescheduleFromRun(self, newTime):\n if newTime is None:\n self.deleteFromStore()\n else:\n self.time = newTime",
"def set_execution_type(self, type):\n self.execution_type = type",
"def task_type(self, task_type):\n\n self._task_type = task_type",
"def delete(self, type=None, name=None, identity=None):\n if name and identity:\n name = None # Only specify one\n request = self.request(operation='DELETE', type=type, name=name,\n identity=identity)\n self.call(request, expect=error.NO_CONTENT)",
"def type(self, type):\n allowed_values = [\"None\", \"File\", \"FileManagerFile\", \"BusOb\", \"History\", \"Other\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and type not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `type` ({0}), must be one of {1}\" # noqa: E501\n .format(type, allowed_values)\n )\n\n self._type = type",
"def mime_type(self, mime_type):\n\n self._mime_type = mime_type",
"def delete(self, key, key_type=None):\n pass",
"def delete_time(self) -> str:\n return pulumi.get(self, \"delete_time\")",
"def delete_time(self) -> str:\n return pulumi.get(self, \"delete_time\")",
"def type(self, type: str):\n allowed_values = [\"daylight_factor\", \"annual\", \"radiation\", \"direct_reflection\", \"five_phase\", \"point_in_time\", \"solar_access\", \"three_phase\"] # noqa: E501\n if type not in allowed_values:\n raise ValueError(\n \"Invalid value for `type` ({0}), must be one of {1}\"\n .format(type, allowed_values)\n )\n\n self._type = type",
"def delete_action(self, type_of_action):\n if(type(type_of_action) != str):\n self._logger.write(\"Error! type_of_action must be of type string\")\n elif(type_of_action == None):\n self._logger.write(\"Error! type_of_action contains no value\")\n elif(len(self._types_of_actions) == 0):\n self._logger.write(\"Error! types_of_actions list is empty\")\n else:\n try:\n self._types_of_actions.remove(type_of_action)\n except Exception as e:\n self._logger.write(\"Error! could not remove type_of_action from types_of_actions list:\\n %s\" % e)",
"def delete(self, filetype_ref):\n\n fileformat = self.get_by_ref(filetype_ref)\n if fileformat is not None:\n if fileformat.delete() == 0:\n del self.__filetypeList[filetype_ref]\n return 0\n else:\n return 1\n else:\n print_error(\"File format type with id %s not found\" % filetype_ref)\n return 1",
"def type(self, type):\n allowed_values = [\"WORKSPACE\", \"PLAN\", \"FLOW\", \"ACTION\", \"CONNECTION\", \"RESOURCE\", \"ENGINE\", \"CLUSTER\", \"FOLDER\"] # noqa: E501\n if type not in allowed_values:\n raise ValueError(\n \"Invalid value for `type` ({0}), must be one of {1}\" # noqa: E501\n .format(type, allowed_values)\n )\n\n self._type = type",
"def type(self, type):\n allowed_values = [\"CREATE\", \"CLOSE\", \"REOPEN\", \"CLIENT_CONFIGURE\", \"CLIENT_CONFIGURE_REJECT\", \"TRANSFER_FUNDS\", \"TRANSFER_FUNDS_REJECT\", \"MARKET_ORDER\", \"MARKET_ORDER_REJECT\", \"FIXED_PRICE_ORDER\", \"LIMIT_ORDER\", \"LIMIT_ORDER_REJECT\", \"STOP_ORDER\", \"STOP_ORDER_REJECT\", \"MARKET_IF_TOUCHED_ORDER\", \"MARKET_IF_TOUCHED_ORDER_REJECT\", \"TAKE_PROFIT_ORDER\", \"TAKE_PROFIT_ORDER_REJECT\", \"STOP_LOSS_ORDER\", \"STOP_LOSS_ORDER_REJECT\", \"TRAILING_STOP_LOSS_ORDER\", \"TRAILING_STOP_LOSS_ORDER_REJECT\", \"ORDER_FILL\", \"ORDER_CANCEL\", \"ORDER_CANCEL_REJECT\", \"ORDER_CLIENT_EXTENSIONS_MODIFY\", \"ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT\", \"TRADE_CLIENT_EXTENSIONS_MODIFY\", \"TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT\", \"MARGIN_CALL_ENTER\", \"MARGIN_CALL_EXTEND\", \"MARGIN_CALL_EXIT\", \"DELAYED_TRADE_CLOSURE\", \"DAILY_FINANCING\", \"RESET_RESETTABLE_PL\"] # noqa: E501\n if type not in allowed_values:\n raise ValueError(\n \"Invalid value for `type` ({0}), must be one of {1}\" # noqa: E501\n .format(type, allowed_values)\n )\n\n self._type = type",
"def schedule_type(self, schedule_type):\n\n self._schedule_type = schedule_type",
"def schedule_type(self, schedule_type):\n\n self._schedule_type = schedule_type",
"def delete(self, trash=True, **kwargs):\n if self.is_trashed or not trash:\n super(Picture, self).delete()\n return\n\n self.trashed_time = datetime.now()\n self.save()",
"def delete(**args):\n\tglobal _objstore\n\t_objstore = _objstore or ObjStore()\n\n\t_objstore.delete(args['type'], args['name'])\n\treturn {'message':'ok'}",
"def change_type(self, change_type):\n\n self._change_type = change_type",
"def predio_delete(sender, instance, **kwargs):\n instance.dataFile.delete(False)",
"def recurrence_type(self, recurrence_type):\n allowed_values = [\"None\", \"Minute\", \"Hour\", \"Day\", \"Week\", \"Month\", \"Year\"] # noqa: E501\n if recurrence_type not in allowed_values:\n raise ValueError(\n \"Invalid value for `recurrence_type` ({0}), must be one of {1}\" # noqa: E501\n .format(recurrence_type, allowed_values)\n )\n\n self._recurrence_type = recurrence_type",
"def execution_type(self, execution_type):\n self._execution_type = execution_type",
"def delete(self):\n self.connection.deprecate_activity_type(self.domain.name, self.name, self.version)",
"def execute(self):\r\n self.changeAttr(\"changeType\", \"delete\")\r\n self.changeAttr(\"changeMark\", \"1\")",
"def file_type(self, file_type):\n allowed_values = [undefined, undefined, undefined, ] # noqa: E501\n\n self._file_type = file_type",
"def set_action_type(self, action_type):\n self.single_selection_from_kendo_dropdown(self.action_type_kendo_dropdown_locator, action_type)\n self.wait_for_ajax_spinner_load()"
] | [
"0.55426234",
"0.54422",
"0.54303664",
"0.5243352",
"0.5130753",
"0.51242626",
"0.49633163",
"0.49580863",
"0.4862699",
"0.4837523",
"0.48264766",
"0.47609124",
"0.47609124",
"0.47589472",
"0.47226307",
"0.4716207",
"0.4709835",
"0.46772438",
"0.46732327",
"0.46732327",
"0.46679085",
"0.46529922",
"0.46367505",
"0.46269587",
"0.46127063",
"0.4607508",
"0.45999816",
"0.4590433",
"0.45900717",
"0.4549118"
] | 0.5637675 | 0 |
Basic test for findService parsing with a civic address. | def test_findservice_civic_address(self):
xml = """
<findService xmlns="urn:ietf:params:xml:ns:lost1" serviceBoundary="reference">
<location id="ce152f4b-2ade-4e37-9741-b6649e2d87a6" profile="civic">
<civ:civicAddress xmlns:civ="urn:ietf:params:xml:ns:pidf:geopriv10:civicAddr">
<civ:country>US</civ:country>
<civ:A1>ME</civ:A1>
<civ:A2>Piscataquis</civ:A2>
<civ:A3>T3 R11 Wels</civ:A3>
<civ:RD>Golden</civ:RD>
<civ:STS>Rd</civ:STS>
<civ:HNO>5833</civ:HNO>
<civ:PC>00135</civ:PC>
</civ:civicAddress>
</location>
<service>urn:nena:service:sos</service>
</findService>
"""
root = etree.fromstring(xml)
target = FindServiceXmlConverter()
result = target.parse(root)
self.assertEqual(result.location.id, 'ce152f4b-2ade-4e37-9741-b6649e2d87a6') | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_client_address_retrieve(self):\n pass",
"def test_ipam_services_read(self):\n pass",
"def test_get_service_string(self):\n pass",
"def test_get_virtual_service(self):\n pass",
"def testParse(self):\n services = self._getServices()",
"def test_ipam_services_list(self):\n pass",
"def test_virtualservice_get(self):\n pass",
"def test_address_info(self):\n from supvisors.rpcinterface import RPCInterface\n # prepare context\n self.supervisor.supvisors.context.addresses = {\n '10.0.0.1': Mock(**{'serial.return_value': 'address_info'})}\n # create RPC instance\n rpc = RPCInterface(self.supervisor)\n # test with known address\n self.assertEqual('address_info', rpc.get_address_info('10.0.0.1'))\n # test with unknown address\n with self.assertRaises(RPCError) as exc:\n rpc.get_address_info('10.0.0.0')\n self.assertEqual(Faults.BAD_ADDRESS, exc.exception.code)\n self.assertEqual('BAD_ADDRESS: address 10.0.0.0 unknown in Supvisors',\n exc.exception.text)",
"def test_get_order_address(self):\n pass",
"def test_address_page(self):\n tester = app.test_client(self)\n response = tester.get('/', content_type = \"html_text\")\n self.assertTrue(b'Address Locator' in response.data)",
"def test_ipam_services_create(self):\n pass",
"def test_client_address_create(self):\n pass",
"def find_service(iface, context, name):",
"def test_service():\n ddo = get_sample_ddo()\n sa = ddo.get_service(ServiceTypes.ASSET_ACCESS)\n assert sa.get_cost() == 1.0\n assert sa.get_c2d_address()\n assert sa.main[\"name\"] == \"dataAssetAccessServiceAgreement\"\n\n assert \"attributes\" in sa.as_dictionary()\n converted = Service.from_json(sa.as_dictionary())\n assert converted.attributes == sa.attributes\n assert converted.service_endpoint == sa.service_endpoint\n assert converted.type == sa.type\n assert converted.index == sa.index",
"def test_client_addresses_list(self):\n pass",
"def find(self, text: unicode) -> ghidra.program.model.address.Address:\n ...",
"def test_unknown_service(self):\n raise NotImplementedError # FIXME",
"def test_add_virtual_service(self):\n pass",
"def test_get_contracts_addresses_empty():\n addresses = ContractHandler.get_contracts_addresses(_NETWORK, address_file=None)\n assert addresses is None",
"def test_build__valid_input(self, valid_service: fixture) -> None:\n service: Service = valid_service\n\n assert service.name == 'Testing Service'",
"async def test_get_organization_address(client):\n params = [('access_token', 'access_token_example')]\n headers = { \n 'Accept': 'application/json',\n }\n response = await client.request(\n method='GET',\n path='/v1/addresses/{address_id}'.format(address_id=56),\n headers=headers,\n params=params,\n )\n assert response.status == 200, 'Response body is : ' + (await response.read()).decode('utf-8')",
"def test_get_and_has__name_and_address(network, example_config):\n addresses = ContractHandler.get_contracts_addresses(\n network, example_config.address_file\n )\n target_address = addresses[\"DTFactory\"]\n\n contract = ContractHandler.get(\"DTFactory\", target_address)\n assert \"createToken\" in str(contract.abi)\n assert contract.address == addresses[\"DTFactory\"]\n\n assert ContractHandler.has(\"DTFactory\", target_address)\n assert not ContractHandler.has(\"foo name\", \"foo address\")\n assert not ContractHandler.has(\"foo name\", contract.address)\n assert not ContractHandler.has(\"DTFactory\", \"foo address\")",
"def test_get_services_html(self):\n pass",
"def test_addr_city_good_values(self):\n for input_val, output_val in self.known_values:\n self.line._parse_addr_city(input_val)\n self.assertEqual(output_val, self.line.addr_city)",
"def test_networking_project_network_service_get(self):\n pass",
"def test_city_country(self):\n\t\tformatted_address = city_country('santiago', 'chile')\n\t\tself.assertEqual(formatted_address, 'Santiago, Chile')",
"def test_get_eligible_shipment_services(self):\n pass",
"def test_get_contracts_addresses_bad_path():\n addresses = ContractHandler.get_contracts_addresses(\n _NETWORK, address_file=\"/bin/foo/bar/tralala\"\n )\n assert addresses is None",
"def test_get_contact(self):\n pass",
"def search_service(self, name_filter):\n rs=search_service(name_filter)\n for el in rs:\n print(el)"
] | [
"0.64207476",
"0.62982064",
"0.62926865",
"0.62176013",
"0.6189355",
"0.60833365",
"0.606279",
"0.5928941",
"0.5896843",
"0.58331347",
"0.57547104",
"0.5736013",
"0.56428236",
"0.56183106",
"0.5606168",
"0.55707866",
"0.5561389",
"0.5544311",
"0.55386513",
"0.5505321",
"0.54591113",
"0.54583097",
"0.54466605",
"0.5436617",
"0.54173785",
"0.5414928",
"0.5405592",
"0.53986853",
"0.5367732",
"0.5342349"
] | 0.7775548 | 0 |
Returns the dialogueIDth caption from vttFile | def getCaptionFromVTTcaptionFile(vttFile, dialogueID):
import webvtt
return webvtt.read(vttFile)[dialogueID].text | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def caption(self):\n return self._caption",
"def get_caption(self):\n try:\n return self.canvas.getID()\n except (TypeError, AttributeError):\n return self.id",
"def __load_dialogue_ids(self, filename):\n with open(filename, \"r\") as file:\n return file.readlines()[0].split()",
"def getTextIdForCaption(elm):\n #the obvious case #1\n text = getFirstChildWithTagName(elm, \"text\")\n #the less-obvious cases\n if text == None:\n promptItem = getFirstChildWithTagName(elm, \"promptItem\")\n if promptItem == None:\n prompt = getFirstChildWithTagName(elm, \"prompt\")\n if prompt == None: return \"\"\n else:\n promptItem = getFirstChildWithTagName(prompt, \"promptItem\")\n if promptItem == None: return \"\"\n #promptItem variable better have something in it at this point\n return getTextIdFromPromptItem(promptItem)\n else:\n return text.getAttribute(\"id\")",
"def process_caption(caption, figure_num):\n caption = caption.replace('III', '3').replace('II', '2').replace(' I ', '1').replace('I:', '1:')\n caption = caption.lower().split(figure_num)[1].split('figure')[0].split('fig')[0].split('table')[0]\n caption = caption.split('....')[0]\n caption = caption.lstrip(' .').lstrip(' :')\n return caption",
"def get_captions(video_id):\n try:\n transcript = YouTubeTranscriptApi.get_transcript(video_id)\n \n #parse only string and remove the time of captions\n text = []\n for txt in transcript:\n text.append(txt['text'])\n return text\n except:\n text = \"No Captions\"\n return text",
"def Caption(self, default=None):\n return self.data.get('caption', default)",
"def vim_id(self):\n return self._vim_id",
"def get_command(self):\n return 'caption'",
"def get_reference_header(file):\n\n with open(file, \"r\") as typing_report:\n lines = typing_report.readlines()\n return lines[1].split('\\\\t')[3]",
"def extract_subtitle_track(path_to_mkv):\n handler = SubtitleHandler()\n with open(path_to_mkv, \"rb\") as fp:\n mkvparse.mkvparse(fp, handler)\n\n return handler.subs",
"def get_file_name(self):\n dialog = gtk.FileChooserDialog(\"Open..\",\n None,\n gtk.FILE_CHOOSER_ACTION_OPEN,\n (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,\n gtk.STOCK_OPEN, gtk.RESPONSE_OK))\n dialog.set_default_response(gtk.RESPONSE_OK)\n response = dialog.run()\n\n if response == gtk.RESPONSE_OK:\n self.file_name = dialog.get_filename()\n self.tot_rows = len(open(self.file_name).readlines())\n self.ifile = open(self.file_name)\n self.reader = csv.reader(self.ifile)\n self.row = self.reader.next()\n dialog.destroy()\n elif response == gtk.RESPONSE_CANCEL:\n print 'Closed, no file selected.'\n dialog.destroy()",
"def get_fedcm_dialog_title(self):\n pass",
"def test_caption(self):\n inv_search = \"caption:muon\"\n spi_search = \"find caption muon\"\n self._compare_searches(inv_search, spi_search)",
"def get_tnamed(infile, tnamed, subdir='',verbose=False):\n\n ## TNamed Object\n tnamed = getter(infile,tnamed,subdir,verbose)\n return tnamed.GetTitle()",
"def comdlg32_GetFileTitle(jitter, get_str, set_str):\n ret_ad, args = jitter.func_args_stdcall([\"lpszFile\", \"lpszTitle\", \"cbBuf\"])\n raise RuntimeError('API not implemented')\n jitter.func_ret_stdcall(ret_ad, ret_value)",
"def get_caption_comments(content):\n\n if not content.startswith('## fig:'):\n return None, None\n\n content = content.splitlines()\n\n id = content[0].strip('## ')\n\n caption = []\n for line in content[1:]:\n if not line.startswith('# ') or line.startswith('##'):\n break\n else:\n caption.append(line.lstrip('# ').rstrip())\n\n # add \" around the caption. TODO: consider doing this upstream\n # in pandoc-attributes\n caption = '\"' + ' '.join(caption) + '\"'\n return id, caption",
"def get_verse_text(verse_id: int, version: Version = DEFAULT_VERSION) -> Optional[str]:\n if verse_id not in VERSE_IDS:\n raise InvalidVerseError(verse_id=verse_id)\n\n try:\n version_verse_texts: Dict[int, str] = _get_version_verse_texts(version)\n except FileNotFoundError as e:\n raise MissingVerseFileError(e)\n\n return version_verse_texts.get(verse_id)",
"def GetPageText(self, page_idx):\r\n \r\n if page_idx >= self._tabs.GetPageCount():\r\n return \"\"\r\n\r\n # update our own tab catalog\r\n page_info = self._tabs.GetPage(page_idx)\r\n return page_info.caption",
"def get_title(filename):\n _,long_name = filename.split(\"\\\\\")\n name,_ = long_name.split(\"_gold_\")\n f = os.path.join(FIXED, name + \".fix\")\n #with open(f, 'r') as in_f:\n with codecs.open(f, 'r', encoding='utf-8') as in_f:\n lines = in_f.readlines()\n i = 0\n line = lines[i]\n while len(line) < 5:\n i += 1\n line = lines[i]\n return lines[i]",
"def read_cue(file, verbose=False):\n # Read the full Cue file.\n if(verbose):\n print(f'Parsing {file}...', flush=True)\n lines = None\n for encoding in encodings_to_test:\n try:\n with open(file, 'r', encoding=encoding) as f:\n lines = f.readlines()\n if(verbose):\n print(f'Parsed using \"{encoding}\" encoding.', flush=True)\n break\n except UnicodeError:\n pass\n\n if(lines is None):\n raise UnicodeError('Unable to find appropriate encoding for input file.')\n\n cue = {}\n cue['Files'] = {}\n # Line index. We don't use a for loop as we will\n # read multiple lines for information.\n i = 0\n try:\n while(True):\n # We have a FILE specification in the Cue sheet.\n if(lines[i].startswith('FILE')):\n # Get the filename.\n filename = lines[i].split('\"')[1]\n # Now we will parse the tracks from the file.\n # Use a local variable name for clarity.\n file_details = {}\n # But store that variable in the cue sheet parse dictionary.\n cue['Files'][filename] = file_details\n # Create the Track entry to store tracks from the file.\n file_details['Tracks'] = {}\n # Start at the next line.\n i += 1\n # Use the Cue sheet indentation for sectioning. 2 spaces for\n # TRACK entries in the FILE entry.\n while(lines[i].startswith(' '*2)):\n # Get rid of extra white space.\n line = lines[i].strip()\n # Handle TRACK entries.\n if(line.startswith('TRACK')):\n # Get the track number.\n track = int(line.split()[1])\n # Use a local variable name for clarity.\n track_details = {}\n # But store that variable in the cue sheet parse dictionary.\n file_details['Tracks'][track] = track_details\n # Create the INDEX dictionary to store track indices.\n track_details['INDEX'] = {}\n # Start at the next line.\n i += 1\n # Use the Cue sheet indentation for sectioning. 4 spaces\n # for INDEX entries in the TRACK entry.\n while(lines[i].startswith(' '*4)):\n # Get rid of extra white space.\n line = lines[i].strip()\n # Find the index entries.\n if(line.startswith('INDEX')):\n # Remove the INDEX text and extra white space.\n line = line[5:].strip()\n # Get the INDEX number and the rest of the line.\n # The rest of the line should be the time information.\n key, value = line.split(None, 1)\n # Store the time information for this index.\n track_details['INDEX'][int(key)] = value.strip().replace('\"', '')\n i += 1\n else:\n # Store all the other entries as text. Use the first\n # word as the access key.\n key, value = line.split(None, 1)\n # Also remove quotes from track names and similar.\n track_details[key] = value.strip().replace('\"', '')\n i += 1\n else:\n # Store all the other entries as text. Use the first\n # word as the access key.\n key, value = lines[i].split(None, 1)\n # Also remove quotes from track names and similar.\n file_details[key] = value.strip().replace('\"', '')\n i += 1\n else:\n # Store all the other entries as text. Use the first\n # word as the access key.\n key, value = lines[i].split(None, 1)\n # Also remove quotes from track names and similar.\n cue[key] = value.strip().replace('\"', '')\n i += 1\n except IndexError:\n # We're done.\n pass\n return cue",
"def _get_track_name(self, filename):\n return os.path.basename(filename)",
"def __getitem__(self, index):\n matrix_id = self.dialogue_ids[index]\n return torch.load('data/dialogue-' + matrix_id + '.pt')",
"def get_emotion_label(self, file_name):\n file_name = file_name[:-4]\n emotion_name = file_name.split('_')[-1] # the last is a position of emotion code\n return emotion_name",
"def _header_from_vcf(vcf_path):\n vcf_lines_generator = lines_from_vcf(vcf_path)\n\n for line in vcf_lines_generator:\n if line.startswith('#CHROM'):\n vcf_lines_generator.close() # Don't leave the file handle opened\n return line.strip().replace('#CHROM', 'CHROM').split('\\t')",
"def get_utterances_from_filename(dialog_csv_filename):\n with open(dialog_csv_filename, \"r\") as dialog_csv_file:\n return get_utterances_from_file(dialog_csv_file)",
"def _read_vtc(vtc_file):\r\n with open(vtc_file, 'rb') as f:\r\n filebytes = f.read()\r\n\r\n hdr = {}\r\n hdr['file_guid'] = hexlify(filebytes[:16])\r\n # not sure about the 4 Bytes inbetween\r\n\r\n i = 20\r\n mpg_file = []\r\n start_time = []\r\n end_time = []\r\n while i < len(filebytes):\r\n mpg_file.append(_make_str(unpack('c' * 261, filebytes[i:i + 261])))\r\n i += 261\r\n Location = filebytes[i:i + 16]\r\n correct = b'\\xff\\xfe\\xf8^\\xfc\\xdc\\xe5D\\x8f\\xae\\x19\\xf5\\xd6\"\\xb6\\xd4'\r\n assert Location == correct\r\n i += 16\r\n start_time.append(_filetime_to_dt(unpack('<q',\r\n filebytes[i:(i + 8)])[0]))\r\n i += 8\r\n end_time.append(_filetime_to_dt(unpack('<q',\r\n filebytes[i:(i + 8)])[0]))\r\n i += 8\r\n\r\n return mpg_file, start_time, end_time",
"def get_rvt_file_version(rvt_file):\n file_info = get_basic_info(rvt_file, cleaned_str=True)\n re_version = re.compile(r\"Format: (\\d{4})\")\n found = re.findall(re_version, file_info)\n if found:\n rvt_file_version = found[0]\n else:\n re_version = re.compile(r\"Autodesk Revit (\\d{4})\")\n rvt_file_version = re.findall(re_version, file_info)[0]\n return rvt_file_version",
"def openFileExplorer(self, caption=''):\n\n file_path = None\n file_path, idk = QFileDialog.getOpenFileName(caption=caption)\n\n if file_path == '':\n file_path = None\n\n return file_path",
"def user_response(self, dialog_number: int):\n return self.rtext[dialog_number][0]"
] | [
"0.59000456",
"0.58283216",
"0.5773122",
"0.55387735",
"0.54730004",
"0.54553735",
"0.53017414",
"0.52924526",
"0.52771646",
"0.5201588",
"0.5136322",
"0.51156497",
"0.51120484",
"0.50966525",
"0.5068463",
"0.5060997",
"0.50441873",
"0.50228816",
"0.49699327",
"0.49609575",
"0.49497628",
"0.4940743",
"0.49221414",
"0.49158138",
"0.4894647",
"0.48877555",
"0.48629335",
"0.48622715",
"0.4855993",
"0.48527914"
] | 0.8716171 | 0 |
returns True (if same emotion) | def compareEmotionSimilarity(audioFile, emotion, emoPredictor, verbose=False, profile=False):
error = ""
if (profile): start = time.time()
# from speech_to_emotion.emotion_classifier_nn import livePredictions
# emoPredictor = livePredictions(path='speech_to_emotion/Emotion_Voice_Detection_Model.h5', file=audioFile)
# emoPredictor.load_model()
emoPredictor.file = audioFile
prediction = emoPredictor.makepredictions()
if verbose: print("user emotion -", prediction)
if (profile):
end = time.time()
print("(profile) compare emotion : ", end-start)
return (prediction == emotion), prediction, error | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def is_equivalence(self) -> bool:",
"def is_duplicate(self, other):\n if self.att != other.att or self.pol != other.pol:\n return False\n similarity = F.cosine_similarity(self.emb.unsqueeze(0),\n other.emb.unsqueeze(0))\n return similarity >= self.threshold",
"def __flt_eq_emo(self, other):\n if self.emote is None:\n return True\n\n return self.emote == other.emote",
"def is_het(self): \n return self.geno_hap1 != self.geno_hap2",
"def __eq__(self, other : dumbEmoji) -> bool:\n return type(other) == dumbEmoji and self.sendable == other.sendable",
"def monkey_trouble(a_smile, b_smile):\r\n return a_smile == b_smile",
"def is_same(source_molecule, target_molecule):\n return source_molecule.mol_text == target_molecule.mol_text",
"def same_player(self, other):\n return self.name == other.name \\\n and self.color == other.color",
"def monkey_trouble2(a_smile, b_smile):\n if a_smile == b_smile:\n return True\n else:\n return False",
"def IsSimilar(self,other):\n self.__do_essential_memebers_exist__()\n other.__do_essential_memebers_exist__()\n return self.element_type == other.element_type",
"def __eq__(self, other):\n if not isinstance(other, Promotion):\n return False\n\n return self.__dict__ == other.__dict__",
"def __flt_eq_eye(self, other):\n if self.eyes is None:\n return True\n\n return self.eyes == other.eyes",
"def is_trained(self) -> bool:",
"def similarity(self, e1, e2):\n\t\tpass",
"def is_hom(self) -> bool:\n if self.is_null():\n return False\n if self.allele1 == -1 or self.allele2 == -1:\n return True\n return self.allele1 == self.allele2",
"def _mp_embeds_into(mp1, mp2):\n sc_matches = []\n if mp1.monomer.name != mp2.monomer.name:\n return False\n # Check that all conditions in mp2 are met in mp1\n for site_name, site_state in mp2.site_conditions.items():\n if site_name not in mp1.site_conditions or \\\n site_state != mp1.site_conditions[site_name]:\n return False\n return True",
"def test_unique_genome(self):\n p1 = self.player()\n p2 = self.player()\n self.assertTrue(p1.genome is p2.genome)",
"def is_homo_alt(self):\n return self.geno_hap1 == 1 and self.geno_hap2 == 1",
"def same_as(self, space, in_space):\n if self.marks == space.marks and self.genus == space.genus:\n return True\n space = space.complementary_component(in_space)\n if self.marks == space.marks and self.genus == space.genus:\n return True\n return False",
"def e_paralelo(self, other):\n if (self == other) or (self.normaliza() == other.normaliza()):\n return True\n else:\n return False",
"def haveEncountered(self,mono1,mono2,eps): \n return self.distance(mono1,mono2) < eps",
"def verif_victoire(self):\n\n if self._mot_en_cours == self._mot_a_trouver :\n return True\n else :\n return False",
"def is_actor():\n return False",
"def has_interacted(self, other):\n if other in self._memory:\n if self.get_memory_of(other).has_interacted():\n return True\n else:\n return False\n else:\n return False",
"def same_chunk(self, wn1, wn2):\n if self.chunk_map[wn1] == self.chunk_map[wn2]:\n return True\n else:\n return False",
"def is_summon(self):\n return False",
"def is_hom_alt(self) -> bool:\n return self.is_hom() and (self.allele1 > 0 or self.allele2 > 0)",
"def match(self) -> bool:",
"def _one_emotion(emotions_lst, emotion):\n for cur_el in emotions_lst:\n if cur_el[0] == emotion:\n return cur_el\n return None",
"def is_indeed(self) -> bool:\n return self.mukluk > 5"
] | [
"0.66043097",
"0.6126945",
"0.5980369",
"0.5870635",
"0.5852156",
"0.58448535",
"0.5837227",
"0.5769008",
"0.5768744",
"0.57412714",
"0.5719944",
"0.5682366",
"0.5676539",
"0.56701696",
"0.56568533",
"0.56337667",
"0.5630597",
"0.556876",
"0.5558811",
"0.55464154",
"0.55197686",
"0.5512142",
"0.55025744",
"0.55011165",
"0.5490053",
"0.5487586",
"0.5471918",
"0.5454857",
"0.54484874",
"0.54461545"
] | 0.62601924 | 1 |
Perform comparison $ python compareAudio.py audioFile(.webm), netflixWatchID(str), dialogueID(number), gameID(str) | def performThreeComparisons(netflixWatchID, dialogueID, audioFile, gameID, userTranscript, emoPredictor, verbose=False, profile=False, logErrors=True):
logFile = "logFile.txt"
errorsLst = []
resultDICT = {"gameID" : gameID, "dialogueID" : dialogueID, "error" : "", "success" : True}
overallscore = 0.0
totalScores = 2
# 1. get processed data from contentDB
featureFileURL, originalEmotion, originalCaption = getProcessedFromContentDB(netflixWatchID, dialogueID, profile=profile)
resultDICT["originalEmotion"] = originalEmotion
resultDICT["originalCaption"] = originalCaption
# print(featureFileURL, emotion, originalCaption)
# 2. Validate audioFile
audioFile = validateAudioFileFormat(audioFile, profile=profile)
# 3. comparePhonetic
# featureFileURL = "132.csv"
phoneticSimilarity, error = comparePhoneticSimilarity(audioFile, featureFileURL, verbose=False, profile=profile)
if error is not "":
errorsLst.append(error) # Log error
resultDICT["phoneticScore"] = round(phoneticSimilarity, 2)
if verbose: print("Phonetic similarity:", resultDICT["phoneticScore"])
overallscore += resultDICT["phoneticScore"]
# 4. Compare Emotion
emotionSimilarity, userEmotion, error = compareEmotionSimilarity(audioFile, originalEmotion, emoPredictor, verbose=True, profile=profile)
if error is not "":
errorsLst.append(error) # Log error
resultDICT["emotionScore"] = 20.0 if emotionSimilarity else 0.0
resultDICT["userEmotion"] = userEmotion
if verbose: print("Similar emotion:", resultDICT["emotionScore"])
# 5. Compare Lyrics
userTranscript = userTranscript.lower()
lyricalSimilarity, error = compareLyricalSimilarity(userTranscript, originalCaption, verbose=False, profile=profile)
if error is not "":
errorsLst.append(error) # Log error
resultDICT["userTranscript"] = userTranscript
resultDICT["lyricalScore"] = round(lyricalSimilarity*100 , 2)
if verbose: print("Lyrical Similarity:", resultDICT["lyricalScore"])
overallscore += resultDICT["lyricalScore"]
overallscore /= totalScores
overallscore += resultDICT["emotionScore"] # add emotion bonus
# add average score
resultDICT["averageScore"] = round(overallscore, 2)
# convert to JSON
resultJSON = json.dumps(resultDICT)
resultBYTES = resultJSON.encode('utf-8')
if logErrors: _logToFile(errorsLst, resultJSON=resultJSON, logFile=logFile)
return resultBYTES, resultJSON, errorsLst | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def compare(file1, file2):\n process = subprocess.Popen([PBWT_BIN, 'compare', file1, file2],\n stdout=subprocess.PIPE)\n process_results(str(process.communicate()[0]))",
"def same_file(wavecar1, wavecar2, wavecar3):\n same = False\n if (filecmp.cmp(wavecar1, wavecar2, shallow=False)):\n print(\"Serious problem:: {} and {} are the same\".format(wavecar1, wavecar2))\n same = True\n if (filecmp.cmp(wavecar1, wavecar3, shallow=False)):\n print(\"Serious problem:: {} and {} are the same\".format(wavecar1, wavecar3))\n same = True\n if (filecmp.cmp(wavecar2, wavecar3, shallow=False)):\n print(\"Serious problem:: {} and {} are the same\".format(wavecar2, wavecar3))\n same = True\n\n if same:\n print(\"It seems that you are using same files to do finite difference, exit\")\n print(\"\\tComment the 'same_file' checker if you know what you are doing\")\n raise SystemExit",
"def comparePhoneticSimilarity(audioFile, featureFile, verbose=False, profile=False):\n if (profile): start = time.time()\n assert(\".wav\" in audioFile), \"Expected .wav as audioFile\"\n configFile = 'databuilder/configs/prosodyShs.conf'\n error = \"\"\n if not (os.path.exists(configFile) and os.path.exists(audioFile) and os.path.exists(featureFile)):\n error = \"(middle) error: one or more files don't exist (check paths). Cannot compare phonetics. exiting...\\n\"\n for ff in (configFile, audioFile, featureFile):\n if not os.path.exists(ff): error += \"not found file: \" + ff + \"\\n\"\n print(error)\n return 0, error\n status, error = extract(audioFile, \"test.csv\", configFile, verbose=verbose)\n if not status: #failed\n error = \"(middle) feature extraction error: \" + error\n print(error)\n return 0, error\n similarity = compare(\"test.csv\", featureFile, 'prosody', delimiter=';', verbose=verbose, plot=False)\n if verbose: print(\"Similarity: \", similarity)\n if (profile):\n end = time.time()\n print(\"(profile) compare phonetic similarity : \", end-start)\n return similarity, error",
"def test_gathering_audio_files(\n requests_mock: rm_Mocker,\n json_db_mock: str,\n lep_dl: LepDL,\n) -> None:\n requests_mock.get(\n conf.JSON_DB_URL,\n text=json_db_mock,\n )\n lep_dl.get_remote_episodes()\n lep_dl.files = downloader.gather_all_files(lep_dl.db_episodes)\n audio_files = lep_dl.files.filter_by_type(Audio)\n assert len(audio_files) == 18",
"def _compare_files(self, first_file, second_file):\n\n self.log.info('-' * 80)\n self.log.info('Compare files')\n\n code, out = cmd_exec(['cmp', str(first_file), str(second_file)], shell=False, log=self.log)\n if code:\n self.log.warning('md5 checksum IS NOT SAME with ffmpeg sw decode')\n self.log.warning(out)\n return False\n\n self.log.info('md5 checksum IS SAME with ffmpeg sw decode')\n return True",
"def play_audio():\n directory = os.fsencode(MINI_PATH)\n print(directory)\n adp= []\n # lst = os.listdir(directory)\n # lst.sort()\n for file in os.listdir(directory):\n filename = os.fsdecode(file)\n #print(file)\n\n if filename.endswith(\".mp3\"): \n adp.append(MINI_PATH+filename)\n #print(adp)\n adp.sort()\n print(\"ADP: \", adp)\n x = \"|\".join(adp)\n print( f'concat:{x}')\n subprocess.call(['ffmpeg', '-i', f'concat:{x}', '-acodec', 'copy', RESULT_PATH])\n \n for file in os.listdir(directory):\n filename = os.fsdecode(file)\n print(filename)\n if filename.endswith(\".mp3\"):\n os.remove(MINI_PATH+filename)",
"def test_file_count(self, audio_store_and_expected_files):\n audio_store = audio_store_and_expected_files[0]\n expected_files = audio_store_and_expected_files[1]\n\n # Check number of files.\n assert audio_store.file_count == expected_files",
"def test_match_new_aud():\n for ii in range(2):\n assert get_clip(audio['NTF'], log, ii) == get_clip(audlist, unscram_log, ii)",
"def test_bunch_of_files(self):\n bunch = [\"1.тест.mp3\", \"2.smash.mp3\", \"3.дdд.mp3\"]\n expected = [\"1.test.mp3\", \"2.smash.mp3\", \"3.ddd.mp3\"]\n for audio in bunch:\n f = open(audio, 'w+')\n f.close()\n audios = filter(lambda x: x.endswith(\".mp3\"), os.listdir())\n for audio in audios:\n rename_audio(audio)\n audios = filter(lambda x: x.endswith(\".mp3\"), os.listdir())\n for a, b in zip(audios, expected):\n print(a, b)\n for filename, expectation in zip(audios, expected):\n self.assertEqual(filename, expectation)",
"def test_conversion():\n file = 'Sherlock OST/SHERlocked.mp3'\n new_name = cr.SingleSong_conversion(file)\n assert new_name[0].split('/')[-1] in os.listdir(os.path.split(file)[0])",
"def testRoundTrip(self):\n with self.test_session():\n path = os.path.join(\n resource_loader.get_data_files_path(), 'testdata/mono_10khz.wav')\n with open(path, 'rb') as f:\n original_contents = f.read()\n\n audio_op = ffmpeg.decode_audio(\n original_contents, file_format='wav', samples_per_second=10000,\n channel_count=1)\n encode_op = ffmpeg.encode_audio(\n audio_op, file_format='wav', samples_per_second=10000)\n encoded_contents = encode_op.eval()\n self.assertEqual(original_contents, encoded_contents)",
"def compare():\n data = request.get_json()\n res_sim = audio_featurizer.compare_two_features_sets(data['features_1'], data['features_2'])\n result = dict(similarity=res_sim)\n return jsonify(result)",
"def fileCompare(a, b):\n if a[\"file_run\"] > b[\"file_run\"]:\n return 1\n elif a[\"file_run\"] == b[\"file_run\"]:\n if a[\"file_lumi\"] > b[\"file_lumi\"]:\n return 1\n elif a[\"file_lumi\"] == b[\"file_lumi\"]:\n if a[\"file_first_event\"] > b[\"file_first_event\"]:\n return 1\n if a[\"file_first_event\"] == b[\"file_first_event\"]:\n return 0\n\n return -1",
"def getAudioFileFromFilelist(audiofiltered):\n for audioFile in audiofiltered:\n audioRoot, audioExt = os.path.splitext(audioFile)\n if audioExt in ['.wav', '.aiff', '.aif']:\n return audioFile",
"def test_no_audio():\n # This file doesn't exist\n no_audio_file_struct = FileStruct(\"fixtures/chirp_noaudio.mp3\")\n no_audio_file_struct.features_file = \"features/chirp_noaudio.json\"\n feat_type = FeatureTypes.framesync\n CQT(no_audio_file_struct, feat_type, sr=22050).features\n assert (os.path.isfile(no_audio_file_struct.features_file))\n with open(no_audio_file_struct.features_file) as f:\n data = json.load(f)\n assert(CQT.get_id() in data.keys())",
"def test_accuracy():\n hits = 0\n total = 0\n # create_database()\n # gen_random_samples()\n song_to_id, id_to_song, hash_dict = load_database()\n for filename in os.listdir(\"Songs\"):\n sample_dict = hash_random_sample(filename)\n offset_dict, song_id = find_song(\n hash_dict, sample_dict, id_to_song)\n print(id_to_song[song_id])\n print(filename)\n if id_to_song[song_id] == filename:\n print(\"Success\")\n hits += 1\n else:\n print(\"Fail\")\n total += 1\n print((hits / total) * 100, \" %\")",
"def test_extracting_audio_data(\n only_audio_episodes: LepEpisodeList,\n lep_dl: LepDL,\n) -> None:\n expected_audio = Audio(\n ep_id=2009101908, # many posts in that day\n name=\"15. Extra Podcast – 12 Phrasal Verbs\",\n short_date=\"2009-10-19\",\n filename=\"[2009-10-19] # 15. Extra Podcast – 12 Phrasal Verbs\",\n primary_url=\"http://traffic.libsyn.com/teacherluke/15-extra-podcast-12-phrasal-verbs.mp3\", # noqa: E501,B950\n )\n lep_dl.files = downloader.gather_all_files(only_audio_episodes)\n audio_files = lep_dl.files.filter_by_type(Audio)\n assert audio_files[1] == expected_audio",
"def test_audio_extension(filename):\n\t\n\t# We need to make a test for extention :\n\timport os\n\textension = os.path.splitext(filename)[1]\n\text_ok=['.aif','.aifc','.aiff','.au','.cda','.m4a','.m4b','.m4p','.mid','.midi','.mka','.mkv','.mod','.mp1','.mp2','.mp3','.mpa','.nst','.odm','.ogg','.ptm','.ra','.s3m','.snd','.wav','.wma','.wow','.xm','.AIF','.AIFC','.AIFF','.AU','.CDA','.M4A','.M4B','.M4P','.MID','.MIDI','.MKA','.MKV','.MOD','.MP1','.MP2','.MP3','.MPA','.NST','.ODM','.OGG','.PTM','.RA','.S3M','.SND','.WAV','.WMA','.WOW','.XM']\n\tif extension in ext_ok:\n\t\treturn True\n\telse:\n\t\treturn False",
"def compare_files(file1, file2):\n return filecmp.cmp(file1, file2)",
"def main():\n input_video = sys.argv[1]\n input_audio = sys.argv[2]\n output_video = sys.argv[3]\n set_audio(input_video, input_audio, output_video)",
"def load_files(file1, file2):\n\n f = open(\"results/\" + file1, \"r\")\n results = json.loads(f.read())\n f.close()\n\n f = open(\"results/\" + file2, \"r\")\n previous_results = json.loads(f.read())\n f.close()\n\n compare(results, previous_results)",
"def main():\n destination = Path(argv[1])\n source_files = destination.glob(\"**/*.wma\")\n for file in source_files:\n new_name = file.name.rsplit(\".\", maxsplit=1)[0] + \".flac\"\n dest = str(file.parent / new_name)\n cmd = list(map(str, [\"avconv\", \"-i\", file, dest]))\n if platform == \"win32\":\n print(\"Running on windows... on Unix I'd run the following command:\")\n print(cmd)\n else:\n that = Popen(cmd)\n that.wait()",
"def get_audio(name, n):\n audio_path = os.path.join(args.input_folder, name, \"audio.ogg\")\n if not os.path.exists(audio_path):\n ## Some folders have multiple .ogg files, so we need to first combine them into one file. Example:\n ## |── Universe\n ## │ ├── aligned.swc\n ## │ ├── audio1.ogg\n ## │ ├── audio2.ogg\n ## │ ├── audio3.ogg\n ## │ ├── audio4.ogg\n ## │ ├── audiometa.txt\n ## │ ├── info.json\n ## │ ├── wiki.html\n ## │ ├── wiki.txt\n ## │ └── wiki.xml\n\n multiple_ogg_files = []\n for i in range(1, 5):\n path = os.path.join(args.input_folder, name, \"audio\" + str(i) + \".ogg\")\n if os.path.exists(path):\n multiple_ogg_files.append(path)\n else:\n break\n if len(multiple_ogg_files) == 0:\n return\n elif len(multiple_ogg_files) == 1:\n os.system(\"cp \\\"\" + multiple_ogg_files[0] + \"\\\" \\\"\" + audio_path + \"\\\"\")\n else:\n tmp_file_name = \"ffmeg_inputs.txt\"\n print(\"tmp_file_name=\", tmp_file_name)\n with open(tmp_file_name, \"w\", encoding=\"utf-8\") as tmp_file:\n for path in multiple_ogg_files:\n tmp_file.write(\"file '\" + path + \"'\\n\")\n cmd = \"ffmpeg -f concat -i \\\"\" + tmp_file_name + \"\\\" -c copy \\\"\" + audio_path + \"\\\"\"\n print(cmd)\n os.system(cmd)\n\n output_audio_path = args.destination_folder + \"/audio/\" + str(n) + \".ogg\"\n os.system(\"cp \\\"\" + audio_path + \"\\\" \" + output_audio_path)",
"def compareEmotionSimilarity(audioFile, emotion, emoPredictor, verbose=False, profile=False):\n error = \"\"\n if (profile): start = time.time()\n # from speech_to_emotion.emotion_classifier_nn import livePredictions\n # emoPredictor = livePredictions(path='speech_to_emotion/Emotion_Voice_Detection_Model.h5', file=audioFile)\n # emoPredictor.load_model()\n emoPredictor.file = audioFile\n prediction = emoPredictor.makepredictions()\n if verbose: print(\"user emotion -\", prediction)\n if (profile):\n end = time.time()\n print(\"(profile) compare emotion : \", end-start)\n return (prediction == emotion), prediction, error",
"def recognize_sync_audio_file(self, file, language_code = \"en-US\", is_long_recording = False):\n with io.open(file, \"rb\") as audio_file:\n content = audio_file.read()\n audio = speech.RecognitionAudio(content=content)\n\n if language_code not in self.languages:\n print('\\\"{}\\\" is not a supported language code. Make sure it\\'s supported by Google and try adding it to the languages list.\\n'.format(language_code))\n return -1\n\n config = speech.RecognitionConfig(\n encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=self.microphone_handler.RATE,\n language_code=language_code,\n )\n\n try:\n response = self.client.long_running_recognize(config=config, audio=audio, timeout=500).result() \n except:\n return -1\n\n return self._get_message_from_proto(response)['transcript']",
"def test_audio_features(self):\n\n # 1ehPJRt49h6N0LoryqKZXq, 8737: How Far I'll Go (Alessia Cara Version) by Alessia Cara\n # 2fGFaTDbE8aS4f31fM0XE4, 5037: Pop 101 (feat. Anami Vice) by Marianas Trench\n targets = {8737: {'danceability': 0.317,\n 'energy': 0.562,\n 'key': 9,\n 'loudness': -9.609,\n 'mode': 1,\n 'speechiness': 0.395,\n 'acousticness': 0.124,\n 'instrumentalness': 0.000144,\n 'liveness': 0.0667,\n 'valence': 0.127,\n 'tempo': 181.100,\n 'duration_ms': 175507,\n 'time_signature': 4,\n },\n 5037: {'danceability': 0.756,\n 'energy': 0.658,\n 'key': 11,\n 'loudness': -6.128,\n 'mode': 0,\n 'speechiness': 0.202,\n 'acousticness': 0.0581,\n 'instrumentalness': 0,\n 'liveness': 0.0674,\n 'valence': 0.640,\n 'tempo': 120.018,\n 'duration_ms': 247829,\n 'time_signature': 4,\n },\n }\n\n results = {track.i_id: track for track in self.tracks if track.i_id in targets}\n\n for target, expecteds in targets.iteritems():\n result = results[target]\n for key, expected in expecteds.iteritems():\n self.assertEqual(result.__getattr__(key), expected)",
"def load_and_process_audio(self):\n output_vector = None\n doa = None\n if self.model == \"gcc_cnn\":\n output_vector, doa = self.format_gcc_cnn()\n elif self.model == \"gcc_dsp\":\n output_vector, doa = self.format_gcc_dsp()\n elif self.model == \"raw_cnn\":\n output_vector, doa = self.format_raw_audio_cnn()\n elif self.model == \"raw_resnet\":\n output_vector, doa = self.format_raw_audio_cnn()\n else:\n print(\"Error -> No file found\")\n\n return output_vector, doa",
"def compare_spectrum(spectrum0, spectrum1):\n title0 = spectrum0.get_title() \n title1 = spectrum1.get_title() \n if(title0 < title1): \n return -1\n elif(title0 > title1): \n return 1\n else:\n return 0",
"def do_comparex(self, str_arg):\n arg = validateString(str_arg)\n file1, fileset = arg.split(' ', 1)\n if len(fileset) == 0:\n self.resultFlag = False\n raise ValueError('Bad parameter. Please check your script.')\n if not os.path.isfile(file1):\n self.resultFlag = False\n raise ValueError(file1 + ' not exist, Please check your script.')\n # f_list=[pp1 for pp1 in fileset.split(' ') if pp1!='']\n for fn in fileset.split(' '):\n # print file1, f2\n if not os.path.isfile(fn):\n self.resultFlag = False\n raise ValueError(fn + ' not exist, Please check your script.')\n if self.__compareImage(file1, fn):\n self.resultFlag = True\n print('[Found match. %s and %s are identical.]' % (file1, fn))\n return\n print('[No match found.]')\n self.resultFlag = False",
"def compareLyricalSimilarity(userTranscript, originalCaption, verbose=False, profile=False):\n error = \"\"\n if (profile): start = time.time()\n # cmp = compareToDialogue(audioFile, originalCaption, verbose=verbose)\n cmp = similar(userTranscript, originalCaption)\n if (profile):\n end = time.time()\n print(\"(profile) lyrical similarity :\", end-start)\n return cmp, error"
] | [
"0.5997795",
"0.5918491",
"0.5860667",
"0.5591653",
"0.5559069",
"0.5415558",
"0.537906",
"0.53485507",
"0.53323954",
"0.5326343",
"0.5321445",
"0.52875805",
"0.526904",
"0.5242733",
"0.5236806",
"0.52278113",
"0.5217617",
"0.5208304",
"0.51605356",
"0.5155278",
"0.51301885",
"0.5108482",
"0.5058677",
"0.50519705",
"0.504841",
"0.5035986",
"0.50294334",
"0.5002043",
"0.500012",
"0.4996029"
] | 0.6617059 | 0 |
Init constructor of HID. | def __init__(self, vendor_id: int = 0x2C97, hid_path: Optional[bytes] = None) -> None:
if hid is None:
raise ImportError("hidapi is not installed, try: "
"'pip install ledgercomm[hid]'")
self.device = hid.device()
self.path: Optional[bytes] = hid_path
self.__opened: bool = False
self.vendor_id: int = vendor_id | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def __init__(self, device_handle):\n\n self.device_handle = device_handle",
"def __init__(self):\n self._device_info = None",
"def __init__(self, Interface=\"USB\", Number=DRIVER_NUM):\n self.bib = CDLL(\"delib64\") # this will NOT fail...\n self.interface = Interface\n self.number = 0 #Number\n self.handle = 0\n self.version = 0\n\n if self.interface == \"USB\":\n self.createModule(self.RO_USB)\n elif self.interface == \"ETH\":\n self.createModule(self.RO_ETH)\n elif self.interface == \"ETH_LC\":\n self.createModule(self.RO_ETH_LC)\n else:\n print(\"Valid interfaces are USB or ETH and ETH/LC. Default ist USB.\")\n sys.exit(1)\n #self.debugModule()\n #print(\"init object! Handle is: \", self.handle)",
"def init():\n try:\n h = hid.device()\n h.open(USB_VID, USB_PID)\n h.set_nonblocking(1)\n except IOError as ex:\n print('ERROR: could not establish connection to device')\n print(ex)\n return None\n return h",
"def __init__(self, *args):\n _snap.TUIntH_swiginit(self, _snap.new_TUIntH(*args))",
"def __init__(self, hdw=['Soundcard'], devicename='dev1'):\n self.debugFlag = False\n self.task = None # NI Task\n self.required_hardware = hdw # Require specific hardware \n self.hardware = [] # list of hardware actually found on this system\n self.find_hardware(device_info={'devicename': devicename}) # population the self.hardware list",
"def __init__(self, device_id):\n info_pointer = pm.lib.Pm_GetDeviceInfo(device_id)\n if not info_pointer:\n raise IOError('PortMidi device with id={} not found'.format(\n device_id))\n info = info_pointer.contents\n \n self.device_id = device_id\n self.interface = info.interface.decode('utf-8')\n self.name = info.name.decode('utf-8')\n self.is_input = info.is_input\n self.is_output = info.is_output\n self.opened = bool(info.opened)",
"def __init__(self, uid):\n Device.__init__(self, uid)\n\n self.expected_name = 'Analog Out Bricklet'\n\n self.binding_version = [1, 0, 0]",
"def __init__(self, pid, init=None):\n self.__pid = pid\n\n cmd_handler = Cmd_Handler(lambda x: x['type'])\n cmd_handler.register_cmd('build', self.decide_build)\n cmd_handler.register_cmd('move', self.decide_move)\n self.__cmd_handler = cmd_handler\n\n self.__opponent = None\n self.look_ahead = 0\n\n self.__state = None\n\n if init:\n self.init_state(init)",
"def __init__(self, dev):\n self.dev = dev\n self.dev.cla = 0x80",
"def init(self) -> None:\n ...",
"def __init__(self):\n ChipData.ChipData.__init__(self)",
"def __init__(self):\n super().__init__()\n\n # Robot state\n self.ask_mode = False\n\n # Connect two large motors on output ports B and C\n self.sound = Sound()\n self.leds = Leds()\n self.p1 = TouchSensor(INPUT_1)\n self.p2 = TouchSensor(INPUT_2)\n self.p3 = TouchSensor(INPUT_3)\n self.p4 = TouchSensor(INPUT_4)",
"def __init__(self, port, bar, cmd_reg):\n self.port = port\n if bar:\n self.spam = getHwHandle.getBar1Handle(self.port)\n else:\n self.spam = getHwHandle.getBar0Handle(self.port)\n\n self.cmd_reg = cmd_reg",
"def __init__(self):\n # Hardware initialization\n gpio.init()\n # Logging\n self._logger = logging.getLogger(' '.join([__name__, __version__]))\n self._logger.debug(\n 'Instance of %s created: %s',\n self.__class__.__name__,\n str(self)\n )",
"def initialize(self,*args,**kwargs):\n self.__instrumentID = c_uint32(0) \n self.__numInstruments = c_uint32()\n self.__nbrOfChannels = c_uint32()\n self.__nbrADCBits = c_uint32()\n self.__temperature = c_int32()\n self.__time_us = c_double()\n\n self.loadDLLs(**kwargs) # Load the different DLLs or DLL based modules\n self.reinit() # init or reinit the board\n self.createDictAndGlobals() # create dictionaries and global variables\n self.nbrOfChannels=int(self.__nbrOfChannels.value) # duplicate self.nbrOfChannels in a Python type variable \n self.getInitialConfig()",
"def __init__(self, *args):\n _snap.TUIntHI_swiginit(self, _snap.new_TUIntHI(*args))",
"def __init__(self, pci_fid: str, **kwargs):\n super().__init__(**kwargs)\n self.fid = pci_fid",
"def __init__(self, usb_bus, usb_dev):\n self.usb_bus = usb_bus\n self.usb_dev = usb_dev\n self.usb_target = 'usb:{bus}:{dev}'.format(bus = self.usb_bus,\n dev = self.usb_dev)\n self.hw_connected = False\n\n self.rdwr_options = {\n 'targets': ['106A'], # type2tag, nfcA\n 'on-startup': on_startup,\n 'on-connect': on_connect,\n }\n\n self.last_nfcid = \"\";",
"def __init__(self):\n _hypre.HypreILU_swiginit(self, _hypre.new_HypreILU())",
"def __init__(self):\n self.data0 = [] # This will hold data from ADC0\n self.data1 = [] # This will hold data from ADC1\n self.dev = _configure_device()",
"def __init__(self) -> None:\n self.sensor = serial.Serial(config.DEVICE)\n super().__init__()",
"def __init__(self):\n\n # For now, we'll connect to the target via the Apollo debug controller.\n # This should be replaced by a high-speed USB link soon; but for now\n # we'll use the slow debug connection.\n self._debugger = ApolloDebugger()\n self._serial = self._find_serial_connection()",
"def __init__(self, *args):\n _snap.TUIntKd_swiginit(self, _snap.new_TUIntKd(*args))",
"def __init__(self, *args, **kwargs):\n SpecMessage.__init__(self, '<IiiiIIiiIII80s')\n\n if len(args) > 0:\n self.init(*args, **kwargs)",
"def __init__(self, device):\n self._unique_id = device\n self._device = AehW4a1(device)\n self._fan_modes = FAN_MODES\n self._swing_modes = SWING_MODES\n self._preset_modes = PRESET_MODES\n self._attr_available = False\n self._on = None\n self._current_temperature = None\n self._target_temperature = None\n self._attr_hvac_mode = None\n self._fan_mode = None\n self._swing_mode = None\n self._preset_mode = None\n self._previous_state = None",
"def __init__(self, dev_id, devname):\n enocean.EnOceanDevice.__init__(self)\n self.stype = \"listener\"\n self.dev_id = dev_id\n self.which = -1\n self.onoff = -1\n self.devname = devname",
"def __init__(self):\n i2c.Pn532_i2c.__init__(self)\n self._uid = False",
"def __init__(self):\n self.hw = dev_hwinfo.device()\n self.ethKey=\"Ethernet\"\n self.ethAllInterfaceName=[]\n dir_path = os.path.dirname(os.path.realpath(__file__))\n self.myDefine = init_define.main()\n self.mPlatform=self.hw.getPlatform()",
"def init(self):\n pass"
] | [
"0.6862138",
"0.6743291",
"0.67000437",
"0.66972363",
"0.6555643",
"0.6550871",
"0.65466005",
"0.65423924",
"0.6522224",
"0.6498889",
"0.64774984",
"0.64688903",
"0.64580566",
"0.6452935",
"0.6445795",
"0.6438601",
"0.6433724",
"0.64092666",
"0.6399368",
"0.63911164",
"0.63842994",
"0.63745123",
"0.6360917",
"0.63506454",
"0.633763",
"0.63333577",
"0.6332777",
"0.63322806",
"0.632131",
"0.63211876"
] | 0.7098126 | 0 |
Open connection to the HID device. Returns None | def open(self) -> None:
if not self.__opened:
if self.path is None:
self.path = HID.enumerate_devices(self.vendor_id)[0]
self.device.open_path(self.path)
self.device.set_nonblocking(True)
self.__opened = True | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def init():\n try:\n h = hid.device()\n h.open(USB_VID, USB_PID)\n h.set_nonblocking(1)\n except IOError as ex:\n print('ERROR: could not establish connection to device')\n print(ex)\n return None\n return h",
"def performOpen(self, options={}):\n self._lib = CDLL('sc5520a_uhfs.dll')\n self._set_signatures()\n # The expected format for the serial number is: 10001A4C\n addr = self.getAddress()\n # handle = self._lib.sc5520a_uhfsOpenDevice(1, addr.encode('utf-8'),0)\n handle = c_void_p()\n status = self._lib.sc5520a_uhfsOpenDevice(1, addr.encode('utf-8'),0, byref(handle)) \n # raise TypeError(handle)\n # assert status == SCI_SUCCESS (SCI_SUCCESS = 0)\n\n # raise TypeError(handle)\n if not handle:\n msg = 'Failed to connect to the instrument with serial number: %s'\n raise RuntimeError(msg % addr)\n self._handle = handle\n self._addr = addr",
"def open(self):\n self.device = ConnectHandler(\n device_type='vyos',\n host=self.hostname,\n username=self.username,\n password=self.password,\n timeout=self.timeout,\n port=self.port\n )",
"def open(self):\n # Move all of the connection arguments into connect_args\n connect_args = {}\n\n # check for mode\n if self.get_option('port') is None:\n if self.get_option('mode') == 'telnet':\n connect_args['port'] = 23\n elif self.get_option('mode') == 'serial':\n connect_args['port'] = '/dev/ttyUSB0'\n else:\n connect_args['port'] = 830\n else:\n connect_args['port'] = self.get_option('port')\n\n if (self.get_option('mode') == 'telnet' or\n self.get_option('mode') == 'serial'):\n if self.get_option('baud') is None:\n # Default baud if serial or telnet mode\n connect_args['baud'] = 9600\n if self.get_option('attempts') is None:\n # Default attempts if serial or telnet mode\n connect_args['attempts'] = 10\n\n connect_args['host'] = self.get_option('host')\n # connect_args['port'] = self.get_option('port')\n connect_args['user'] = self.get_option('remote_user')\n connect_args['passwd'] = self.get_option('password')\n connect_args['ssh_private_key_file'] = self.get_option('private_key_file')\n connect_args['ssh_config'] = self.get_option('pyez_ssh_config')\n connect_args['timeout'] = self.get_option('persistent_connect_timeout')\n try:\n log_connect_args = dict(connect_args)\n log_connect_args[\"passwd\"] = \"NOT_LOGGING_PARAMETER\"\n\n self.queue_message(\"vvvv\", \"Creating device parameters: %s\" % log_connect_args)\n timeout = connect_args.pop(\"timeout\")\n self.dev = jnpr.junos.device.Device(**connect_args)\n self.queue_message(\"vvvv\", \"Opening device.\")\n self.dev.open()\n self.queue_message(\"vvvv\", \"Device opened.\")\n\n self.dev.timeout = self.get_option('persistent_command_timeout')\n self.queue_message(\"vvvv\", \"Setting default device timeout to %d.\" % timeout)\n # Exceptions raised by close() or open() are all sub-classes of\n # ConnectError, so this should catch all connection-related exceptions\n # raised from PyEZ.\n except pyez_exception.ConnectError as ex:\n raise AnsibleError(\"Unable to make a PyEZ connection: %s\" % (str(ex)))",
"def open_device_dialog(self):\n res, device = DeviceDialog.get_device(self.indexer)\n if res and device:\n self.serial = device.serial\n if self.serial:\n caps_str = None\n self.open_device(self.serial, caps_str)",
"def open(self):\n if self._connected:\n try:\n self.native.find_prompt()\n except: # noqa E722 pylint: disable=bare-except\n self._connected = False\n\n if not self._connected:\n self.native = ConnectHandler(\n device_type=\"cisco_asa\",\n ip=self.host,\n username=self.username,\n password=self.password,\n port=self.port,\n global_delay_factor=self.global_delay_factor,\n secret=self.secret,\n verbose=False,\n )\n self._connected = True\n\n log.debug(\"Host %s: Connection to controller was opened successfully.\", self.host)",
"def open_device(self):\n\t\t# open device\n\t\t# declare ctype variables\n\t\thdwf = c_int()\n\n\t\tprint \"\\nOpening device\"\n\t\tdwf.FDwfDeviceOpen(c_int(-1), byref(hdwf))\n\n\t\tif hdwf.value == 0:\n\t\t\tprint \"failed to open device\"\n\t\t\tquit()\n\n\t\tself.interface_handler = hdwf\n\n\t\thzSysIn = c_double()\n\t\t#max_buffer_size_in = c_int()\n\n\t\tdwf.FDwfDigitalInInternalClockInfo(self.interface_handler, byref(hzSysIn))\n\t\t#dwf.FDwfDigitalInBufferSizeInfo(self.interface_handler, byref(max_buffer_size_in))\n\n\t\tself.internal_clock_freq = hzSysIn.value\n\n\t\t#print \"internal digital in frequency is \" + str(hzSysIn.value)\n\t\t#print \"digital in max buffer size: \" + str(max_buffer_size_in.value)",
"def device_connect(self):\n pass",
"def open(self, deviceID):\r\n \r\n return self._performAction(deviceID, _API_DEVICE_ACTION_OPEN)",
"def connect_dmm2110():\n address = 'USB0::0x05E6::0x2110::8010814::INSTR'\n rm = visa.ResourceManager()\n return rm.open_resource(address)",
"def connect_dmm2100():\n address = 'USB0::0x05E6::0x2100::1416380::INSTR'\n rm = visa.ResourceManager()\n return rm.open_resource(address)",
"def connect(self):\n\n log.info('Connecting to device \"{0}\" using {1} at \"{2}\".'.format(\n self.name, self.driver, self.connection_resource))\n\n if self.driver == drivers.pyvisa:\n try:\n if not (legacyVisa):\n rm = pyvisa.ResourceManager()\n self.device = rm.open_resource(**self.connection_resource)\n else:\n self.device = pyvisa.Instrument(**self.connection_resource)\n except pyvisa.VisaIOError as e:\n raise DeviceNotFoundError(\n 'Could not open device at \"{0}\".'.format(self.connection_resource), e)\n\n elif self.driver == drivers.telnet:\n self.device = telnetlib.Telnet(\n timeout=2, **self.connection_resource)\n elif self.driver == drivers.requests:\n r = requests.get(self.request_address)\n if r.status_code != 200:\n raise DeviceNotFoundError(\n 'Could not connect to device at \"{0}\".'.format(self.connection_resource), e)\n\n elif self.driver == drivers.lgpib:\n try:\n self.device = Gpib.Gpib(**self.connection_resource)\n except gpib.GpibError as e:\n raise DeviceNotFoundError(\n 'Could not open device at \"{0}\".'.format(self.connection_resource), e)\n elif self.driver == drivers.pyvisa_usb:\n try:\n if not (legacyVisa):\n rm = pyvisa.ResourceManager()\n self.device = rm.open_resource(**self.connection_resource)\n else:\n class USBDevice(pyvisa.Instrument):\n \"\"\"\n Using USB devices with PyVISA requires a small hack: the object must be an Instrument, but we can't call Instrument.__init__.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Bypass the initialization in visa.Instrument, due to \"send_end\" not being valid for USB.\n pyvisa.ResourceTemplate.__init__(\n self, *args, **kwargs)\n\n self.device = USBDevice(**self.connection_resource)\n\n except pyvisa.VisaIOError as e:\n raise DeviceNotFoundError(\n 'Could not open device at \"{0}\".'.format(self.connection_resource), e)\n\n try:\n self._connected()\n except Exception as e:\n raise DeviceNotFoundError('Could not finish connection to device at \"{0}\".'.format(\n self.connection_resource), e)",
"def __init__(self, vendor_id: int = 0x2C97, hid_path: Optional[bytes] = None) -> None:\n if hid is None:\n raise ImportError(\"hidapi is not installed, try: \"\n \"'pip install ledgercomm[hid]'\")\n\n self.device = hid.device()\n self.path: Optional[bytes] = hid_path\n self.__opened: bool = False\n self.vendor_id: int = vendor_id",
"def _open(self):\n \n # Open Device\n try:\n logger.debug(\"%s: UDP port opening started...\" % \\\n self.__class__.__name__)\n self._udp_socket.bind(tuple(['',self._port]))\n logger.debug(\"%s: ...UDP port opening complete.\" % \\\n self.__class__.__name__)\n \n # Instantiate router\n self._platform = router.HorizonRouteable()\n self._platform._version = self._version\n self._platform.message_routed = self.message_received\n def tmp():\n return self.__str__()\n self._platform.__str__ = tmp\n self._router = router.HorizonRouter(platform = self._platform, \n clients = [], \n send_all = self._send_all)\n \n # Open failed\n except Exception as ex:\n logger.error(\"%s: ...UDP port opening failed:\\n%s\" % \\\n (self.__class__.__name__, str(ex)))\n raise utils.TransportError \\\n (\"UDP Port open failed!\\n\" + str(ex))",
"def openSensel():\n handle = None\n (error, device_list) = sensel.getDeviceList()\n if device_list.num_devices != 0:\n (error, handle) = sensel.openDeviceByID(device_list.devices[0].idx)\n return handle",
"def open(device, **kwargs):\n if len(device.split(':')) == 6:\n from .bluepy import BluepyConnection\n return BluepyConnection(device, **kwargs)\n else:\n from .serial import SerialConnection\n return SerialConnection(device, **kwargs)",
"def open(self):\n self.__port.open()",
"def _open(self):\n \n # Open Device\n try:\n logger.debug(\"%s: UDP port opening started...\" % \\\n self.__class__.__name__)\n self._udp_socket.bind(('',self._port))\n self._socket = HorizonTransport_Socket(sock = self._udp_socket,\n host = self._addr[0],\n port = self._addr[1],\n name = \"%s:%d\" % self._addr,\n store_timeout = self.store_timeout,\n version = self.version)\n self._socket.opened = True\n logger.debug(\"%s: ...UDP port opening complete.\" % \\\n self.__class__.__name__)\n \n # Open failed\n except Exception as ex:\n logger.error(\"%s: ...UDP port opening failed:\\n%s\" % \\\n (self.__class__.__name__, str(ex)))\n raise utils.TransportError \\\n (\"UDP Port open failed!\\n\" + str(ex))",
"def open_device(self, device):\n raise NotImplementedError(\"implement in derived transport class\")",
"def acquire(self):\n clf = nfc.ContactlessFrontend()\n\n if clf.open('usb:{bus}:{dev}'.format(bus = self.usb_bus,\n dev = self.usb_dev)):\n print(\"dev {0} acquired successfully\".format(self.usb_target))\n self.hw_connected = True\n return True\n\n print(\"dev {0} not found\".format(self.usb_target))\n return False",
"def __connect(self):\n try:\n self._device = usb.core.find(idVendor=self.usb_vendor_id, idProduct=self.usb_product_id)\n self._configuration = self._device.get_active_configuration()\n except Exception as e:\n return False\n self.reset()\n return True",
"def open(self):\n logging.debug('Connecting to device %s' % self.paramiko_cfg.get('hostname'))\n self.ssh = paramiko.SSHClient()\n self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n self.ssh.connect(**self.paramiko_cfg)",
"def Demo():\n args = _Parse()\n device = args.device.lower()\n if device == 'keyboard':\n DemoBluetoothHIDKeyboard(args.remote_host_address, args.chars_to_send)\n elif device == 'mouse':\n DemoBluetoothHIDMouse(args.remote_host_address)\n else:\n args.print_help()",
"def opened(self):\n self.send({\n \"msg\": \"connect\",\n \"version\": DDP_VERSIONS[0],\n \"support\": DDP_VERSIONS\n })",
"def open_connection(self):\r\n # Open ModBus connection\r\n try:\r\n self.c = ModbusClient(host=self.host, port=self.port,\r\n unit_id=self.unit_id, auto_open=True, auto_close=True)\r\n except ValueError:\r\n print(\"Error with host: {}, port: {} or unit-ID: {} params\".format(\r\n self.host, self.port, self.unit_id))",
"def connect_to_device(self):\n result = self._lib.NRFJPROG_connect_to_device()\n if result != NrfjprogdllErr.SUCCESS:\n raise APIError(result)",
"def connect(self, vid=0x04D8, pid=0x00DD, devnum=0):\n self.device = hid.enumerate(vid, pid)\n if self.device:\n self.mcp2221a.open_path(self.device[devnum][\"path\"])\n else:\n raise NoDeviceError(\"No MCP2221A devices found\")",
"def open(self, device_id):\n self._js[device_id].open()",
"def _open_device(self):\r\n self._lib = windll.LoadLibrary(\"lib\\\\ps2000a.dll\")\r\n c_handle = c_int16()\r\n with self._driver_lock:\r\n m = self._lib.ps2000aOpenUnit(byref(c_handle),None)\r\n if m == 286:\r\n m = self._lib.ps2000aChangePowerSource(c_handle,\r\n c_int32(m))\r\n check_result(m)\r\n self._handle = c_handle\r\n\r\n return True",
"def __connect(self):\n if DEBUG:\n printLog(self.threadName + '[iDevice] Connecting to device %s...' % self.deviceId, logging.INFO)\n try:\n self.adbc, serialno = ViewClient.connectToDeviceOrExit(verbose=DEBUG, serialno=self.deviceId)\n # print 'Connected.'\n if self.adbc is None:\n printLog(self.threadName + '[iDevice] Failed to connect to Device %s...' % self.deviceId, logging.ERROR)\n return\n # get phone's screen resolution, once connected, it is fixed\n self.scn_width = int(self.adbc.display['width'])\n self.scn_height = int(self.adbc.display['height'])\n # printLog(self.threadName + \"[iDevice] Device %s's screen resolution is: %d * %d\" % (\n # self.deviceId, self.scn_width, self.scn_height), logging.DEBUG)\n self.adbc.wake()\n # printLog(self.threadName + '[iDevice] Creating View Client... ', logging.DEBUG)\n self.vc = ViewClient(self.adbc, serialno, autodump=False, forceviewserveruse=True)\n if DEBUG:\n printLog(self.threadName + '[iDevice] Device %s connected.' % self.deviceId, logging.INFO)\n # self.resultFlag = True\n except Exception, e:\n printLog(self.threadName + \"[iDevice] CANNOT connect to device %s. Please check the USB cable and \"\n \"reconnect the device.\" % self.deviceId, logging.ERROR)\n # if DEBUG:\n # traceback.print_exc()\n raise EnvironmentError(e.message)"
] | [
"0.76332617",
"0.6955843",
"0.69416445",
"0.68056446",
"0.6553122",
"0.65466124",
"0.6523534",
"0.6514852",
"0.6506754",
"0.64412344",
"0.6438013",
"0.6406292",
"0.6384707",
"0.63268006",
"0.62957555",
"0.6287522",
"0.6280608",
"0.6214638",
"0.62089825",
"0.6192919",
"0.6183042",
"0.6178109",
"0.616639",
"0.61275566",
"0.61120415",
"0.6110462",
"0.6109749",
"0.6062564",
"0.604365",
"0.60188067"
] | 0.75960964 | 1 |
Receive data through HID device `self.device`. Blocking IO. Returns Tuple[int, bytes] A pair (sw, rdata) containing the status word and response data. | def recv(self) -> Tuple[int, bytes]:
seq_idx: int = 0
self.device.set_nonblocking(False)
data_chunk: bytes = bytes(self.device.read(64 + 1))
self.device.set_nonblocking(True)
assert data_chunk[:2] == b"\x01\x01"
assert data_chunk[2] == 5
assert data_chunk[3:5] == seq_idx.to_bytes(2, byteorder="big")
data_len: int = int.from_bytes(data_chunk[5:7], byteorder="big")
data: bytes = data_chunk[7:]
while len(data) < data_len:
read_bytes = bytes(self.device.read(64 + 1, timeout_ms=1000))
data += read_bytes[5:]
sw: int = int.from_bytes(data[data_len - 2:data_len], byteorder="big")
rdata: bytes = data[:data_len - 2]
LOG.debug("<= %s %s", rdata.hex(), hex(sw)[2:])
return sw, rdata | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def receive_data(self):\n chunks = []\n bytes_recd = 0\n while bytes_recd < 8:\n #I'm reading my data in byte chunks\n try:\n chunk = self.sockfd.recv(min(8 - bytes_recd, 4))\n chunks.append(chunk)\n bytes_recd = bytes_recd + len(chunk)\n except:\n print(f'{self.ip} socket failed')\n break\n # if chunk == '':\n # raise RuntimeError(\"Socket connection broken\")\n\n stat_tuple = struct.unpack('L', chunks[0])\n data_tuple = struct.unpack('L', chunks[1])\n stat = stat_tuple[0]\n data = data_tuple[0]\n return stat, chunks[1]",
"def _receive(self, length):\n \n return self.device.read(length)",
"def __recv__(self):\n data = self.port.read(size=1)\n v = int.from_bytes(data, byteorder=\"little\")\n if(self.verbose):\n pc.color_stdout(\"RED\")\n print(\"<< %s\\t - %s\\t - %d\"% (hex(v),bin(v),v))\n pc.color_stdout(\"RESET\")\n return data",
"def doRead(self):\n return fdesc.readFromFD(self.fileno(), self.protocol.dataReceived)",
"def recv(self):\r\n try:\r\n self.lock.acquire()\r\n length, = struct.unpack(self.HEADER_FORMAT, self.stream.read(self.HEADER_SIZE))\r\n return self.stream.read(length)\r\n finally:\r\n self.lock.release()",
"def recvData(self):\n prec_state = self.status\n self.status = Modem.Status.BUSY2RECV\n data = self.conn.recvData()\n self.status = prec_state\n self.checkConnection(data)\n return data",
"def recv(self):\r\n opcode, data = self.recv_data()\r\n return data",
"def recibir(self):\r\n lenbuf = self.__recvall(4)\r\n longitud, = struct.unpack('!I', lenbuf)\r\n return self.__recvall(longitud)",
"def receive(self):\n raw_msglen = self.recvall(4)\n if not raw_msglen:\n return None\n msglen = stc.unpack('>I', raw_msglen)[0]\n # Read the message data\n return self.recvall(msglen)",
"def receive(self):\n data = self.socket.recv(4096)\n return data",
"def __response(self, cmd_val=None):\n # Receive the response while listening serial input\n bytes_received = bytearray(1)\n while True:\n one_byte = self.device.read(1)\n '''If no bytes are read the sensor might be in sleep mode.\n It makes no sense to raise an exception here. The raise condition\n should be checked in a context outside of this function.'''\n if len(one_byte) > 0:\n bytes_received[0] = ord(one_byte)\n # if this is true, serial data is coming in\n if bytes_received[0] == self.__SerialStart:\n single_byte = self.device.read(1)\n if ((cmd_val is not None and cmd_val != command[\"Request\"]) and ord(single_byte) == self.__ResponseByte) or ((cmd_val is None or cmd_val is command[\"Request\"]) and ord(single_byte) == self.__ReceiveByte):\n bytes_received.append(ord(single_byte))\n break\n else:\n if self.__duty_cycle == 0:\n self.logger.error(\"{}: a sensor response has not arrived within timeout limit. If the sensor is in sleeping mode wake it up first! Returning an empty byte array as response!\".format(self.sensor_name))\n else:\n self.logger.info(\"{}: no response. Expected while in duty cycle.\".format(self.sensor_name))\n return bytearray()\n\n response_bytes = struct.unpack('BBBBBBBB', self.device.read(8))\n bytes_received.extend(response_bytes)\n\n if cmd_val is not None and cmd_val != command[\"Request\"]:\n\n if bytes_received[1] is not self.__ResponseByte:\n raise IOError(\"{}: no ResponseByte found in the response.\".format(self.sensor_name))\n\n if bytes_received[2] != cmd_val:\n raise IOError(\"{}: third byte of serial data \\\"{}\\\" received is not the expected response to the previous command: \\\"{}\\\"\".format(self.sensor_name, bytes_received[2], cmd_val.name))\n\n if cmd_val is None or cmd_val == command[\"Request\"]:\n if bytes_received[1] is not self.__ReceiveByte:\n raise IOError(\"{}: received byte not found in the response.\".format(self.sensor_name))\n\n # Evaluate checksum\n if self.__checksum_make(bytes_received[0:-2]) != bytes_received[-2]:\n raise IOError(\"{}: checksum of received data is invalid.\".format(self.sensor_name))\n\n # Set device_id if device id is not initialized or proof it, if it's not None\n if self.__device_id is None:\n self.__device_id = bytes_received[-4:-2]\n elif self.__device_id is not None and not self.__device_id.__eq__(bytes_received[-4:-2]):\n raise ValueError(\"{}: data received ({}) does not belong to this device with id {}.\".format(self.sensor_name, bytes_received, self.__device_id))\n\n self.logger.info(\"{}: the response was successful with message {}.\".format(self.sensor_name, \"\".join(\"%02x:\" % b for b in bytes_received)))\n return bytes_received",
"def receive_response(self):\n return self.socket.receive()",
"def recv(self, length = 0):\n return self.received.get()",
"def read_response(self):\n counter = 0\n rx_pkt_done = 0\n while not rx_pkt_done:\n uart_status, tx_buff_full, tx_buff_empty, rx_buff_full, rx_buff_empty, rx_pkt_done = self.x10g_rdma.read_uart_status()\n counter += 1\n if counter == 15001:\n print(\"\\n\\t read_response() timed out waiting for uart!\\n\")\n break\n response = self.x10g_rdma.uart_rx(0x0)\n # print(\"R: {}. {}\".format(response, counter))\n # print(\"... receiving: {} ({})\".format(' '.join(\"0x{0:02X}\".format(x) for x in response), counter))\n return response\n # return self.x10g_rdma.uart_rx(0x0)",
"def receive_data():\n\n # Receive the first message (the header),\n # which indicates the incoming data length\n data_length = int(pickle.loads(conn.recv(HEADER_SIZE)))\n \n if data_length:\n # Receive the data itself\n data = pickle.loads(conn.recv(data_length))\n\n return data",
"def receive(self):\n\n return self.sock.recv(1024)",
"def get_data(self):\n\n data = self.socket.recv(BUFFER_SIZE)\n\n if not data:\n return None\n\n if len(data) == BUFFER_SIZE:\n while True:\n try:\n data += self.socket.recv(BUFFER_SIZE)\n except:\n break\n \n return data",
"def _recv(self):\n return self._channel.recv(_MAX_READ_AMOUNT)",
"async def recv(self):\n return await self.receptor.response_queue.get()",
"def requestDataFromServer(self):\r\n self.tempVar = None\r\n dataAvailable = threading.Event()\r\n\r\n self.sendMessage(\"requestData\", \"\")\r\n\r\n @self.ursinaClient.event\r\n def receiveData(Content):\r\n self.ursinaClient.lock.acquire()\r\n\r\n self.tempVar = Content\r\n dataAvailable.set()\r\n\r\n self.ursinaClient.lock.release()\r\n\r\n # print(\"Len Data Recvd: \", len(Content))\r\n\r\n dataAvailable.wait()\r\n\r\n tempVar = self.tempVar\r\n\r\n del self.tempVar\r\n return tempVar",
"def receive_device(self):\n try:\n device_p = self._libudev.udev_monitor_receive_device(self)\n except EnvironmentError:\n self._reraise_with_socket_path()\n if not device_p:\n raise EnvironmentError('Could not receive device')\n action = ensure_unicode_string(\n self._libudev.udev_device_get_action(device_p))\n return action, Device(self.context, device_p)",
"def receive(self, data, length, packet_info):\n return",
"async def read(self) -> Union[dictwrapper, str]:\n while True:\n await self.connect()\n try:\n rx_timeout = self.alive_opts.get('rx_timeout', None)\n reader = self.reader.readuntil(separator=b'\\n')\n self.bresponse = await asyncio.wait_for(reader,\n rx_timeout)\n self.response = polystr(self.bresponse)\n if self.response.startswith(\n \"{\") and self.response.endswith(\"}\\r\\n\"):\n self.unpack(self.response)\n self._oldstyle_shim()\n self.valid |= PACKET_SET\n return self.data\n return self.response\n except asyncio.CancelledError:\n self.close()\n raise\n except Exception as exc: # pylint: disable=W0703\n error = 'timeout' if isinstance(\n exc, asyncio.TimeoutError) else exc\n self.logger.warning(\n f'Failed to get message from GPSD: {error}')\n self.close()\n if self.reconnect:\n # Try again later\n await asyncio.sleep(self.reconnect)\n else:\n raise",
"def _GetResponseFrame(self):\n self.write([self.SERIAL_IO])\n time.sleep(.1)\n resp = self.read(3)\n [ack, txcount, rxcount] = self.decode(resp)\n if ack != 0xFF:\n raise ValueError('Serial - GetResponseFrame - NACK received - Transmissionerror')\n if rxcount > 0:\n time.sleep(.01)\n com = self._serial_read(rxcount)\n #Add to buffer\n self.buffer += com\n return [ack, txcount, len(self.buffer)]",
"async def _monitor_recv(self):\n\n while True:\n await RisingEdge(self.clock)\n await ReadOnly()\n if self.bus.valid.value:\n self._recv(int(self.bus.data.value))",
"def recv(self) -> tuple:\n (data, c) = self.socket.recvfrom(Rudp.Packet.buffer())\n # print(data)\n (packet, validity) = Rudp.Packet.unpack(data)\n if(validity):\n print(\"Valid Packet Received From: \", c)\n else:\n raise Rudp.InvalidPacket(\"Invalid Packet Received\")\n\n return (packet, validity, c)",
"def _receive_packet(self):\n report = self._serial_read(1)\n if len(report) != 1:\n self.log(\"ERROR: Didn't read back a report!\")\n report = -1\n else:\n report = report[0]\n retval = self._serial_read(1)\n if len(retval) != 1:\n self.log(\"ERROR: Didn't read back a return value!\")\n retval = -1\n else:\n retval = retval[0]\n\n return_payload_len = self._serial_read(1)\n if len(return_payload_len) != 1:\n self.log(\"ERROR: Didn't read back a return payload length!\")\n return_payload_len = 0\n else:\n return_payload_len = return_payload_len[0]\n\n if return_payload_len != 0:\n return_payload = self._serial_read(return_payload_len)\n else:\n return_payload = []\n checksum = self._serial_read(1)\n if len(checksum) != 1:\n self.log(\"ERROR: Didn't read back a checksum!\")\n checksum = -1\n else:\n checksum = checksum[0]\n\n data = self.MAGIC_HEADER + [report, retval, return_payload_len] + return_payload\n data.append(checksum)\n\n our_checksum = self.generate_checksum(data[:-1])\n if our_checksum != checksum:\n self.log(\"ERROR: Our checksum didn't calculate properly! \"\n \"(Calculated {}, expected {})\".format(our_checksum, checksum))\n return -1, checksum, []\n else:\n if self.verbose:\n self.log(\"Checksum match! ({} == {})\".format(our_checksum, checksum))\n\n return report, retval, return_payload",
"def _read(self):\n \n try:\n d = self._get_byte()\n ts = time.time()\n while d != self.HDLC_FLAG_BYTE:\n d = self._get_byte()\n ts = time.time()\n packet = [d]\n d = self._get_byte()\n if d == self.HDLC_FLAG_BYTE:\n d = self._get_byte()\n ts = time.time()\n else:\n packet.append(d)\n while d != self.HDLC_FLAG_BYTE:\n d = self._get_byte()\n packet.append(d)\n if self._debug == True:\n print \"Serial:_read: unescaped\", packet\n packet = self._unescape(packet)\n \n crc = self._crc16(0, packet[1:-3])\n packet_crc = self._decode(packet[-3:-1])\n \n if crc != packet_crc:\n print \"Warning: wrong CRC! %x != %x %s\" % (crc, packet_crc, [\"%2x\" % i for i in packet])\n if self._debug:\n if self._ts == None:\n self._ts = ts\n else:\n print \"Serial:_read: %.4f (%.4f) Recv:\" % (ts, ts - self._ts), self._format_packet(packet[1:-3])\n self._ts = ts\n return RawPacket(ts, packet[1:-3], crc == packet_crc)\n except socket.timeout:\n return None",
"def _read_v2(self):\n return self.usb_dev.read(self.ep_in, self.rdbuf_chunksize, self.usb_rd_timeout)",
"def get_data(self, poll_req):\n try:\n self.write(poll_req)\n reply = self.read_line()\n return reply\n except Exception:\n raise"
] | [
"0.65270954",
"0.6320771",
"0.62461853",
"0.6179725",
"0.616269",
"0.60660446",
"0.6049839",
"0.59986186",
"0.59340626",
"0.59284836",
"0.59060866",
"0.5892542",
"0.5891193",
"0.5879894",
"0.5854489",
"0.58111537",
"0.5801802",
"0.579307",
"0.57675236",
"0.5746004",
"0.57268906",
"0.5715979",
"0.5712136",
"0.5702087",
"0.5679062",
"0.56741077",
"0.56682783",
"0.5647613",
"0.5635658",
"0.5631454"
] | 0.67547876 | 0 |
Search through the provided list of devices to find the one with the matching usage_page and usage. | def find_device(devices, *, usage_page, usage):
if hasattr(devices, "send_report"):
devices = [devices]
for device in devices:
if (
device.usage_page == usage_page
and device.usage == usage
and hasattr(device, "send_report")
):
return device
raise ValueError("Could not find matching HID device.") | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def find_devices (devicelist):\n vprint(\"\\nFind known devices:\")\n for device in devicelist:\n if find_device(device) is not None :\n vprint(\"\\tFound :\", device)\n else:\n vprint(\"\\tNOT found:\", device )\n vprint(\"..........\") \n return",
"def find(ctx, name):\n conf = settings.devices.get(name, dict())\n if conf.get('type') == 'command':\n return conf, name, name\n\n uuids = ctx.obj['uuids']\n context = Context()\n for dev in iter(context.list_devices()):\n if 'ID_FS_TYPE' in dev:\n if name == uuids.get(dev.get('ID_FS_UUID')):\n return (settings.devices[name], dev['DEVNAME'],\n settings.devices[name].get('label',\n dev.get('ID_FS_LABEL')))\n\n print('Device \"%s\" not found.' % name)\n sys.exit(1)",
"def find_device_of_type(device: UpnpDevice, device_types: List[str]) -> UpnpDevice:\n for device_ in device.all_devices:\n if device_.device_type in device_types:\n return device_\n\n raise UpnpError(f\"Could not find device of type: {device_types}\")",
"def get_devices(token, params, sensitive_data=False):\n tenant = init_tenant_context(token, db)\n\n pagination = {'page': params.get('page_number'), 'per_page': params.get('per_page'), 'error_out': False}\n\n SORT_CRITERION = {\n 'label': Device.label,\n None: Device.id\n }\n sortBy = SORT_CRITERION.get(params.get('sortBy'))\n\n attr_filter = []\n query = params.get('attr')\n\n for attr_label_item in query:\n parsed = re.search('^(.+){1}=(.+){1}$', attr_label_item)\n attr_label = []\n attr_label.append(DeviceAttr.label == parsed.group(1))\n # static value must be the override, if any\n attr_label.append(text(\"coalesce(overrides.static_value, attrs.static_value)=:static_value \").bindparams(static_value=parsed.group(2)))\n attr_filter.append(and_(*attr_label))\n\n query = params.get('attr_type')\n for attr_type_item in query:\n attr_filter.append(DeviceAttr.value_type == attr_type_item)\n\n label_filter = []\n target_label = params.get('label')\n if target_label:\n label_filter.append(Device.label.like(\"%{}%\".format(target_label)))\n\n template_filter = []\n target_template = params.get('template')\n if target_template:\n template_filter.append(DeviceTemplateMap.template_id == target_template)\n\n if (attr_filter): #filter by attr\n LOGGER.debug(f\" Filtering devices by {attr_filter}\")\n\n page = db.session.query(Device) \\\n .join(DeviceTemplateMap, isouter=True)\n\n page = page.join(DeviceTemplate) \\\n .join(DeviceAttr, isouter=True) \\\n .join(DeviceOverride, (Device.id == DeviceOverride.did) & (DeviceAttr.id == DeviceOverride.aid), isouter=True)\n\n page = page.filter(*label_filter) \\\n .filter(*template_filter) \\\n .filter(*attr_filter) \\\n .order_by(sortBy) \\\n .paginate(**pagination)\n\n\n elif label_filter or template_filter: # only filter by label or/and template\n if label_filter:\n LOGGER.debug(f\"Filtering devices by label: {target_label}\")\n\n if template_filter:\n LOGGER.debug(f\"Filtering devices with template: {target_template}\") \n \n page = db.session.query(Device) \\\n .join(DeviceTemplateMap, isouter=True)\n\n if sensitive_data: #aditional joins for sensitive data\n page = page.join(DeviceTemplate) \\\n .join(DeviceAttr, isouter=True) \\\n .join(DeviceOverride, (Device.id == DeviceOverride.did) & (DeviceAttr.id == DeviceOverride.aid), isouter=True)\n\n page = page.filter(*label_filter) \\\n .filter(*template_filter) \\\n .order_by(sortBy) \\\n .paginate(**pagination)\n\n else:\n LOGGER.debug(f\" Querying devices sorted by device id\")\n page = db.session.query(Device).order_by(sortBy).paginate(**pagination)\n\n devices = []\n \n if params.get('idsOnly').lower() in ['true', '1', '']:\n return DeviceHandler.get_only_ids(page)\n\n for d in page.items:\n devices.append(serialize_full_device(d, tenant, sensitive_data))\n\n\n result = {\n 'pagination': {\n 'page': page.page,\n 'total': page.pages,\n 'has_next': page.has_next,\n 'next_page': page.next_num\n },\n 'devices': devices\n }\n\n return result",
"def _find_device(self):\n found_device = False\n nearby_devices = None\n try:\n nearby_devices = self._adapter.scan()\n except Exception:\n pass\n\n if nearby_devices is not None:\n for device in nearby_devices:\n name = device['name']\n if name is not None and name.startswith(self._search_name):\n self._address = device['address']\n print(f'Found device named: {name} at {self._address}')\n found_device = True\n break\n\n return found_device",
"def find_dev_by_prefix(devices, prefix):\n result = []\n for dev in devices.values():\n if dev.unique_id.startswith(prefix):\n result.append(dev)\n return result",
"def find_usage(cls, usage_id):\n return cls._usage_index[usage_id]",
"def find_devices_by_hints(devices, root_device_hints):\n LOG.debug('Trying to find devices from \"%(devs)s\" that match the '\n 'device hints \"%(hints)s\"',\n {'devs': ', '.join([d.get('name') for d in devices]),\n 'hints': root_device_hints})\n parsed_hints = parse_root_device_hints(root_device_hints)\n for dev in devices:\n device_name = dev.get('name')\n\n for hint in parsed_hints:\n hint_type = VALID_ROOT_DEVICE_HINTS[hint]\n device_value = dev.get(hint)\n hint_value = parsed_hints[hint]\n\n if hint_type is str:\n try:\n device_value = _normalize_hint_expression(device_value,\n hint)\n except ValueError:\n LOG.warning(\n 'The attribute \"%(attr)s\" of the device \"%(dev)s\" '\n 'has an empty value. Skipping device.',\n {'attr': hint, 'dev': device_name})\n break\n\n if hint == 'size':\n # Since we don't support units yet we expect the size\n # in GiB for now\n device_value = device_value / units.Gi\n\n LOG.debug('Trying to match the device hint \"%(hint)s\" '\n 'with a value of \"%(hint_value)s\" against the same '\n 'device\\'s (%(dev)s) attribute with a value of '\n '\"%(dev_value)s\"', {'hint': hint, 'dev': device_name,\n 'hint_value': hint_value,\n 'dev_value': device_value})\n\n # NOTE(lucasagomes): Boolean hints are not supported by\n # specs_matcher.match(), so we need to do the comparison\n # ourselves\n if hint_type is bool:\n try:\n device_value = strutils.bool_from_string(device_value,\n strict=True)\n except ValueError:\n LOG.warning('The attribute \"%(attr)s\" (with value '\n '\"%(value)s\") of device \"%(dev)s\" is not '\n 'a valid Boolean. Skipping device.',\n {'attr': hint, 'value': device_value,\n 'dev': device_name})\n break\n if device_value == hint_value:\n continue\n\n elif specs_matcher.match(device_value, hint_value):\n continue\n\n LOG.debug('The attribute \"%(attr)s\" (with value \"%(value)s\") '\n 'of device \"%(dev)s\" does not match the hint %(hint)s',\n {'attr': hint, 'value': device_value,\n 'dev': device_name, 'hint': hint_value})\n break\n else:\n yield dev",
"def searchCmdUsage(self, searchStr):\n attr = self.__listAttr()\n for name in attr:\n if name.lower() == searchStr.lower() + '_usage':\n return name, getattr(self, name)\n return None, None",
"def list_devices(arn=None, nextToken=None):\n pass",
"async def find_devices() -> List[DeviceInfo]:\n return await Discovery.search_devices()",
"def retr_devices_by_app( app ) :\n\n\t\t\t_logger.info( '...retr_devices_by_app...' )\n\t\t\toutput = []\n\t\t\ttry :\n\t\t\t\tdb = mongo.db.auth_devices\n\t\t\t\tfor device in db.find( { 'app_tags' : app } ) :\n\t\t\t\t\toutput.append({'moniker' : device['moniker'] ,\n\t\t\t\t\t\t\t\t 'description' : device['description'] ,\n\t\t\t\t\t\t\t\t 'active' : device['active'] ,\n\t\t\t\t\t\t\t\t 'device_id' : device['device_id'] ,\n\t\t\t\t\t\t\t\t 'enlisted' : device['enlisted'] ,\n\t\t\t\t\t\t\t\t 'last_kown_remote_ip' : device['last_known_remote_ip'] ,\n\t\t\t\t\t\t\t\t 'engaged' : device['engaged'] ,\n\t\t\t\t\t\t\t\t 'canononical_user' : device['canonical_user'] ,\n\t\t\t\t\t\t\t\t 'scope' : device['scope'] ,\n\t\t\t\t\t\t\t\t 'segment' : device['segment']\n\t\t\t\t\t})\n\t\t\texcept Exception as e :\n\t\t\t\t _logger.error( '...retr_devices_by_app %s' % e.message )\n\t\t\treturn jsonify({'result' : output})",
"def discoverDevice(\n self, ip, devicepath=None, prodState=None, deviceConfig=None\n ):\n if devicepath is None:\n devicepath = self.options.deviceclass\n if prodState is None:\n prodState = self.options.productionState\n\n self.scanned += 1\n if self.options.maxdevices:\n if self.scanned >= self.options.maxdevices:\n self.log.info(\n \"Limit of %d devices reached\", self.options.maxdevices\n )\n defer.returnValue(None)\n\n try:\n kw = dict(\n deviceName=ip,\n discoverProto=None,\n devicePath=devicepath,\n performanceMonitor=self.options.monitor,\n locationPath=self.options.location,\n groupPaths=self.options.groups,\n systemPaths=self.options.systems,\n productionState=prodState,\n )\n\n # If zProperties are set via a job, get them and pass them in\n if self.options.job:\n job_props = yield self.config().callRemote(\n \"getJobProperties\", self.options.job\n )\n if job_props is not None:\n # grab zProperties from Job\n kw[\"zProperties\"] = getattr(job_props, \"zProperties\", {})\n # grab other Device properties from jobs\n # deviceProps = job_props.get('deviceProps', {})\n # kw.update(deviceProps)\n # @FIXME we are not getting deviceProps, check calling\n # chain for clues. twisted upgrade heartburn perhaps?\n\n # if we are using SNMP, lookup the device SNMP info and use the\n # name defined there for deviceName\n if not self.options.nosnmp:\n self.log.debug(\"Scanning device with address %s\", ip)\n zProps = kw.get(\"zProperties\", {})\n deviceSnmpCommunities = zProps.get(\"zSnmpCommunities\", None)\n if not deviceSnmpCommunities and deviceConfig:\n deviceSnmpCommunities = getattr(\n deviceConfig, \"zSnmpCommunities\", None\n )\n\n snmp_config = yield self.findRemoteDeviceInfo(\n ip, devicepath, deviceSnmpCommunities\n )\n if snmp_config:\n if snmp_config.sysName:\n kw[\"deviceName\"] = snmp_config.sysName\n if snmp_config.version:\n kw[\"zSnmpVer\"] = snmp_config.version\n if snmp_config.port:\n kw[\"zSnmpPort\"] = snmp_config.port\n if snmp_config.community:\n kw[\"zSnmpCommunity\"] = snmp_config.community\n\n # Since we did not find any snmp info and we are in\n # strict discovery mode, do not create a device\n elif self.options.zSnmpStrictDiscovery:\n self.log.info(\n \"zSnmpStrictDiscovery is True. \"\n \"Not creating device for %s.\",\n ip,\n )\n defer.returnValue(None)\n\n # RULES FOR DEVICE NAMING:\n # 1. If zPreferSnmpNaming is true:\n # If snmp name is returned, use snmp name. Otherwise,\n # use the passed device name. If no device name was passed,\n # do a dns lookup on the ip.\n # 2. If zPreferSnmpNaming is false:\n # If we are discovering a single device and a name is\n # passed in instead of an IP, use the passed-in name.\n # Otherwise, do a dns lookup on the ip.\n if self.options.zPreferSnmpNaming and not isip(kw[\"deviceName\"]):\n # In this case, we want to keep kw['deviceName'] as-is,\n # because it is what we got from snmp\n pass\n elif self.options.device and not isip(self.options.device):\n kw[\"deviceName\"] = self.options.device\n else:\n # An IP was passed in so we do a reverse lookup on it to get\n # deviceName\n try:\n kw[\"deviceName\"] = yield asyncNameLookup(ip)\n except Exception as ex:\n self.log.debug(\"Failed to lookup %s (%s)\", ip, ex)\n\n # If it's discovering a particular device,\n # ignore zAutoDiscover limitations\n forceDiscovery = bool(self.options.device)\n\n # now create the device by calling zenhub\n result = None\n try:\n result = yield self.config().callRemote(\n \"createDevice\", ipunwrap(ip), force=forceDiscovery, **kw\n )\n except Exception as ex:\n raise ZentinelException(ex)\n\n self.log.debug(\"Got result from remote_createDevice: %s\", result)\n dev, created = result\n\n # if no device came back from createDevice we assume that it\n # was told to not auto-discover the device. This seems very\n # dubious to me! -EAD\n if not dev:\n self.log.info(\"IP '%s' on no auto-discover, skipping\", ip)\n defer.returnValue(None)\n\n # A device came back and it already existed.\n if not created and not dev.temp_device:\n # if we shouldn't remodel skip the device by returning\n # at the end of this block\n if not self.options.remodel:\n self.log.info(\n \"Found IP '%s' on device '%s';\" \" skipping discovery\",\n ip,\n dev.id,\n )\n if self.options.device:\n self.setExitCode(3)\n defer.returnValue(dev)\n else:\n # we continue on to model the device.\n self.log.info(\"IP '%s' on device '%s' remodel\", ip, dev.id)\n self.sendDiscoveredEvent(ip, dev)\n\n # the device that we found/created or that should be remodeled\n # is added to the list of devices to be modeled later\n if not self.options.nosnmp:\n self.discovered.append(dev.id)\n\n yield self.config().callRemote(\"succeedDiscovery\", dev.id)\n defer.returnValue(dev)\n except ZentinelException as e:\n self.log.exception(e)\n if self.options.snmpMissing:\n self.sendEvent(\n dict(\n device=ip,\n component=ip,\n ipAddress=ip,\n eventKey=ip,\n eventClass=Status_Snmp,\n summary=str(e),\n severity=Info,\n agent=\"Discover\",\n )\n )\n except Exception as e:\n self.log.exception(\"Failed device discovery for '%s'\", ip)\n finally:\n self.log.info(\"Finished scanning device with address %s\", ip)",
"def get_devices_summary():\n\n # This function was created to replace get_devices_information\n # because it wasn't detecting virtual systems in Palo Alto Virtual Systems\n global nipper_xml\n devices = {}\n headings = []\n\n # Add the table headings to a list\n for h in nipper_xml.findall(\"./summary/table/[@ref='SCOPE.AUDITDEVICELIST.TABLE']/headings/heading\"):\n if h not in headings:\n headings.append(h.text)\n\n for device in nipper_xml.findall(\"./summary/table/[@ref='SCOPE.AUDITDEVICELIST.TABLE']/tablebody/tablerow\"):\n values = []\n for i in device.findall('./tablecell/item'):\n if i not in values:\n values.append(i.text)\n if DEBUG:\n print \"\\t\" + note + \"%s: %s\" % (headings[headings.index('Name')], values[headings.index('Name')])\n print \"\\t\" + note + \"%s: %s\" % (headings[headings.index('Device')], values[headings.index('Device')])\n print \"\\t\" + note + \"%s: %s\" % (headings[headings.index('OS')], values[headings.index('OS')].split(\" \")[0])\n print \"\\t\" + note + \"%s: %s\" % (headings[headings.index('OS')], values[headings.index('OS')].split(\" \")[1])\n devices[values[headings.index('Name')]] = {'name': values[headings.index('Name')],\n 'type': values[headings.index('Device')],\n 'os': values[headings.index('OS')].split(' ')[0],\n 'osversion': values[headings.index('OS')].split(' ')[1]\n }\n\n if DEBUG:\n print info + \"Device Object:\"\n print devices\n raw_input(warn + \"Press enter to continue\")\n return devices",
"def find(vps, sn = None):\n devices = UsbTools.find_all(vps)\n # do we have any devices?\n if len(devices) == 0:\n return None, 'no device found'\n if sn is not None:\n # filter using the serial number\n devices_sn = [d for d in devices if d[2] == sn]\n if len(devices_sn) == 0:\n # we have devices, but none with this serial number\n s = []\n s.append('no device with this serial number')\n s.append('devices found:')\n for d in devices:\n s.append('%04x:%04x sn %r' % (d[0], d[1], d[2]))\n return None, '\\n'.join(s)\n else:\n devices = devices_sn\n # no devices\n if len(devices) == 0:\n return None, 'no device found'\n # multiple devices\n if len(devices) > 1:\n s = []\n s.append('multiple devices found:')\n for d in devices:\n s.append('%04x:%04x sn %r' % (d[0], d[1], d[2]))\n return None, '\\n'.join(s)\n # 1 device\n return devices[0], None",
"def devices(self, query=None):\n if query is not None:\n query = clean(query, self.devices_parameters)\n query = \"?\" + urllib.parse.urlencode(query)\n else:\n query = \"\"\n return self.get(\"/devices\" + query)",
"def search(self,name=None):\n\t\taddresses = discover_devices()\n\t\t#if len(addresses) == 0:\n\t\t#\treturn None\n\t\tnames = []\n\t\tfor adr in addresses:\n\t\t\tnames.append(lookup_name(adr))\n\t\t\tif name != None and name == names[-1]:\n\t\t\t\treturn adr\n\n\t\treturn zip(addresses,names)",
"def scan_devices(self):\n self._update_info()\n\n return self.last_results",
"def find_device(device):\n return usb.core.find(idVendor=device['idVendor'], idProduct=device['idProduct'])",
"def find(cls, device_name):\n return cls.query(cls.device_name == device_name).fetch(1)",
"async def device_info(request):\n textx = await request.get_reply_message()\n codename = request.pattern_match.group(1)\n if codename:\n pass\n elif textx:\n codename = textx.text\n else:\n await edit_or_reply(request, \"`Usage: .device <codename> / <model>`\")\n return\n data = json.loads(\n get(\n \"https://raw.githubusercontent.com/androidtrackers/\"\n \"certified-android-devices/master/by_device.json\"\n ).text\n )\n results = data.get(codename)\n if results:\n reply = f\"**Search results for {codename}**:\\n\\n\"\n for item in results:\n reply += (\n f\"**Brand**: `{item['brand']}`\\n\"\n f\"**Name**: `{item['name']}`\\n\"\n f\"**Model**: `{item['model']}`\\n\\n\"\n )\n else:\n reply = f\"`Couldn't find info about {codename}!`\\n\"\n await edit_or_reply(request, reply)",
"def user_sends_get_call_to_the_devices():\n web_app.list_devices()",
"def test_get_devices1(self):\n pass",
"def device_info(device_id):\n device_info_map = listall.device_raw_info()[\"devices\"]\n for operating_system in device_info_map.keys():\n devices = device_info_map[operating_system]\n for device in devices:\n if device[\"udid\"].lower() == device_id.lower():\n return device\n return None",
"def flask_internal_get_devices():\n try:\n # retrieve the authorization token\n token = retrieve_auth_token(request)\n\n # retrieve pagination\n page_number, per_page = get_pagination(request)\n\n params = {\n 'page_number': page_number,\n 'per_page': per_page,\n 'sortBy': request.args.get('sortBy', None),\n 'attr': request.args.getlist('attr'),\n 'attr_type': request.args.getlist('attr_type'),\n 'label': request.args.get('label', None),\n 'template': request.args.get('template', None),\n 'idsOnly': request.args.get('idsOnly', 'false'),\n }\n\n result = DeviceHandler.get_devices(token, params, True)\n LOGGER.info(f' Getting known internal devices.')\n \n return make_response(jsonify(result), 200)\n except HTTPRequestError as e:\n LOGGER.error(f' {e.message} - {e.error_code}.')\n if isinstance(e.message, dict):\n return make_response(jsonify(e.message), e.error_code)\n\n return format_response(e.error_code, e.message)",
"def flask_get_devices():\n try:\n # retrieve the authorization token\n token = retrieve_auth_token(request)\n\n # retrieve pagination\n page_number, per_page = get_pagination(request)\n\n params = {\n 'page_number': page_number,\n 'per_page': per_page,\n 'sortBy': request.args.get('sortBy', None),\n 'attr': request.args.getlist('attr'),\n 'attr_type': request.args.getlist('attr_type'),\n 'label': request.args.get('label', None),\n 'template': request.args.get('template', None),\n 'idsOnly': request.args.get('idsOnly', 'false'),\n }\n\n result = DeviceHandler.get_devices(token, params)\n LOGGER.info(f' Getting latest added device(s).')\n\n return make_response(jsonify(result), 200)\n except HTTPRequestError as e:\n LOGGER.error(f' {e.message} - {e.error_code}.')\n if isinstance(e.message, dict):\n return make_response(jsonify(e.message), e.error_code)\n\n return format_response(e.error_code, e.message)",
"def device_by_nickname(self, nickname):\n devices = self.list_devices()\n if devices:\n return next((d[\"iden\"] for d in devices.get(\"devices\", [])\n if nickname == d.get(\"nickname\")), None)",
"def test_get_devices(self):\n pass",
"def test_get_devices(self):\n pass",
"def getDevices(i):\n devices = Account['KTFLR'].devices('monpressprod')\n device = devices[i]\n return device"
] | [
"0.6269344",
"0.5997133",
"0.59589404",
"0.588711",
"0.5793125",
"0.57546246",
"0.568376",
"0.56786346",
"0.55943453",
"0.550942",
"0.55043346",
"0.54662585",
"0.54382575",
"0.5410512",
"0.54044867",
"0.5389828",
"0.5379705",
"0.5365242",
"0.53301144",
"0.5328609",
"0.5327337",
"0.5292771",
"0.5289681",
"0.52335787",
"0.5224841",
"0.52182925",
"0.5208202",
"0.5177173",
"0.5177173",
"0.5174263"
] | 0.7825975 | 0 |
function to convert contribs collection items to edges ones edge doc {_id, name_1, name_2, tags [{name, urls[]}]} =========================================================== if src in srcs then skip if name_1 and name_2 not found then insert new doc if tag.name not found then insert new tag if tag.url not found then insert new url | def contribs2edges():
client = mongo.MongoClient(config["MONGO_URI"])
db = client.links
db.edges.remove()
edges = dict()
for contrib in db.contribs.find():
for item in contrib["data"]:
id = u"{} {}".format(item["name_1"], item["name_2"]).replace(" ", "_")
edge = edges.get(id) #db.edges.find_one({"_id" : id}))
if not edge:
edge = {"_id" : id, "name_1" : item["name_1"], "name_2" : item["name_2"], "tags" : []}
for tag in item["tags"]:
edge_tag = filter(lambda x: x["name"] == tag, edge["tags"])
if len(edge_tag):
edge_tag = edge_tag[0]
else:
edge_tag = {"name" : tag, "urls" : []}
edge["tags"].append(edge_tag)
if item["url"] not in edge_tag["urls"]:
edge_tag["urls"].append(item["url"])
if id not in edges:
edges[id] = edge
db.edges.insert(edges.values()) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def construct_edge_list(cong):\n usr_to_src = []\n list_to_exclude = [\n 'twitter',\n 'youtu',\n 'fllwrs',\n 'unfollowspy',\n 'livetv',\n 'pscp',\n 'live',\n 'ln.is',\n 'tinyurl',\n 'facebook',\n 'bit.ly',\n 'goo.gl',\n 'instagram',\n 'google'\n ]\n for x in cong:\n if x[2]:\n for url in x[2].split(','):\n if not any(y in url for y in list_to_exclude) and x[0] not in url.replace('.', '_'):\n if url.endswith('.com') and url.startswith(\"http://www\"):\n usr_to_src.append((x[0], url.split('.')[1].lower()))\n elif url.endswith('.com') and url.startswith(\"http://m\"):\n usr_to_src.append((x[0], url.split('.')[1].lower()))\n elif url.endswith('.in') and url.startswith(\"http://www\"):\n usr_to_src.append((x[0], url.split('.')[1].lower()))\n elif url.startswith(\"http://\") or url.startswith(\"https://\"):\n l_url = url.split('/')\n if len(l_url) >= 3 and '.' in l_url[2]:\n if l_url[2].startswith('www') or l_url[2].startswith('m'):\n usr_to_src.append(\n (x[0], l_url[2].split('.')[1].lower()))\n else:\n usr_to_src.append((x[0], l_url[2].lower()))\n\n ll = []\n for i in cong:\n if i[1]:\n for x in i[1].split(','):\n if (x != '@'):\n x = x.replace('@', '')\n ll.append((i[0], x))\n return (ll, usr_to_src)",
"def extract_sources(self, doc):\n self.log.info(\"Extracting sources for %s\" % doc)\n\n sources_added = 0\n\n for u in doc.utterances:\n if u.entity.person:\n p = u.entity.person\n\n s = DocumentSource()\n s.person = p\n s.affiliation = p.affiliation\n s.quoted = True\n s.unnamed = False\n\n if doc.add_source(s):\n sources_added += 1\n\n self.log.info(\"Added %d sources for %s\" % (sources_added, doc))",
"def get_prep_tags(src_xml, d1):\n root, tree = gen_tree(src_xml)\n d2 = OrderedDict()\n # list of old rIds\n rId_lis = [i for i in d1.keys()]\n nmsps = root.nsmap['r']\n ext_lst = []\n \n for relation in root:\n for ele in relation:\n attrib = ele.attrib\n tag = ele.tag\n # try:\n # if attrib[f\"{{{nmsps}}}id\"]:\n if attrib.get(f\"{{{nmsps}}}id\"):\n if attrib.get(f\"{{{nmsps}}}id\") in rId_lis:\n if relation.tag in d2:\n val = d2[relation.tag]\n val.append([tag, attrib.get('id'), attrib.get(f\"{{{nmsps}}}id\")])\n d2[relation.tag] = val\n else:\n d2[relation.tag] = [[tag, attrib.get('id'), attrib.get(f\"{{{nmsps}}}id\")]]\n else:\n if 'uri' in ele.attrib:\n if relation.tag not in ext_lst:\n ext_lst.append(relation.tag)\n # print(\"ELE11: \", ele)\n # extLst.append(ele)\n # if relation.tag in d2:\n # val = d2[relation.tag]\n # val.append(ele)\n # d2[relation.tag] = val\n # else:\n # d2[relation.tag] = [ele]\n d2 = modify_d2(d1, d2)\n return d2, ext_lst",
"def igraph2mongo(graph,collection,mode='OUT',overwrite = False):\r\n for i in graph.vs:\r\n if not list(collection.find({'_id':i.index})):\r\n post = {\"_id\": i.index,\r\n \"neighbors_{}\".format(mode):list(set(graph.neighbors(i.index,mode=mode)))}\r\n post_id = collection.insert_one(post).inserted_id\r\n print( \"node \",post_id,\" added\")\r\n elif overwrite == True:\r\n post = {\"_id\": i.index,\r\n \"neighbors_{}\".format(mode):list(set(graph.neighbors(i.index,mode=mode)))}\r\n collection.replace_one({'_id':i.index},post)\r\n print(\"node \",i.index,\" replaced\")\r\n else:\r\n# print(\"THIS object has the _id\",i.index,list(collection.find({'_id':i.index})))\r\n pass\r\n if overwrite == True:\r\n print(collection, \"has been changed\")",
"def merge_docs(self):",
"def canonicalize(tags):\n # test format \n r = random.randint(0, len(tags)-1)\n\n # in multilabel format? each tag is in the form of [e1, e2, ...]\n isMultiLabel = True if hasattr(tags[r], '__iter__') else False\n\n if isMultiLabel: # i.e. each label is a list\n print('TDocTag.canonicalize> input labels in multilabel format.')\n docTags = []\n for i, tag in enumerate(tags): \n \n # docId = TDocTag.getDocID(i)\n docId = i # set docId here\n if tag[0] == docId: \n # do nothing, first element is already the intended docId\n pass \n else: \n tag.insert(0, docId)\n docTags.append(tag)\n else: \n docTags = []\n for i, tag in enumerate(tags): \n if i < 3: assert isinstance(tag, str)\n docId = i # docId = TDocTag.getDocID(i) \n docTags.append([docId, tag, ]) \n return docTags",
"def copy_tags(apps, schema_editor):\n TaggitTag = apps.get_model('taggit', 'Tag')\n ExtrasTag = apps.get_model('extras', 'Tag')\n\n tags_values = TaggitTag.objects.all().values('id', 'name', 'slug')\n tags = [ExtrasTag(**tag) for tag in tags_values]\n ExtrasTag.objects.bulk_create(tags)",
"def insert_values():\n merged_df = pd.read_csv(\"merged_fuzzy_df.csv\")\n df = pd.read_csv(\"df.csv\")\n story_entity_df = pd.read_csv(\"story_entity_df.csv\")\n\n merged_df['entity_id'] = merged_df['entity_id'].apply(str)\n\n # find and input new types\n TYPES = get_types_ids(list(story_entity_df[\"label\"].unique()))\n\n new_parents = {}\n new_alias = {}\n\n merged_df[\"wiki\"].fillna(\"\", inplace=True)\n\n # if score = -2, it needs new alias as well as new parents\n for index, row in merged_df[merged_df[\"score\"] == -2].iterrows():\n\n # create a new parent\n if row[\"text\"] not in new_parents:\n new_parents[row[\"text\"]] = [\n str(uuid.uuid4()),\n row[\"text\"],\n TYPES[row[\"label\"]],\n row[\"wiki\"],\n True,\n str(datetime.utcnow())\n ]\n\n merged_df.at[index,\n \"entity_id\"] = new_parents[row[\"text\"]][0]\n\n # add alias with corresponding parent ID\n if row[\"text\"] not in new_alias:\n new_alias[row[\"text\"]] = [\n str(uuid.uuid4()),\n row[\"text\"],\n row[\"wiki\"],\n row[\"score\"],\n str(datetime.utcnow()),\n new_parents[row[\"text\"]][0],\n TYPES[row[\"label\"]]\n ]\n\n for index, row in merged_df[merged_df[\"score\"] >= -1].iterrows():\n # if score >= -1, it needs new alias\n if row[\"text\"] not in new_alias:\n new_alias[row[\"text\"]] = [\n str(uuid.uuid4()),\n row[\"text\"],\n row[\"wiki\"],\n row[\"score\"],\n str(datetime.utcnow()),\n row[\"entity_ref_id\"],\n TYPES[row[\"label\"]]\n ]\n\n merged_df.at[index,\n \"entity_id\"] = row[\"entity_ref_id\"]\n\n # if already matched, write story_entity_id into entity_id for mapping\n for index, row in merged_df[merged_df[\"score\"].isnull()].iterrows():\n merged_df.at[index,\n \"entity_id\"] = row[\"entity_ref_id\"]\n\n for _, value in new_parents.items():\n STORY_REF_INPUTS.append(value)\n\n for _, value in new_alias.items():\n ENTITY_ALIAS_INPUTS.append(value)\n\n logging.info(\"parents: {}\".format(len(STORY_REF_INPUTS)))\n logging.info(\"alias: {}\".format(len(ENTITY_ALIAS_INPUTS)))\n\n columns_to_drop = [\"legal_name\", \"wiki\", \"label\",\n \"entity_ref_id\", \"entity_name\",\n \"text\", \"score\"]\n merged_df.drop(columns_to_drop, axis=1, inplace=True)\n\n # generate uuids for story_map\n uuids = []\n for _ in range(len(merged_df)):\n uuids.append(str(uuid.uuid4()))\n\n logging.info(\"check na {}\".format(merged_df.isnull().values.any()))\n\n # input new_entites to table\n # using entity UUID and story UUID to apis_story_enity_map table\n\n merged_df[\"uuid\"] = uuids\n merged_df[\"created_at\"] = str(datetime.utcnow())\n\n merged_df = merged_df[[\"uuid\", \"entity_id\",\n \"story_uuid\", \"mentions\",\n \"salience\", \"created_at\"]]\n\n STORY_MAP_INPUTS = [tuple(row)\n for row in merged_df.itertuples(index=False)]\n\n # see if there are apis_entity elements in the stories\n match_manual_entity_to_story(df)\n\n insert_story_entity_ref(STORY_REF_INPUTS)\n insert_entity_alias(ENTITY_ALIAS_INPUTS)\n insert_story_entity_map(STORY_MAP_INPUTS)\n\n logging.info(\"finished\")\n\n logging.info(\"delete articles without entities\")\n articles_without_entities(df, story_entity_df)",
"def copy_images(apps, schema_editor):\n\n FieldImage = apps.get_model('field_wagtail', 'FieldImage')\n Image = apps.get_model('wagtailimages', 'Image')\n django_content_type = apps.get_model('contenttypes', 'contenttype')\n tagged_item_model = apps.get_model('taggit', 'TaggedItem')\n\n images = Image.objects.all()\n new_images = []\n for image in images:\n new_images.append(FieldImage(\n id=image.id,\n title=image.title,\n file=image.file,\n width=image.width,\n height=image.height,\n created_at=image.created_at,\n focal_point_x=image.focal_point_x,\n focal_point_y=image.focal_point_y,\n focal_point_width=image.focal_point_width,\n focal_point_height=image.focal_point_height,\n file_size=image.file_size,\n collection=image.collection,\n uploaded_by_user=image.uploaded_by_user,\n alt_text=''\n ))\n\n FieldImage.objects.bulk_create(new_images)\n\n ct_extended_model, created = django_content_type.objects.get_or_create(\n app_label='field_wagtail',\n model='fieldimage'\n )\n ct_wagtail_model = django_content_type.objects.get(\n app_label='wagtailimages',\n model='image'\n )\n\n tagged_item_model.objects.filter(\n content_type_id=ct_wagtail_model.id).update(\n content_type_id=ct_extended_model.id\n )",
"def transform4Doc2Vec(docs):\n\n # transform documents to be used by doc2Vec\n documents = []\n analyzedDocument = namedtuple('AnalyzedDocument', 'words tags')\n for i, doc in enumerate(docs):\n # use first line if documents are not tokenized, otherwise next line\n # words = text.lower().split()\n tags = [i]\n documents.append(analyzedDocument(doc, tags))\n\n return documents",
"def add_tagged_ways(file_input, cut_edges):\n\n # New way will be created like this. Second '%s' is for nodes.\n new_way_template = \\\n ' <way id=\"%s\" user=\"OSM-dead-end-painter\" visible=\"true\">\\n' + \\\n '%s' + \\\n ' <tag k=\"highway\" v=\"service\"/>\\n' + \\\n ' <tag k=\"construction\" v=\"cut-edge\"/>\\n' + \\\n ' <tag k=\"layer\" v=\"10\"/>\\n' + \\\n ' </way>\\n'\n # way_id must be unique within DB, so pick some very large start\n very_large_offset = 1000000000\n\n way_id = False # False when outside a way. Otherwise, way_id.\n out_buffer = \"\" # We collect everything into here while inside <way> element\n\n # Assumption: all ways begin and end like this. It is so in OSM exports.\n way_begin = re.compile(\"<way id=\\\"(\\d+)\\\"\")\n way_end = re.compile(\"</way>\")\n nd = re.compile(\"<nd ref=\\\"(\\d+)\\\"\")\n\n for line in fileinput.input(file_input):\n if not way_id:\n compatible_print(line)\n way_found = way_begin.search(line)\n if way_found:\n way_id = way_found.groups()[0]\n way_nodes = []\n way_has_cut_edges = False\n cur_cut_edge_nodes = \"\"\n in_cut_segment = False\n prev_node = None\n # Collector for all new ways made from cut segments of current way:\n cut_ways_collector = \"\"\n continue\n\n # Here, we are inside <way> element.\n\n nd_found = nd.search(line)\n if nd_found: # New node reference on this way\n new_node = nd_found.groups()[0]\n way_nodes.append(new_node)\n if prev_node != None:\n # Check if this subsegment is in cut_edge set.\n # It can be also \"the other way around\", but it is important to store it\n # in the order in which the way traversed it.\n if ((prev_node, new_node) in cut_edges) or ((new_node, prev_node) in cut_edges):\n if in_cut_segment:\n # We were in cut segment, it just continues.\n cur_cut_edge_nodes += ' <nd ref=\"%s\"/>\\n' % new_node\n else:\n # We were not in cut segment. It started.\n cur_cut_edge_nodes = ' <nd ref=\"%s\"/>\\n <nd ref=\"%s\"/>\\n' % (prev_node, new_node)\n in_cut_segment = True\n way_has_cut_edges = True\n else:\n # Last edge is not cutting.\n if in_cut_segment:\n # We were previously in cut segment, and it ended. Form the new way.\n cut_ways_collector += new_way_template % (very_large_offset, cur_cut_edge_nodes)\n very_large_offset += 1\n else:\n # We were not in cut segment, and are not. No action.\n pass\n in_cut_segment = False\n\n # end of \"if (prev, new) in cut_edges\"\n\n prev_node = new_node\n\n if way_end.search(line):\n # End of the way. Flush all collected lines and process the way if needed.\n # First, print the existing way\n compatible_print(out_buffer)\n out_buffer = \"\"\n way_id = False\n # and the closing tag of the existing way\n compatible_print(line)\n\n # Now, output new ways, if there are any\n if way_has_cut_edges:\n # We updated cut_ways_collector only when a cutting segment changes to non-cutting.\n # But if the whole way ended and we were in cutting segment, we must\n # update cut_ways_collector separately.\n if in_cut_segment:\n cut_ways_collector += new_way_template % (very_large_offset, cur_cut_edge_nodes)\n very_large_offset += 1\n compatible_print(cut_ways_collector)\n continue\n\n # We are still inside <way>, so add whatever we found to the future output\n out_buffer += line",
"def convert_2_data(\n users, items, ratings,\n train_ratio\n):\n def get_concept_num_from_str(df, concept_name):\n concept_strs = [concept_str.split(',') for concept_str in df[concept_name]]\n concepts = set(itertools.chain.from_iterable(concept_strs))\n concepts.remove('')\n num_concepts = len(concepts)\n return list(concepts), num_concepts\n\n num_users = users.shape[0]\n num_items = items.shape[0]\n\n ######################### Define entities #########################\n genders = list(users.gender.unique())\n num_genders = len(genders)\n\n occupations = list(users.occupation.unique())\n num_occupations = len(occupations)\n\n ages = list(users.age.unique())\n num_ages = len(ages)\n\n genres = list(items.keys()[3:20])\n num_genres = len(genres)\n\n years = list(items.year.unique())\n num_years = len(years)\n\n unique_directors, num_directors = get_concept_num_from_str(items, 'directors')\n unique_actors, num_actors = get_concept_num_from_str(items, 'actors')\n unique_writers, num_writers = get_concept_num_from_str(items, 'writers')\n\n ######################### Define number of entities #########################\n num_nodes = num_users + num_items + num_genders + num_occupations + num_ages + num_genres + num_years + \\\n num_directors + num_actors + num_writers\n num_node_types = 10\n\n ######################### Define entities to node id map #########################\n nid2e = {}\n acc = 0\n uid2nid = {uid: i + acc for i, uid in enumerate(users['uid'])}\n for i, uid in enumerate(users['uid']):\n nid2e[i + acc] = ('uid', uid)\n acc += num_users\n iid2nid = {iid: i + acc for i, iid in enumerate(items['iid'])}\n for i, iid in enumerate(items['iid']):\n nid2e[i + acc] = ('iid', iid)\n acc += num_items\n gender2nid = {gender: i + acc for i, gender in enumerate(genders)}\n for i, gender in enumerate(genders):\n nid2e[i + acc] = ('gender', gender)\n acc += num_genders\n occ2nid = {occupation: i + acc for i, occupation in enumerate(occupations)}\n for i, occ in enumerate(occupations):\n nid2e[i + acc] = ('occ', occ)\n acc += num_occupations\n age2nid = {age: i + acc for i, age in enumerate(ages)}\n for i, age in enumerate(ages):\n nid2e[i + acc] = ('age', age)\n acc += num_ages\n genre2nid = {genre: i + acc for i, genre in enumerate(genres)}\n for i, genre in enumerate(genres):\n nid2e[i + acc] = ('genre', genre)\n acc += num_genres\n year2nid = {year: i + acc for i, year in enumerate(years)}\n for i, year in enumerate(years):\n nid2e[i + acc] = ('year', year)\n acc += num_years\n director2nid = {director: i + acc for i, director in enumerate(unique_directors)}\n for i, director in enumerate(unique_directors):\n nid2e[i + acc] = ('director', director)\n acc += num_directors\n actor2nid = {actor: i + acc for i, actor in enumerate(unique_actors)}\n for i, actor in enumerate(unique_actors):\n nid2e[i + acc] = ('actor', actor)\n acc += num_actors\n writer2nid = {writer: i + acc for i, writer in enumerate(unique_writers)}\n for i, writer in enumerate(unique_writers):\n nid2e[i + acc] = ('writer', writer)\n e2nid = {'uid': uid2nid, 'iid': iid2nid, 'gender': gender2nid, 'occ': occ2nid, 'age': age2nid, 'genre': genre2nid,\n 'year': year2nid, 'director': director2nid, 'actor': actor2nid, 'writer': writer2nid}\n\n ######################### create graphs #########################\n edge_index_nps = {}\n print('Creating user property edges...')\n u_nids = [e2nid['uid'][uid] for uid in users.uid]\n gender_nids = [e2nid['gender'][gender] for gender in users.gender]\n gender2user_edge_index_np = np.vstack((np.array(gender_nids), np.array(u_nids)))\n occ_nids = [e2nid['occ'][occ] for occ in users.occupation]\n occ2user_edge_index_np = np.vstack((np.array(occ_nids), np.array(u_nids)))\n age_nids = [e2nid['age'][age] for age in users.age]\n age2user_edge_index_np = np.vstack((np.array(age_nids), np.array(u_nids)))\n edge_index_nps['gender2user'] = gender2user_edge_index_np\n edge_index_nps['occ2user'] = occ2user_edge_index_np\n edge_index_nps['age2user'] = age2user_edge_index_np\n\n print('Creating item property edges...')\n i_nids = [e2nid['iid'][iid] for iid in items.iid]\n year_nids = [e2nid['year'][year] for year in items.year]\n year2user_edge_index_np = np.vstack((np.array(year_nids), np.array(i_nids)))\n\n directors_list = [\n [director for director in directors.split(',') if director != '']\n for directors in items.directors\n ]\n directors_nids = [[e2nid['director'][director] for director in directors] for directors in directors_list]\n directors_nids = list(itertools.chain.from_iterable(directors_nids))\n d_i_nids = [[i_nid for _ in range(len(directors_list[idx]))] for idx, i_nid in enumerate(i_nids)]\n d_i_nids = list(itertools.chain.from_iterable(d_i_nids))\n director2user_edge_index_np = np.vstack((np.array(directors_nids), np.array(d_i_nids)))\n\n actors_list = [\n [actor for actor in actors.split(',') if actor != '']\n for actors in items.actors\n ]\n actor_nids = [[e2nid['actor'][actor] for actor in actors] for actors in actors_list]\n actor_nids = list(itertools.chain.from_iterable(actor_nids))\n a_i_nids = [[i_nid for _ in range(len(actors_list[idx]))] for idx, i_nid in enumerate(i_nids)]\n a_i_nids = list(itertools.chain.from_iterable(a_i_nids))\n actor2user_edge_index_np = np.vstack((np.array(actor_nids), np.array(a_i_nids)))\n\n writers_list = [\n [writer for writer in writers.split(',') if writer != '']\n for writers in items.writers\n ]\n writer_nids = [[e2nid['writer'][writer] for writer in writers] for writers in writers_list]\n writer_nids = list(itertools.chain.from_iterable(writer_nids))\n w_i_nids = [[i_nid for _ in range(len(writers_list[idx]))] for idx, i_nid in enumerate(i_nids)]\n w_i_nids = list(itertools.chain.from_iterable(w_i_nids))\n writer2user_edge_index_np = np.vstack((np.array(writer_nids), np.array(w_i_nids)))\n edge_index_nps['year2user'] = year2user_edge_index_np\n edge_index_nps['director2user'] = director2user_edge_index_np\n edge_index_nps['actor2user'] = actor2user_edge_index_np\n edge_index_nps['writer2user'] = writer2user_edge_index_np\n\n kwargs = {\n 'num_nodes': num_nodes, 'num_node_types': num_node_types,\n 'users': users, 'ratings': ratings, 'items': items,\n 'e2nid': e2nid, 'nid2e': nid2e\n }\n\n print('Creating rating property edges...')\n if train_ratio is not None:\n train_pos_unid_inid_map, test_pos_unid_inid_map, neg_unid_inid_map = {}, {}, {}\n\n user2item_edge_index_np = np.zeros((2, 0))\n pbar = tqdm.tqdm(users.uid, total=users.uid.shape[0])\n for uid in pbar:\n pbar.set_description('Creating the edges for the user {}'.format(uid))\n uid_ratings = ratings[ratings.uid == uid].sort_values('timestamp')\n uid_iids = uid_ratings[['iid']].to_numpy().reshape(-1)\n\n unid = e2nid['uid'][uid]\n train_pos_uid_iids = list(uid_iids[:-1])\n train_pos_uid_inids = [e2nid['iid'][iid] for iid in train_pos_uid_iids]\n test_pos_uid_iids = list(uid_iids[-1:])\n test_pos_uid_inids = [e2nid['iid'][iid] for iid in test_pos_uid_iids]\n neg_uid_iids = list(set(items.iid) - set(uid_iids))\n neg_uid_inids = [e2nid['iid'][iid] for iid in neg_uid_iids]\n\n train_pos_unid_inid_map[unid] = train_pos_uid_inids\n test_pos_unid_inid_map[unid] = test_pos_uid_inids\n neg_unid_inid_map[unid] = neg_uid_inids\n\n unid_user2item_edge_index_np = np.array([[unid for _ in range(len(train_pos_uid_inids))], train_pos_uid_inids])\n user2item_edge_index_np = np.hstack([user2item_edge_index_np, unid_user2item_edge_index_np])\n edge_index_nps['user2item'] = user2item_edge_index_np\n kwargs['edge_index_nps'] = edge_index_nps\n\n kwargs['train_pos_unid_inid_map'], kwargs['test_pos_unid_inid_map'], kwargs['neg_unid_inid_map'] = \\\n train_pos_unid_inid_map, test_pos_unid_inid_map, neg_unid_inid_map\n else:\n u_nids = [e2nid['uid'][uid] for uid in ratings.uid]\n i_nids = [e2nid['iid'][iid] for iid in ratings.iid]\n user2item_edge_index_np = np.vstack((np.array(u_nids), np.array(i_nids)))\n edge_index_nps['user2item'] = user2item_edge_index_np\n kwargs['edge_index_nps'] = edge_index_nps\n\n print('Building the item occurence map...')\n item_nid_occs = {}\n for iid in items.iid:\n item_nid_occs[e2nid['iid'][iid]] = ratings[ratings.iid == iid].iloc[0]['movie_count']\n kwargs['item_nid_occs'] = item_nid_occs\n return Data(**kwargs)",
"def update_genres(source_item: Dict, target_item: Dict) -> None:\n for genre in target_item.get('genre', []):\n for item in source_item['highlight'].get('genres', []):\n if genre['name'].strip() in remove_html_tags(item):\n genre['name'] = item",
"def documents(iati_import, activity, project, activities_globals):\n imported_docs = []\n changes = []\n\n xml_ns = 'http://www.w3.org/XML/1998/namespace'\n first_image = True\n\n for doc_link in activity.findall('document-link'):\n url = ''\n doc_format = ''\n title = ''\n title_language = ''\n category = ''\n language = ''\n\n if 'url' in doc_link.attrib.keys():\n url = doc_link.attrib['url']\n\n # Check if it's the first image\n if url and url.rsplit('.', 1)[1].lower() in VALID_IMAGE_EXTENSIONS and first_image:\n first_image = False\n continue\n\n if 'format' in doc_link.attrib.keys():\n if not len(doc_link.attrib['format']) > 75:\n doc_format = doc_link.attrib['format']\n else:\n add_log(iati_import, 'document_link_format',\n 'format is too long (75 characters allowed)', project)\n\n # Check if the format is 'application/http'\n if doc_format == 'application/http':\n continue\n\n title_element = doc_link.find('title')\n if not title_element is None:\n title = get_text(title_element, activities_globals['version'])\n if len(title) > 100:\n add_log(iati_import, 'document_link_title',\n 'title is too long (100 characters allowed)', project,\n IatiImportLog.VALUE_PARTLY_SAVED)\n title = title[:100]\n\n if activities_globals['version'][0] == '1' and \\\n '{%s}lang' % xml_ns in title_element.attrib.keys():\n if not len(title_element.attrib['{%s}lang' % xml_ns]) > 2:\n title_language = title_element.attrib['{%s}lang' % xml_ns]\n else:\n add_log(iati_import, 'document_link_title_language',\n 'language is too long (2 characters allowed)', project)\n elif activities_globals['version'][0] == '2':\n narrative_element = title_element.find('narrative')\n if not narrative_element is None and \\\n '{%s}lang' % xml_ns in narrative_element.attrib.keys():\n if not len(narrative_element.attrib['{%s}lang' % xml_ns]) > 2:\n title_language = narrative_element.attrib['{%s}lang' % xml_ns]\n else:\n add_log(iati_import, 'document_link_title_language',\n 'language is too long (2 characters allowed)', project)\n\n category_element = doc_link.find('category')\n if not category_element is None and 'code' in category_element.attrib.keys():\n if not len(category_element.attrib['code']) > 3:\n category = category_element.attrib['code']\n else:\n add_log(iati_import, 'document_link_category',\n 'category is too long (3 characters allowed)', project)\n\n language_element = doc_link.find('language')\n if not language_element is None and 'code' in language_element.attrib.keys():\n if not len(language_element.attrib['code']) > 2:\n language = language_element.attrib['code']\n else:\n add_log(iati_import, 'document_link_language',\n 'language is too long (2 characters allowed)', project)\n\n doc, created = get_model('rsr', 'projectdocument').objects.get_or_create(\n project=project,\n url=url,\n format=doc_format,\n title=title,\n title_language=title_language,\n category=category,\n language=language\n )\n\n if created:\n changes.append(u'added project document (id: %s): %s' % (str(doc.pk), doc))\n\n imported_docs.append(doc)\n\n for doc_link in project.documents.all():\n if not doc_link in imported_docs:\n changes.append(u'deleted project document (id: %s): %s' %\n (str(doc_link.pk),\n doc_link.__unicode__()))\n doc_link.delete()\n\n return changes",
"def copy_taggeditems(apps, schema_editor):\n TaggitTaggedItem = apps.get_model('taggit', 'TaggedItem')\n ExtrasTaggedItem = apps.get_model('extras', 'TaggedItem')\n\n tagged_items_values = TaggitTaggedItem.objects.all().values('id', 'object_id', 'content_type_id', 'tag_id')\n tagged_items = [ExtrasTaggedItem(**tagged_item) for tagged_item in tagged_items_values]\n ExtrasTaggedItem.objects.bulk_create(tagged_items)",
"def migrate_doc(doc: DocCursor) -> DocCursor:\n for transform in transforms:\n doc = transform(doc)\n doc.nested_set_renumber(bulk_create=False)\n for node in doc.walk():\n node.save()\n return doc",
"def add_extLst(src_xml, des_xml, ext_lst, tag_dict):\n inp_root,_ = gen_tree(src_xml)\n out_root, out_tree = gen_tree(des_xml)\n \n for relation in ext_lst:\n \n # if relation in tag_dict.keys():\n # print(\"JJJ: \", relation)\n # print(\"PPP: \", tag_dict[relation])\n for elt in inp_root.findall(relation):\n # print(\"ELE: \", elt.tag)\n out_root.append(elt)\n\n out_tree.write(des_xml, pretty_print=True, xml_declaration=True, encoding='UTF-8', standalone=True)\n return",
"async def paths_from_src(\n src: str = Query(..., description=\"starting article\"),\n dsts: list[str] = Query(..., description=\"destination articles\"),\n db: Session = Depends(database.get_db),\n):\n paths: dict[str, Optional[ArticlePath]] = {}\n ppd = multi_target_bfs(db, src)\n for dst in dsts:\n dst_id = title_to_id(db, dst)\n path = follow_parent_pointers(dst_id, ppd)\n if path is None:\n paths[dst] = None\n continue\n article_path = []\n for article_id in path:\n article_title = id_to_title(db, article_id)\n article_url = f\"https://en.wikipedia.org/?curid={article_id}\"\n article_path.append(\n ArticleWrapper(\n id=article_id,\n title=article_title,\n link=article_url, # type: ignore\n )\n )\n paths[dst] = ArticlePath(articles=article_path)\n return ManyArticlePaths(paths=paths)",
"def exportToDB(self, submissions):\n for p in range(len(submissions)):\n for x in range(len(submissions[p])):\n doc_ref = self.fs_db.collection(u'reddit').document(str(submissions[p][4]))\n doc_ref.set({\n u'content': str(submissions[p][0]),\n u'upvote_ratio': str(submissions[p][1]),\n u'score': submissions[p][2],\n u'title': submissions[p][3],\n u'id': submissions[p][4],\n u'total_awards_received': submissions[p][5],\n u'created_utc': submissions[p][6]\n })",
"def upgrade_to_2():\n\n def update_file_origins(cont_list, cont_name):\n for container in cont_list:\n updated_files = []\n for file in container.get('files', []):\n origin = file.get('origin')\n if origin is not None:\n if origin.get('name', None) is None:\n file['origin']['name'] = origin['id']\n if origin.get('method', None) is None:\n file['origin']['method'] = ''\n updated_files.append(file)\n\n query = {'_id': container['_id']}\n update = {'$set': {'files': updated_files}}\n result = config.db[cont_name].update_one(query, update)\n\n query = {'$and':[{'files.origin.name': { '$exists': False}}, {'files.origin.id': { '$exists': True}}]}\n\n update_file_origins(config.db.collections.find(query), 'collections')\n update_file_origins(config.db.projects.find(query), 'projects')\n update_file_origins(config.db.sessions.find(query), 'sessions')\n update_file_origins(config.db.acquisitions.find(query), 'acquisitions')",
"def mergeURLS(inputs):\n urls = set()\n for i in inputs:\n # Re-raise any exceptions\n try:\n urls = urls.union(i.urls())\n except:\n raise\n return urls",
"def createStructuredTranscript_Non_Core_Doc():\n\n #create a temporary folder that will hold the data transformed from doc to docx\n os.system('mkdir ' + INPUT_FOLDER+'temp')\n\n core_doc_asset = []\n missing_count = 0\n missing_files=[]\n # get all the docx files that are part of the core asset\n for file in glob.glob(INPUT_FOLDER+\"*.doc\"):\n\n # RG numbers for the core asset\n if (\"RG-50.030\" not in file and\n \"RG-50.106\" not in file and\n \"RG-50.549\" not in file):\n \n\n \n # convert file to docx, storing it in an untracked folder called temp\n file_docx = file + 'x'\n command = 'textutil -convert docx ' + file + ' -output ' + INPUT_FOLDER+'temp/'+ file_docx.split('/')[-1]\n call(command, shell=True)\n\n # append to the array\n core_doc_asset.append(file_docx)\n \n\n \n\n # get the units for each file, store them and update tracker\n core_doc_asset=create_dictionary_of_file_list(core_doc_asset)\n \n not_processed=0\n processed_doc=0\n \n # get the units for each file, store them and update tracker \n for mongo_rg in core_doc_asset:\n # get text units for this entry\n processed=[]\n result=[]\n \n for file in core_doc_asset[mongo_rg]:\n \n \n \n units = getTextUnits(INPUT_FOLDER+'temp/'+file.split('/')[-1])\n \n if units:\n #replace white spaces\n for i,element in enumerate(units):\n units[i]['unit']=' '.join(element['unit'].split())\n result.extend(units)\n \n processed.append(True)\n else:\n #check if processed\n processed.append(False)\n\n #set the method used to transform the transcript\n h.update_field(DB, TRACKER, \"rg_number\", mongo_rg, \"method\", \"transcribe_non_core_doc\")\n\n not_processed=not_processed+1\n\n if False in processed:\n\n h.update_field(DB, TRACKER, \"rg_number\", mongo_rg, \"status\", \"Unprocessed\")\n not_processed=not_processed+1\n missing_files.append(' '.join(core_doc_asset[mongo_rg]))\n else:\n # insert units on the output collection\n h.update_field(DB, OUTPUT, \"shelfmark\", 'USHMM '+mongo_rg, \"structured_transcript\", result)\n\n \n # update status on the stracker\n \n h.update_field(DB, TRACKER, \"rg_number\", mongo_rg, \"status\", \"Processed\")\n processed_doc=processed_doc+1\n \n\n #delete the temporary folder\n os.system('rm -r ' + INPUT_FOLDER+'temp')\n\n \n #write the missing files to text file\n file = open(OUTPUT_FOLDER_USHMM_PROCESSING_LOGS+'transcribe_non_core_doc_failed.txt','w')\n file.write('\\n'.join(missing_files))\n\n \n # success\n pprint.pprint(\"Non-core doc files were successfully processed, but there are \" + str(missing_count) + \" missing\")",
"def _copy_from_doc(doc):\n d = {\"has_props\": [], \"origins\": []}\n # Complex function to grab the keys and put them in the root doc\n # if the item is a list, it makes one doc per item with those corresponding keys\n for doc_key in summary_fields:\n sub_doc = doc.get(doc_key, None)\n if isinstance(sub_doc, list) and len(sub_doc) > 0:\n d[\"has_props\"].append(doc_key)\n d[doc_key] = []\n for sub_item in sub_doc:\n temp_doc = {\n copy_key: sub_item[copy_key]\n for copy_key in summary_fields[doc_key]\n if copy_key in sub_item\n }\n d[doc_key].append(temp_doc)\n elif isinstance(sub_doc, dict):\n d[\"has_props\"].append(doc_key)\n if sub_doc.get(\"origins\", None):\n d[\"origins\"].extend(sub_doc[\"origins\"])\n d.update(\n {\n copy_key: sub_doc[copy_key]\n for copy_key in summary_fields[doc_key]\n if copy_key in sub_doc\n }\n )\n return d",
"def appendFeatures(dstFeatures, srcFeatures, col=None):\n assert set(dstFeatures.keys()) == set(srcFeatures.keys())\n for node, features in srcFeatures.iteritems():\n if col is not None:\n dstFeatures[node].append(features[col])\n else:\n for f in features:\n dstFeatures[node].append(f)",
"def ingest_sources(db, sources, ras, decs, references, comments=None, epochs=None,\n equinoxes=None, verbose=False, save_db=False):\n\n n_added = 0\n n_sources = len(sources)\n\n if epochs is None:\n epochs = [None] * n_sources\n if equinoxes is None:\n equinoxes = [None] * n_sources\n if comments is None:\n comments = [None] * n_sources\n\n for i, source in enumerate(sources):\n\n # Construct data to be added\n source_data = [{'source': sources[i],\n 'ra': ras[i],\n 'dec': decs[i],\n 'reference': references[i],\n 'epoch': epochs[i],\n 'equinox': equinoxes[i],\n 'comments': comments[i]}]\n verboseprint(source_data, verbose=verbose)\n\n try:\n db.Sources.insert().execute(source_data)\n n_added += 1\n except sqlalchemy.exc.IntegrityError:\n # try reference without last letter e.g.Smit04 instead of Smit04a\n if source_data[0]['reference'][-1] in ('a', 'b'):\n source_data[0]['reference'] = references[i][:-1]\n try:\n db.Sources.insert().execute(source_data)\n n_added += 1\n except sqlalchemy.exc.IntegrityError:\n raise SimpleError(\"Discovery reference may not exist in the Publications table. \"\n \"Add it with add_publication function. \")\n else:\n raise SimpleError(\"Discovery reference may not exist in the Publications table. \"\n \"Add it with add_publication function. \")\n\n if save_db:\n db.save_database(directory='data/')\n print(n_added, \"sources added to database and saved\")\n else:\n print(n_added, \"sources added to database\")\n\n return",
"def build_or_remove_schema(config):\n\tsbmcollections = config[\"schema\"].keys()\n\tfor sbmcoll in sbmcollections:\n\t\t#if not sbmcoll == \"Thesis\": continue\n\t\tif arg == \"-d\": #deleting\n\t\t\tcollection_id = get_id_of_collection_name(sbmcoll)\n\t\t\tdelete_submission_collection_details(collection_id) #sbmCOLLECTION\n\t\t\tdelete_submission_collection_from_submission_tree(collection_id)#sbmCOLLECTION_sbmCOLLECTION\n\t\t\t\n\t\tif arg == \"-c\": #creating\n\t\t\tid_son = insert_submission_collection(sbmcoll) #sbmCOLLECTION\n\t\t\t## get the maximum catalogue score of the existing collection children:\n\t\t\tmax_child_score = \\\n\t\t\tget_maximum_catalogue_score_of_collection_children_of_submission_collection(0) # 0: highest collection \n\t\t\t## add it to the collection, at a higher score than the others have:\n\t\t\tnew_score = max_child_score + 1\n\t\t\tinsert_collection_child_for_submission_collection(0, id_son, new_score) #sbmCOLLECTION_sbmCOLLECTION\n\t\t\tcollection_id = get_id_of_collection_name(sbmcoll)\n\t\tdoctypes = config[\"schema\"][sbmcoll]\n\t\tfor doctype in doctypes:\n\t\t\tif arg == \"-c\":\n\t\t\t\t## insert the submission-collection/doctype link:\n\t\t\t\t## get the maximum catalogue score of the existing doctype children:\n\t\t\t\tmax_child_score = get_maximum_catalogue_score_of_doctype_children_of_submission_collection(collection_id)\n\t\t\t\t## add it to the new doctype, at a higher score than the others have:\n\t\t\t\tnew_score = max_child_score + 1\n\t\t\t\tinsert_doctype_child_for_submission_collection(collection_id, doctype, new_score) #sbmCOLLECTION_sbmDOCTYPE \n\t\t\telif arg == \"-d\": delete_doctype_children_from_submission_collection(collection_id) #sbmCOLLECTION_sbmDOCTYPE",
"def insert_relations_staging(self):\n\n for year in range(START_YEAR_CREATIVE_WORKS, CURRENT_YEAR, YEARS_RANGE):\n self.load_wikidata(\"movie_roles\", MOVIE_ROLES_BY_YEAR_SPARQL_QUERY, INSERT_MOVIE_ROLE_SQL_QUERY, INSERT_MOVIE_ROLE_MAP_COLUMNS, year, YEARS_RANGE)\n\n self.load_wikidata(\"song_roles\", SONG_ROLES_BY_YEAR_SPARQL_QUERY, INSERT_SONG_ROLE_SQL_QUERY, INSERT_SONG_ROLE_MAP_COLUMNS, year, YEARS_RANGE, True)\n self.load_wikidata(\"tvshow_roles\", TVSHOW_ROLES_SPARQL_QUERY, INSERT_TVSHOW_ROLE_SQL_QUERY,\n INSERT_TVSHOW_ROLE_MAP_COLUMNS)\n self.load_wikidata(\"animatedmovie_roles\", ANIMATEDMOVIE_ROLES_SPARQL_QUERY, INSERT_ANIMATEDMOVIE_ROLE_SQL_QUERY,\n INSERT_ANIMATEDMOVIE_ROLE_MAP_COLUMNS)\n self.load_wikidata(\"videogame_roles\", VIDEOGAME_ROLES_SPARQL_QUERY, INSERT_VIDEOGAME_ROLE_SQL_QUERY, INSERT_VIDEOGAME_ROLE_MAP_COLUMNS)\n self.load_wikidata(\"book_roles\", BOOK_ROLES_SPARQL_QUERY, INSERT_BOOK_ROLE_SQL_QUERY, INSERT_BOOk_ROLE_SQL_QUERY)",
"def unnest_collection(collection, df_list):\n for item in collection['link']['item']:\n if item['class'] == 'dataset':\n df_list.append(Dataset.read(item['href']).write('dataframe'))\n elif item['class'] == 'collection':\n nested_collection = request(item['href'])\n unnest_collection(nested_collection, df_list)",
"async def insert_requirements(conn, mapname):\n select_sql = \"\"\"insert into media_files(path, type, provided) select ?, ?, ? where not exists(select * from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (f\"pics/mapshots/{mapname}\", \"mapshot\", 0, f\"pics/mapshots/{mapname}\"))\n select_sql = \"\"\"insert into requirements(map_id, file_id) select (select map_id from maps where map_path=?), (select file_id from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (mapname, f\"pics/mapshots/{mapname}\"))\n (reqs, sky, texs, exts, linkeds) = await get_required_files(mapname)\n if reqs:\n for req in reqs:\n select_sql = \"\"\"insert into media_files(path, type, provided) select ?, ?, ?\n where not exists(select * from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (req, \"requiredfile\", 0, req))\n select_sql = \"\"\"insert into requirements(map_id, file_id) select (select map_id from maps where map_path=?), (select file_id from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (mapname, req))\n if sky:\n for suffix in [\"bk\", \"dn\", \"ft\", \"lf\", \"rt\", \"up\"]:\n select_sql = \"\"\"insert into media_files(path, type, provided) select ?, ?, ?\n where not exists(select * from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (sky + suffix, \"sky\", 0, sky + suffix))\n select_sql = \"\"\"insert into requirements(map_id, file_id) select (select map_id from maps where map_path=?), (select file_id from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (mapname, sky + suffix))\n\n if texs:\n for req in texs:\n select_sql = \"\"\"insert into media_files(path, type, provided) select ?, ?, ?\n where not exists(select * from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (req, \"texture\", 0, req))\n select_sql = \"\"\"insert into requirements(map_id, file_id) select (select map_id from maps where map_path=?), (select file_id from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (mapname, req))\n if exts:\n for req in exts:\n select_sql = \"\"\"insert into media_files(path, type, provided) select ?, ?, ?\n where not exists(select * from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (req, \"externalfile\", 0, req))\n select_sql = \"\"\"insert into requirements(map_id, file_id) select (select map_id from maps where map_path=?), (select file_id from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (mapname, req))\n if linkeds:\n for req in linkeds:\n select_sql = \"\"\"insert into media_files(path, type, provided) select ?, ?, ?\n where not exists(select * from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (req, \"linkedfile\", 0, req))\n select_sql = \"\"\"insert into requirements(map_id, file_id) select (select map_id from maps where map_path=?), (select file_id from media_files where path=?)\"\"\"\n _ = select(conn, select_sql, (mapname, req))",
"def linear(files):\n return list(map(insert_to_mongo, files))"
] | [
"0.5155826",
"0.5116931",
"0.502896",
"0.48469794",
"0.4804909",
"0.47966293",
"0.47729138",
"0.47717592",
"0.47354752",
"0.4730931",
"0.47188097",
"0.47089943",
"0.4695777",
"0.46924073",
"0.4670455",
"0.4657417",
"0.46162593",
"0.46076247",
"0.45932865",
"0.45638296",
"0.45464498",
"0.45460925",
"0.453677",
"0.4530828",
"0.45303681",
"0.4522521",
"0.4513881",
"0.450216",
"0.4501904",
"0.4495352"
] | 0.7434294 | 0 |
VStream streams vreplication events. | def VStream(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def stream_status_event(self, event):\r\n pass",
"def event_stream(self):\n for message in self.subscribe():\n event = message_to_sse(message[\"data\"])\n yield event",
"def handle_stream_client(self, event):\n try:\n while True:\n client_req = self.receive_streaming_msg()\n self.choose_action(client_req[ZERO], client_req[ONE:], event)\n except socket.error as e:\n print('stream', e)",
"def stream():\n return flask.Response(event_stream(flask.request.access_route[0]),\n mimetype='text/event-stream')",
"def server_streaming(self) -> global___Snippet.ServerStreaming:",
"def onRecv(self, data):\n self.stream += data\n while self.handleStream(): pass",
"def on_connect(self):\n log.info(\"Stream connected\")",
"def on_publish_vertex(self):\n logging.debug(\"Vertex data published\")",
"def client_streaming(self) -> global___Snippet.ClientStreaming:",
"def stream_state_changed(self,state,arg):\n pass",
"def window_updated(self, event):\n log.debug(\"window updated, stream %s\", event.stream_id)\n self.send_data(event.stream_id)",
"def request_received(self, event):\n log.debug(\"request received, stream %s\", event.stream_id)",
"def StartSubscriptions(self):\n rospy.Subscriber('/drivers/dvl', Dvl, self.dvl_callback)\n rospy.Subscriber('/drivers/imu', Imu, self.imu_callback)\n rospy.Subscriber('/reference/depth', Position, self.refDepth_callback)\n rospy.Subscriber('/reference/speed', Speed, self.refSpeed_callback)\n rospy.Subscriber('/reference/rpy', Euler, self.refRpy_callback)\n rospy.Subscriber('/reference/ll', Position, self.refLL_callback)\n rospy.Subscriber('/control/trackers_enabled', Trackers, self.trackersControl_callback)",
"def add_stream_to_event(self,stream):\n assert isinstance(stream,Stream)",
"def data_received(self, event):\n stream_id = event.stream_id\n\n log.debug(\"data received on stream %s: %s...\", stream_id, event.data[:100])\n receive_stream = self.receive_streams.get(stream_id)\n if receive_stream is None:\n try:\n self.conn.reset_stream(stream_id, error_code=ErrorCodes.PROTOCOL_ERROR)\n except StreamClosedError:\n pass\n return\n\n receive_stream.write(event.data)\n self.conn.acknowledge_received_data(event.flow_controlled_length, stream_id)",
"def user_v_server():\r\n\r\n tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n tcpServer.bind((TCP_IP, VANZATOR_PORT))\r\n\r\n tcpServer.listen(1)\r\n (conn, (ip, port)) = tcpServer.accept()\r\n\r\n while True:\r\n data = conn.recv(512)\r\n print(\"Server vanzator a primit:\", data)\r\n MESSAGE = str(ip)\r\n if MESSAGE == 'stop':\r\n break\r\n conn.send(MESSAGE.encode())",
"def video_stream_demo():\n return render_template('video_stream_demo.html')",
"def stream_created(self,stream):\n pass",
"def publish(self, event):\n self.pubsub_router.send(event)",
"def subscribe(self):\n if not self._subscribed and self._connected:\n if ATTR_STREAM_ID not in self.data:\n msg = self._create_message(strings.SUB_MSG)\n self.write(msg)\n else:\n msg = self._create_message(strings.RESUB_MSG)\n self.write(msg)\n self._subscribed = True",
"def streamTest():\n timer = StoreTimer(store, duration=2.0)\n bottle.response.set_header('Content-Type', 'text/event-stream') #text\n bottle.response.set_header('Cache-Control', 'no-cache')\n # Set client-side auto-reconnect timeout, ms.\n yield 'retry: 1000\\n\\n'\n i = 0\n yield 'id: {0}\\n'.format(i)\n i += 1\n yield 'data: START\\n\\n'\n n = 1\n while not timer.expired:\n yield 'id: {0}\\n'.format(i)\n i += 1\n yield 'data: {0}\\n\\n'.format(n)\n n += 1\n yield \"data: END\\n\\n\"",
"def to_event_stream(self, event_stream):\n while self.reading_log:\n event = self.read_event()\n if event is not None:\n event_stream.append(event)",
"def stream_frames(video_capture):",
"def event_publish(self, cmd):\n for sub in self.subscribers:\n sub.event_receive(cmd)",
"def subscribe(receiver):",
"def subscribe(receiver):",
"def subscribe(receiver):",
"def subscribe(observer):",
"def subscribe(observer):",
"def streamer(self):\n retry = 3\n print ('start streamer!')\n while self.container is None and 0 < retry:\n if not self.collect_frames:\n break\n #print (type(self.container))\n retry -= 1\n try:\n self.container = av.open(self.drone.get_video_stream())\n print('success')\n except av.AVError as ave:\n print(ave)\n print('retry...')"
] | [
"0.5862362",
"0.5361396",
"0.5193589",
"0.50663304",
"0.5025312",
"0.49359423",
"0.49321538",
"0.4907434",
"0.49009848",
"0.48569548",
"0.47935286",
"0.478286",
"0.47663593",
"0.47638202",
"0.4749716",
"0.47021312",
"0.47019884",
"0.46913123",
"0.46864375",
"0.46640497",
"0.46458283",
"0.46380752",
"0.46218175",
"0.46034992",
"0.45886788",
"0.45886788",
"0.45886788",
"0.45840412",
"0.45840412",
"0.45666808"
] | 0.5426422 | 1 |
Removes rows which aren't needed in the DF. If a row contains one of the designated symbols it drops them and records them. Returns an Filtered object which contains information about the retained and removed rows. | def filter_unneeded_rows(data: pd.DataFrame) -> FilteredData:
allowed_values = ["BUY", "SELL"]
correct_rows = data["Action"].isin(allowed_values)
num_of_ok_rows = correct_rows.sum()
if num_of_ok_rows == len(data):
return FilteredData(data, {})
legal_rows = data.loc[correct_rows, :]
illegal_rows = data.loc[~correct_rows, :]
unique_illegal = illegal_rows["Action"].unique()
uniques = {}
for unique in unique_illegal:
values = data.loc[data["Action"] == unique, :]
uniques[unique] = (len(values), values.index.to_numpy() + 1)
return FilteredData(legal_rows, uniques) | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def trimDf(df):\n cols = set(df.columns)\n\n cols.remove('exclamationCount') # bug in our feature extraction code\n cols.remove('price') # considered only free apps\n cols.remove('appName') # removing appNames\n\n # return df[list(cols)]\n\n\n\n return df[list(('revSent', 'appLabel'))]",
"def filter_data(self):\n self.df = self.df[HeatStrokeDataFiller.important_features]",
"def filter(self):\n self.data = self.data.loc[~self.data.isnull().any(1),:]",
"def remove(df, pattern):\n return df[~df.index.isin(df.query(pattern).index)]",
"def drop_illogical(df,var1,var2):\r\n #Mask the illogical entries\r\n mask = df[var1]>df[var2]\r\n #Record the number of entries\r\n NumRecords = df.shape[0]\r\n #drop the illogical entries\r\n df = df[df.keys()][~mask]\r\n #Notify the user how many records were dropped\r\n print('{} records dropped because {} is greater than {}'.format(NumRecords-df.shape[0],var1,var2))\r\n \r\n return df",
"def clean(df):",
"def filter_rows(self, **kwds):\n if kwds:\n normalize = lambda v: (v,) if isinstance(v, str) else v\n kwds = dict((k, normalize(v)) for k, v in kwds.items())\n matches_kwds = lambda row: all(row[k] in v for k, v in kwds.items())\n return filter(matches_kwds, self.__iter__())\n return self.__iter__()",
"def discard(self):\n for f in self.featureNames:\n self.data = self.data[self.data[:,self._getFIdx(f)] != '-99999']\n return",
"def delete_row(self):\n return exclusions.closed()",
"def delete(self, predicate=lambda row: True):\n self.rows = [row for row in self.rows if not predicate(row)]",
"def strip_ds(ds):\n if 'brain' in np.unique(ds.sa.all_ROIs):\n ds = ds[(ds.sa.all_ROIs != 'brain'), :]\n print('excluded the rest of the brain from the dataset')\n if 'overlap' in np.unique(ds.sa.all_ROIs):\n ds = ds[(ds.sa.all_ROIs != 'overlap'), :]\n print('excluded overlap from the dataset')\n return ds",
"def unique_filter(rows):\n old_row = {}\n row = None\n for row in rows:\n row_data = dict(row)\n try:\n del row_data['_id']\n del row_data['das']\n del row_data['das_id']\n del row_data['cache_id']\n except:\n pass\n old_data = dict(old_row)\n try:\n del old_data['_id']\n del old_data['das']\n del old_data['das_id']\n del old_data['cache_id']\n except:\n pass\n if row_data == old_data:\n continue\n if old_row:\n yield old_row\n old_row = row\n yield row",
"def exclude_duplicates(self):\n from axs.catalog import AxsCatalog\n return self.filter(self._df[AxsCatalog.DUP_COLNAME] == 0)",
"def removeLegacy(self, path=None):\n\n df = pd.read_csv(path, compression='gzip')\n print(df.shape)\n gamelist = pd.read_csv('Resources/Genres.csv.gz', usecols=['appid'])\n gamelist = pd.DataFrame(gamelist.appid.unique(), columns=['appid'])\n print(gamelist)\n filter_df = pd.merge(df, gamelist, on='appid', how='inner')\n filter_df = filter_df.dropna()\n filter_df = filter_df.sort_values(['steamid', 'appid'], ascending=[True, True])\n print('done')\n print(filter_df.shape)\n print(filter_df)\n print(np.setdiff1d(df['appid'].unique(), filter_df['appid'].unique()))\n filter_df.to_csv(path, compression='gzip', columns=['steamid', 'appid', 'rating'], index=None)",
"def remove_other_elements(data):\n charset = ['F','l','B','r','I','i','M','g','L','b','a','e','K','V','d','R','Z','G','A','Y','u']\n x = []\n for i in range(data.shape[0]):\n for j in range(len(data.iloc[i,1])):\n if data.iloc[i,1][j] in charset:\n x.append(i)\n break\n df = data[(True^data['Index'].isin(x))]\n df.reset_index(drop=True, inplace=True)\n return df",
"def remove(df,column_to_filter,standard_deviations=3):\n import math\n #This function will flatten the row of the dataframe\n def flatten_column(row):\n return tuple(float(x) for x in row)\n stats = df.select(column_to_filter).rdd.flatMap(flatten_column).stats()\n mean = stats.mean()\n variance = stats.variance()\n stddev = math.sqrt(variance)\n stddev_threshhold = stddev*standard_deviations\n print(stddev_threshhold)\n from pyspark.sql.functions import lit\n df = df.where(\"abs({column_to_filter} - {mean}) > {stddev_threshhold}\"\\\n .format(column_to_filter=column_to_filter,mean=mean,stddev_threshhold=stddev_threshhold))\n return df",
"def remove_closed_store(data: pyspark.sql.dataframe.DataFrame) -> pyspark.sql.dataframe.DataFrame:\n closed_store = pd.read_csv('../data/closedStore/Closed stores list.csv')\n closed_store_list = closed_store['Store'].unique()\n \n for store in closed_store_list:\n data = data[data.Store !=store] # remove the colsed store\n return data",
"def filter_data(self):\n self.data = filter_pandas(self.data, self.filters)",
"def filter_dtc_data(orig_df,geneNames):\n # filter criteria:\n # gene_names == JAK1 | JAK2 | JAK3\n # InChi key not missing\n # standard_type IC50\n # units NM\n # standard_relation mappable to =, < or >\n # wildtype_or_mutant != 'mutated'\n # valid SMILES\n # maps to valid RDKit base SMILES\n # standard_value not missing\n # pIC50 > 3\n #--------------------------------------------------\n # Filter dataset on existing columns\n dset_df = orig_df[orig_df.gene_names.isin(geneNames) &\n ~(orig_df.standard_inchi_key.isna()) &\n (orig_df.standard_type == 'IC50') &\n (orig_df.standard_units == 'NM') &\n ~orig_df.standard_value.isna() &\n ~orig_df.compound_id.isna() &\n (orig_df.wildtype_or_mutant != 'mutated') ]\n return dset_df",
"def delete(self, predicate: WhereClause = lambda row: True) -> None:\n self.rows = [row for row in self.rows if not predicate(row)]",
"def clean(self):\n self.df = _data.prune(self.df, [REGEX_PATTERN_GCI, REGEX_PATTERN_DB_ID])\n self.df, _ = _data.remove_totally_failed_tests(self.df)\n self.is_cleaned = True",
"def drop_transactions(df, station, access_point = None):\n\n if access_point is not None:\n station_name = df.nombreestacion.contains(station)\n entrance = df.nombreaccesoestacion.contains(access_point)\n filters = station_name & entrance\n else:\n filters = df.nombreestacion.contains(station)\n return df.filter(~filters)",
"def remove_rows_without_feature(df, feature):\n return df[np.isfinite(df[feature])]",
"def _remove_non_informative_rows(self, df, threshold):\n df_tmp = pd.DataFrame()\n n_features = len(df.columns)\n # calculating ratio of rows that have more than \"ratio\" missing values\n df_tmp['ratio'] = df.apply(lambda row: row.isnull().sum()/n_features, axis='columns')\n\n # kick too noisy rows\n return df[df_tmp['ratio'] <= threshold]",
"def EliminateRows(self, rows):\n return _hypre.HypreParMatrix_EliminateRows(self, rows)",
"def filterRows(function, rows):\n return [y for y in rows if function(y)]",
"def filter_record(self, record):\n nloc = record.seq.find('N')\n if nloc == -1:\n return record\n elif self.action == 'truncate':\n return record[:nloc]\n elif self.action == 'drop':\n raise FailedFilter()\n else:\n assert False",
"def remove_reserved_keys(df, exclude=[]):\n reserved_keys = __column_intersect(\n df, BAMBOO_RESERVED_KEYS).difference(set(exclude))\n\n return df.drop(reserved_keys, axis=1)",
"def filter(self, alias, condition, inplace=False):\n data = self._data.copy()\n data.index = pd.Index(list(range(0, len(data.index))))\n filter_idx, _ = get_logic_index(pd.Series(data.index), condition, data)\n filtered_data = data.iloc[filter_idx, :]\n if inplace:\n self.filtered = alias\n self._data = filtered_data\n else:\n new_ds = self.clone()\n new_ds._data = filtered_data\n new_ds.filtered = alias\n return new_ds",
"def _clean_dataset(df: pd.DataFrame) -> pd.DataFrame:\n df = df.loc[:, ~df.columns.str.contains(\"^Unnamed\")]\n df = df.dropna()\n return df"
] | [
"0.5987847",
"0.5943072",
"0.58474314",
"0.57139724",
"0.5702526",
"0.56567687",
"0.5635453",
"0.5586914",
"0.5586264",
"0.55834323",
"0.5563579",
"0.55631554",
"0.5544793",
"0.5538713",
"0.54920566",
"0.54906213",
"0.54856443",
"0.5456401",
"0.5443878",
"0.5406942",
"0.53937954",
"0.5385565",
"0.53664106",
"0.5348836",
"0.53483623",
"0.5343835",
"0.53187996",
"0.53184205",
"0.53045106",
"0.5299329"
] | 0.59884405 | 0 |
Lists all the uploads for a particular catalog. | def list_uploads_for_catalog_v0(self, catalog_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, ListUploadsResponse_59fc7728, Error_d660d58]
operation_name = "list_uploads_for_catalog_v0"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'catalog_id' is set
if ('catalog_id' not in params) or (params['catalog_id'] is None):
raise ValueError(
"Missing the required parameter `catalog_id` when calling `" + operation_name + "`")
resource_path = '/v0/catalogs/{catalogId}/uploads'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'catalog_id' in params:
path_params['catalogId'] = params['catalog_id']
query_params = [] # type: List
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.catalog.upload.list_uploads_response.ListUploadsResponse", status_code=200, message="Successful operation."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v0.catalog.upload.list_uploads_response.ListUploadsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list_uploads(arn=None, nextToken=None):\n pass",
"def upload_index(self):\n return self.render(\"cadmin/upload.html\", connector=self.connector)",
"def uploads(self):\r\n return u.Uploads(self)",
"def list_multipart_uploads(Bucket=None, Delimiter=None, EncodingType=None, KeyMarker=None, MaxUploads=None, Prefix=None, UploadIdMarker=None):\n pass",
"def get_all_multipart_uploads(self, headers=None, **params):\r\n return self._get_all([('Upload', MultiPartUpload)],\r\n 'uploads', headers, **params)",
"def list_(args):\n osf = _setup_osf(args)\n\n project = osf.project(args.project)\n\n for store in project.storages:\n prefix = store.name\n for file_ in store.files:\n path = file_.path\n if path.startswith('/'):\n path = path[1:]\n\n print(os.path.join(prefix, path))",
"def uploaded(self):\n cursor = self.cursor\n cursor.execute(\n \"SELECT * from songs WHERE uploaded_by = %s\",\n (cherrypy.session['_username'],))\n songs = cursor.fetchmany(10)\n return {'songs':songs}",
"def files_storage_list(self, prefix='pipeline/', print_paths=False):\n\n return self.backend.files_storage_list(prefix=prefix, print_paths=print_paths)",
"def ls(self):\n files = self.drive.files().list().execute().get(\"files\", [])\n for f in files:\n print(f[\"name\"], f[\"mimeType\"])",
"def upload(all_files, session):\n remote_directory = unique_path('cli-import')\n log.info('uploading files to %s' % remote_directory)\n\n for filename in all_files:\n callback = _progress_callback\n log.info(\"Uploading %s\" % filename)\n session.uploadWrapper(filename, remote_directory, callback=callback)\n if callback:\n print('')\n return remote_directory",
"def test_show_uploads(api):\n # checking that we have empty list if we haven't uploaded any files yet\n assert isinstance(api.show_uploads(), list)\n\n # upload the file\n uploaded_file = api.upload(\n tag='test_file',\n expiry='2d',\n path='tests/test_file.txt'\n )\n\n # check that we have our uploaded file in file_obj_list\n assert 1, len(api.show_upload())\n print(uploaded_file)\n print(api.show_uploads())\n\n # upload one more file for testing the key and tag searching\n another_uploaded_file = api.upload(\n tag='another_tag',\n expiry='1d',\n path='tests/test_file.txt'\n )\n\n # check that sorting by tags works\n assert api.show_uploads(tag='test_file')[0] == uploaded_file\n\n # check that sorting by keys works\n assert api.show_uploads(key=uploaded_file.key)[0] == uploaded_file\n\n # check that sorting by tag and key works\n assert api.show_uploads(\n tag='test_file', key=uploaded_file.key\n )[0] == uploaded_file\n\n uploads = api.show_uploads()\n\n # check that show uploads returns us our 2 uploaded files\n assert 2, len(uploads)\n\n # check that all uploaded files are in 'uploads' list\n assert another_uploaded_file and uploaded_file in uploads",
"def get(self):\n\n results_query = FileMetadata.all()\n results_query.ancestor(_PARENT)\n\n items = [result for result in results_query]\n length = len(items)\n\n upload_url = blobstore.create_upload_url('/upload')\n\n self.response.out.write(self.template_env.get_template(\n \"admin.html\").render(\n {\"username\": 'admin',\n \"uploaded_items\": items,\n \"uploaded_length\": length,\n \"upload_url\": upload_url}))",
"def listFiles(self):\n pass",
"def getcatalogs():\n \n # default path for the gthumb catalogs of the logged in user\n gpath = os.environ['HOME'] + \"/.local/share/gthumb/catalogs\"\n\n cats = [] \n cat_list = [] \n try:\n # dir_list has all files and directories in path\n # directories are WITHOUT ending '/'\n dir_list = os.listdir(gpath)\n except:\n # path may not be a directory or permission error\n print \"ERROR: in getcatalogs, gpath:\", gpath\n return []\n \n # get only the directories \n for line in dir_list:\n file = gpath + \"/\" + line\n #print file \n if os.path.isdir(file):\n cats.append(file)\n else: \n # not a directory; ignore \n #print \"not a directory:\", file \n pass\n\n # now get each catalog file from each directory\n for cat in cats:\n try:\n # dir_list has all files and directories in path\n # any directory is WITHOUT ending '/'\n dir_list = os.listdir(cat)\n except:\n # path may not be a directory or permission error\n print \"ERROR: in getcatalogs, cat:\", cat\n return []\n \n for line in dir_list:\n file = cat + \"/\" + line\n #print os.path.splitext(file)[1][1:]\n # append file only if it has catalog extension\n if os.path.splitext(file)[1][1:] == \"catalog\":\n cat_list.append(file)\n \n cat_list.sort() \n\n if random_mode:\n random.shuffle(cat_list)\n \n return cat_list",
"def files(self, **kwargs) -> \"FileMetadataList\":\n return self._cognite_client.files.list(asset_ids=[self.id], **kwargs)",
"def get_catalog_items(id):\n\n username = login_session.get('username', None)\n catalogs = session.query(Catalog).all()\n selected_catalog = session.query(Catalog).filter_by(id=id).one()\n items = selected_catalog.items\n catalogs_display = [\n {\n 'id': catalog.id,\n 'name': catalog.name\n } for catalog in catalogs]\n items_display = [{'id': item.id, 'title': item.title} for item in items]\n items_summary = '{0} Items ({1} items)'.format(\n selected_catalog.name,\n len(items_display))\n return render_template(\n 'home.html',\n catalogs_display=catalogs_display,\n items_display=items_display,\n items_summary=items_summary,\n username=username)",
"def get_content_upload_by_id_v1(self, catalog_id, upload_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, GetContentUploadResponse_b9580f92]\n operation_name = \"get_content_upload_by_id_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'upload_id' is set\n if ('upload_id' not in params) or (params['upload_id'] is None):\n raise ValueError(\n \"Missing the required parameter `upload_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/catalogs/{catalogId}/uploads/{uploadId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n if 'upload_id' in params:\n path_params['uploadId'] = params['upload_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.catalog.upload.get_content_upload_response.GetContentUploadResponse\", status_code=200, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.catalog.upload.get_content_upload_response.GetContentUploadResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def list_files():\n files = []\n for filename in os.listdir(UPLOAD_DIRECTORY):\n path = os.path.join(UPLOAD_DIRECTORY, filename)\n if os.path.isfile(path):\n files.append(filename)\n return jsonify(files)",
"def catalogs(env):\n envs = environments()\n check_env(env, envs)\n\n if app.config['ENABLE_CATALOG']:\n nodenames = []\n catalog_list = []\n query = AndOperator()\n\n if env != '*':\n query.add(EqualsOperator(\"catalog_environment\", env))\n\n query.add(NullOperator(\"catalog_timestamp\", False))\n\n order_by_str = '[{\"field\": \"certname\", \"order\": \"asc\"}]'\n nodes = get_or_abort(puppetdb.nodes,\n query=query,\n with_status=False,\n order_by=order_by_str)\n nodes, temp = tee(nodes)\n\n for node in temp:\n nodenames.append(node.name)\n\n for node in nodes:\n table_row = {\n 'name': node.name,\n 'catalog_timestamp': node.catalog_timestamp\n }\n\n if len(nodenames) > 1:\n form = CatalogForm()\n\n form.compare.data = node.name\n form.against.choices = [(x, x) for x in nodenames\n if x != node.name]\n table_row['form'] = form\n else:\n table_row['form'] = None\n\n catalog_list.append(table_row)\n\n return render_template(\n 'catalogs.html',\n nodes=catalog_list,\n envs=envs,\n current_env=env)\n else:\n log.warn('Access to catalog interface disabled by administrator')\n abort(403)",
"def list_files():\n files = []\n for filename in os.listdir(UPLOAD_FOLDER):\n path = os.path.join(UPLOAD_FOLDER, filename)\n if os.path.isfile(path):\n files.append(filename)\n return jsonify({'List of Files: ': files})",
"def list_all_files(self):\n\n results = self.drive_service.files().list(\n pageSize=10, fields=\"nextPageToken, files(id, name)\").execute()\n items = results.get('files', [])\n if not items:\n logger.info('No files found.')\n else:\n logger.info('Files:')\n for item in items:\n logger.info(u'{0} ({1})'.format(item['name'], item['id']))",
"async def list(self, request):\n\n userid = await authenticated_userid(request)\n project = await request.app.context_project(request, userid)\n\n request['slog'].debug('Camera list requested')\n\n response_js = {\n 'camera_files': await Camera.list(request, userid=userid, project_id=project.project_id)\n }\n\n return web.json_response(response_js)",
"def uploads(self):\n return SpaceUploadsProxy(self._client, self.id)",
"def printUploads(self):\n if self.uploads != []:\n sys.stderr.write(\"\\n+ \" + _(\"Upload Scripts\") + \":\\n\")\n for up in self.uploads:\n print(up)",
"def index():\n print 'Loading Index'\n\n user_upload_folder = os.path.join(app.config['UPLOAD_FOLDER'], str(session['user_id']))\n\n upload_list = ['No Uploads']\n if os.path.isdir(user_upload_folder):\n upload_list = [f for f in os.listdir(user_upload_folder) if f.endswith('.dvw')]\n\n return render_template('index.html', result_dict={'uploads': upload_list})",
"def upload_catalog(self, catalog: Catalog) -> None:\n self._status.check_authority_for_draft()\n\n put_data: Dict[str, Any] = {\"catalog\": catalog.dumps()}\n if not put_data:\n raise TypeError(\"Empty catalog\")\n put_data.update(self._status.get_status_info())\n\n self._client.open_api_do(\"PUT\", \"labels/catalogs\", self.dataset_id, json=put_data)",
"def upload():\r\n\r\n if not os.path.isdir(TO_SEGMENT):\r\n os.mkdir(TO_SEGMENT)\r\n else:\r\n print(\"could not create upload directory: {}\".format(TO_SEGMENT))\r\n print(request.files.getlist(\"file\"))\r\n\r\n for upload in request.files.getlist(\"file\"):\r\n filename = upload.filename\r\n destination = \"/\".join([TO_SEGMENT, filename])\r\n upload.save(destination)\r\n\r\n return redirect(url_for('get_gallery'))",
"def import_list(request):\r\n import_list = ImportQueueMgr.get_list()\r\n ret = {\r\n 'count': len(import_list),\r\n 'imports': [dict(h) for h in import_list],\r\n }\r\n return _api_response(request, ret)",
"def index(request):\n\n #Collect all photos owned by the user and not associated with albums for display\n photos = Photo.objects.filter(owner = request.user, album_id=None)\n\n #Collect all albums owned by the user for display\n albums = Album.objects.filter(owner = request.user)\n\n #Form to upload multiple images extends Djangos form.ImageField()\n #Fields taken 'file' (image)\n form = UploadFileForm()\n\n #Form to upload album\n #Fields taken are 'title'(charfield)\n formAlbum = AlbumForm()\n return render_to_response('photos/index.html',\n {\n 'form': form,\n 'formAlbum': formAlbum,\n 'photos': photos,\n 'albums':albums,\n },\n context_instance=RequestContext(request))",
"def upload(label):\n filekit = current_app.filekits.get(label)\n if filekit is None:\n abort(404)\n _files = []\n for image in request.files.getlist('files'):\n fkit = filekit.save(image)\n fkit_dict = fkit.to_dict()\n fkit_dict['original'] = fkit.url\n fkit_dict['name'] = fkit.filename\n _files.append(fkit_dict)\n return jsonify({'files': _files})"
] | [
"0.60803103",
"0.5518015",
"0.54515773",
"0.53923315",
"0.53463054",
"0.5214537",
"0.52021486",
"0.51877195",
"0.51299816",
"0.51162803",
"0.51151466",
"0.5109009",
"0.5061079",
"0.5020963",
"0.5012223",
"0.5004669",
"0.49983722",
"0.49931318",
"0.4979966",
"0.49755847",
"0.49690202",
"0.49437377",
"0.4937565",
"0.49036786",
"0.4875252",
"0.48248988",
"0.48125494",
"0.4802392",
"0.4786604",
"0.47790837"
] | 0.66676104 | 0 |
Lists catalogs associated with a vendor. | def list_catalogs_for_vendor_v0(self, vendor_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, ListCatalogsResponse_3dd2a983, BadRequestError_a8ac8b44, Error_d660d58]
operation_name = "list_catalogs_for_vendor_v0"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'vendor_id' is set
if ('vendor_id' not in params) or (params['vendor_id'] is None):
raise ValueError(
"Missing the required parameter `vendor_id` when calling `" + operation_name + "`")
resource_path = '/v0/catalogs'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'vendor_id' in params:
query_params.append(('vendorId', params['vendor_id']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.catalog.list_catalogs_response.ListCatalogsResponse", status_code=200, message="Successful operation."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v0.catalog.list_catalogs_response.ListCatalogsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def show_catalogue(self):\n\n data = cur.execute(\"\"\"SELECT productid, productname, unitcost, stock, location \n FROM catalogue WHERE vendorname = ?\"\"\", (self.vendorname,)).fetchall()\n print(tabulate(data, headers=[\"Product ID\", \"Name\", \"Unit Cost\", \"Stock\", \"Location\"]))",
"def catalogs(env):\n envs = environments()\n check_env(env, envs)\n\n if app.config['ENABLE_CATALOG']:\n nodenames = []\n catalog_list = []\n query = AndOperator()\n\n if env != '*':\n query.add(EqualsOperator(\"catalog_environment\", env))\n\n query.add(NullOperator(\"catalog_timestamp\", False))\n\n order_by_str = '[{\"field\": \"certname\", \"order\": \"asc\"}]'\n nodes = get_or_abort(puppetdb.nodes,\n query=query,\n with_status=False,\n order_by=order_by_str)\n nodes, temp = tee(nodes)\n\n for node in temp:\n nodenames.append(node.name)\n\n for node in nodes:\n table_row = {\n 'name': node.name,\n 'catalog_timestamp': node.catalog_timestamp\n }\n\n if len(nodenames) > 1:\n form = CatalogForm()\n\n form.compare.data = node.name\n form.against.choices = [(x, x) for x in nodenames\n if x != node.name]\n table_row['form'] = form\n else:\n table_row['form'] = None\n\n catalog_list.append(table_row)\n\n return render_template(\n 'catalogs.html',\n nodes=catalog_list,\n envs=envs,\n current_env=env)\n else:\n log.warn('Access to catalog interface disabled by administrator')\n abort(403)",
"def do_command(self, args):\n vendorops = dbops.Vendors()\n listing = vendorops.list(args)\n ordering = ['vendor_name']\n do_list(listing, ordering)",
"def list_catalogs(self):\n return self._json_object_field_to_list(\n self._get_catalogs_json(), self.__MISSION_STRING)",
"def getCatalogs():",
"def list_interaction_model_catalogs_v1(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, ListCatalogResponse_bc059ec9]\n operation_name = \"list_interaction_model_catalogs_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.list_catalog_response.ListCatalogResponse\", status_code=200, message=\"Returns list of catalogs for the vendor.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no catalog defined for the catalogId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.list_catalog_response.ListCatalogResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_catalog(self):\n\n rep = req.get_json(self.CATALOG)\n repo_list = rep[\"repositories\"]\n\n for repo in repo_list:\n self.list.append(Repository(repo))\n\n return self.list",
"def get_vendors_and_products_seen(cls, cb):\n url = \"/device_control/v3/orgs/{0}/products\".format(cb.credentials.org_key)\n resp = cb.get_object(url)\n return resp.get(\"results\", [])",
"def get_vendor_list_v1(self, **kwargs):\n # type: (**Any) -> Union[ApiResponse, object, Error_fbe913d9, Vendors_f5f1b90b]\n operation_name = \"get_vendor_list_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n\n resource_path = '/v1/vendors'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.vendor_management.vendors.Vendors\", status_code=200, message=\"Return vendor information on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.vendor_management.vendors.Vendors\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_catalogs(self):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bins_template\n catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs()\n cat_list = []\n for cat in catalogs:\n cat_list.append(Catalog(self._provider_manager, cat, self._runtime, self._proxy))\n return CatalogList(cat_list)",
"def list_detail_catalog(self, catalog_name):\n # list catalog\n self._list_catalog(catalog_name)\n # detail catalog\n self._details_catalog(catalog_name)",
"def catalogs(self):\n return sorted(self._catalog_comp_info_dicts.keys())",
"def test_get_hyperflex_app_catalog_list(self):\n pass",
"def get(self):\n return GenericGet().get_catalogs()",
"def get_catalogs_by_provider(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bins_by_provider\n catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs_by_provider(*args, **kwargs)\n cat_list = []\n for cat in catalogs:\n cat_list.append(Catalog(self._provider_manager, cat, self._runtime, self._proxy))\n return CatalogList(cat_list)",
"def get_catalogs_by_genus_type(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bins_by_genus_type\n catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs_by_genus_type(*args, **kwargs)\n cat_list = []\n for cat in catalogs:\n cat_list.append(Catalog(self._provider_manager, cat, self._runtime, self._proxy))\n return CatalogList(cat_list)",
"def list(logger, client):\n logger.info('Retrieving Cloudify License')\n license = client.license.list()\n print_data(LICENSE_COLUMN, license, 'Cloudify License')",
"def test_listVendorWithNoParams(self):\r\n result = self.client.listVendors({'i_customer': 1})\r\n assert result['result']=='OK'",
"def get_vendors(self, count: int = 10) -> list:\n return list(itertools.islice(self.client.vendors.get_all_generator(), count))",
"def fetch_account_catalogs(account:str):\n for config in accounts:\n if account in config['streamers']:\n return config['catalogs']\n return",
"def show_vendor_product():\n vendor = input(\"Enter the Vendor: \")\n product = input(\"Enter the product: \")\n filter_string = input(\"Enter Optional Search string (i.e. HTTP): \")\n logger.debug(\"Searching: {} from {} -- Filter = {}\".format(product, vendor, filter_string))\n search_url = \"http://cve.circl.lu/api/search/{}/{}\".format(vendor, product)\n req = call_api(search_url)\n if not req:\n logger.debug(\"something no workie with the vendor product call\")\n else:\n print(\"Searching: {} from {} -- Filter = {}\".format(product, vendor, filter_string))\n for item in req:\n if filter_string != '' or not filter_string:\n if filter_string in item['summary']:\n print(\"\\nSummary: \" + item['summary'])\n print(\"CVE: \" + item['id'])\n print(\"CVSS: \" + str(item['cvss']))\n else:\n print(\"\\nSummary: \" + item['summary'])\n print(\"CVE: \" + item['id'])\n print(\"CVSS: \" + str(item['cvss']))\n menu()",
"def search_catalog(self, query):\n scope = datacatalog.SearchCatalogRequest.Scope()\n scope.include_project_ids.append(self.__project_id)\n\n request = datacatalog.SearchCatalogRequest()\n request.scope = scope\n request.query = query\n request.page_size = 1000\n\n return [\n result for result in self.__datacatalog.search_catalog(request)\n ]",
"def get_items_for_catalog(catalog_id):\n pass",
"def get_catalog_items(id):\n\n username = login_session.get('username', None)\n catalogs = session.query(Catalog).all()\n selected_catalog = session.query(Catalog).filter_by(id=id).one()\n items = selected_catalog.items\n catalogs_display = [\n {\n 'id': catalog.id,\n 'name': catalog.name\n } for catalog in catalogs]\n items_display = [{'id': item.id, 'title': item.title} for item in items]\n items_summary = '{0} Items ({1} items)'.format(\n selected_catalog.name,\n len(items_display))\n return render_template(\n 'home.html',\n catalogs_display=catalogs_display,\n items_display=items_display,\n items_summary=items_summary,\n username=username)",
"def get_catalog():\n return jsonify(getCatalog())",
"def checkCatalogs():\n url = CHECKBASE % 'catalogs'\n catalogs = []\n try:\n fh = getURLHandle(url)\n #fh = urllib2.urlopen(url)\n data = fh.read()\n dom = minidom.parseString(data)\n fh.close()\n catalog_elements = dom.getElementsByTagName('Catalog')\n for catel in catalog_elements:\n if catel.firstChild is None:\n continue\n catalog = catel.firstChild.data.strip()\n if len(catalog):\n catalogs.append(str(catalog))\n except:\n raise Exception,\"Could not open %s to search for list of catalogs\" % url\n return catalogs",
"def list_customers():\n customers = db_helper.get_all_customers()\n return jsonify({\"customers\": customers})",
"def list_licenses(licenses):\n #print(\"Available licenses:\\n\")\n for license in licenses:\n print(\"{0}: {name} {ver} ({url})\".format(license, **licenses[license]))",
"def show_all_customers():\n return cr.show_all_customers()",
"def catalog():\n session['target'] = \"/\"\n sqlsession = SQLSESSION()\n items = sqlsession.query(Item, Category)\\\n .join(Category).order_by(Item.create_date).limit(10)\n categories = sqlsession.query(Category).all()\n return render_template(\"catalog.html\",\n items=items,\n categories=categories,\n item_title=\"Latest Items\")"
] | [
"0.6425961",
"0.62713766",
"0.62005067",
"0.61386716",
"0.6064944",
"0.599095",
"0.5985109",
"0.59512717",
"0.5854509",
"0.58000416",
"0.57824093",
"0.573778",
"0.5698321",
"0.56862247",
"0.5647046",
"0.5640386",
"0.5627115",
"0.562495",
"0.5621989",
"0.56063086",
"0.55837905",
"0.5555898",
"0.5410117",
"0.54098076",
"0.539899",
"0.53964186",
"0.5390039",
"0.53361726",
"0.5331113",
"0.53026116"
] | 0.6875441 | 0 |
Creates a new catalog based on information provided in the request. | def create_catalog_v0(self, create_catalog_request, **kwargs):
# type: (CreateCatalogRequest_f3cdf8bb, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, CatalogDetails_912693fa, Error_d660d58]
operation_name = "create_catalog_v0"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'create_catalog_request' is set
if ('create_catalog_request' not in params) or (params['create_catalog_request'] is None):
raise ValueError(
"Missing the required parameter `create_catalog_request` when calling `" + operation_name + "`")
resource_path = '/v0/catalogs'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_catalog_request' in params:
body_params = params['create_catalog_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.catalog.catalog_details.CatalogDetails", status_code=201, message="Catalog created."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v0.catalog.catalog_details.CatalogDetails")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def catalog_create(self, args):\n try:\n if args.id and self.server.connect_ermrest(args.id).exists():\n print(\"Catalog already exists\")\n return\n owner = args.owner if args.owner else None\n catalog = self.server.create_ermrest_catalog(args.id, owner)\n if args.auto_configure:\n model = catalog.getCatalogModel()\n model.configure_baseline_catalog(**args.configure_args)\n if not args.quiet:\n print(\"Created new catalog %s with the following default configuration:\\n\" % catalog.catalog_id)\n pp(catalog.get('/').json())\n except HTTPError as e:\n if e.response.status_code == requests.codes.not_found:\n raise ResourceException('Catalog not found', e)\n elif e.response.status_code == requests.codes.conflict:\n raise ResourceException(\"Catalog already exists\", e)\n else:\n raise e",
"def create_catalog(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinAdminSession.create_bin\n return Catalog(\n self._provider_manager,\n self._get_provider_session('catalog_admin_session').create_catalog(*args, **kwargs),\n self._runtime,\n self._proxy)",
"def CreateFromCatalog(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def POST(self, uri='catalog'):\n # content negotiation\n content_type = negotiated_content_type(self.supported_types, self.default_content_type)\n\n # registry acl enforcement\n allowed = web.ctx.ermrest_registry.can_create(web.ctx.webauthn2_context.attributes)\n if not allowed:\n raise rest.Forbidden(uri)\n\n # optional input\n docstr = web.ctx.env['wsgi.input'].read().decode().strip()\n if docstr:\n try:\n doc = json.loads(docstr)\n except:\n raise exception.rest.BadRequest('Could not deserialize JSON input.')\n else:\n doc = {}\n\n owner = doc.get('owner')\n annotations = doc.get('annotations')\n\n # create the catalog instance\n catalog_id = web.ctx.ermrest_registry.claim_id(id=doc.get('id'), id_owner=owner)\n catalog = web.ctx.ermrest_catalog_factory.create(catalog_id)\n\n # initialize the catalog instance\n pc = sanepg2.PooledConnection(catalog.dsn)\n try:\n next(pc.perform(lambda conn, cur: catalog.init_meta(conn, cur, owner=owner, annotations=annotations)))\n finally:\n pc.final()\n\n # register the catalog descriptor\n entry = web.ctx.ermrest_registry.register(catalog_id, descriptor=catalog.descriptor)\n\n web.header('Content-Type', content_type)\n web.ctx.ermrest_request_content_type = content_type\n\n # set location header and status\n location = '/ermrest/catalog/%s' % catalog_id\n web.header('Location', location)\n web.ctx.status = '201 Created'\n\n if content_type == _text_plain:\n return str(catalog_id)\n else:\n assert content_type == _application_json\n return json.dumps(dict(id=catalog_id))",
"def initCatalog():\n catalog = model.newCatalog()\n return catalog",
"def initCatalog():\n catalog = model.newCatalog()\n return catalog",
"def initCatalog():\n catalog = model.newCatalog()\n return catalog",
"def build_catalog_info(self, catalog_info):\n cat = SourceFactory.build_catalog(**catalog_info)\n catalog_info['catalog'] = cat\n # catalog_info['catalog_table'] =\n # Table.read(catalog_info['catalog_file'])\n catalog_info['catalog_table'] = cat.table\n catalog_info['roi_model'] =\\\n SourceFactory.make_fermipy_roi_model_from_catalogs([cat])\n catalog_info['srcmdl_name'] =\\\n self._name_factory.srcmdl_xml(sourcekey=catalog_info['catalog_name'])\n return CatalogInfo(**catalog_info)",
"def newCatalog():\n catalog = {'videosContext': None,\n 'caraContenido': None,\n 'musicalGenero': None,\n 'fechaMusica': None}\n\n catalog['videosContext'] = lt.newList('ARRAY_LIST')\n catalog['caraContenido'] = mp.newMap(30,\n maptype='PROBING',\n loadfactor=0.4)\n catalog['musicaGenero'] = mp.newMap(30,\n maptype='PROBING',\n loadfactor=0.4)\n catalog['fechaMusica'] = om.newMap('RBT')\n\n return catalog",
"def create_interaction_model_catalog_v1(self, catalog, **kwargs):\n # type: (DefinitionData_ccdbb3c2, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, CatalogResponse_2f6fe800]\n operation_name = \"create_interaction_model_catalog_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog' is set\n if ('catalog' not in params) or (params['catalog'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'catalog' in params:\n body_params = params['catalog']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.catalog_response.CatalogResponse\", status_code=200, message=\"Returns the generated catalogId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the catalog definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=412, message=\"Precondition failed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.catalog_response.CatalogResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def init():\n catalog = model.newCatalog()\n return catalog",
"def initCatalog(tipo):\n catalog = model.newCatalog(tipo)\n \n return catalog",
"def newCatalog(sgml):\n ret = libxml2mod.xmlNewCatalog(sgml)\n if ret is None:raise treeError('xmlNewCatalog() failed')\n return catalog(_obj=ret)",
"def initCatalog(tipolista : str):\n catalog = model.newCatalog(tipolista)\n return catalog",
"def POST(self, uri='catalog'):\n # content negotiation\n content_type = negotiated_content_type(self.supported_types, self.default_content_type)\n\n # registry acl enforcement\n allowed = web.ctx.ermrest_registry.can_create(web.ctx.webauthn2_context.attributes)\n if not allowed:\n raise rest.Forbidden(uri)\n\n # optional input\n docstr = web.ctx.env['wsgi.input'].read().decode().strip()\n if docstr:\n try:\n doc = json.loads(docstr)\n except:\n raise exception.rest.BadRequest('Could not deserialize JSON input.')\n else:\n doc = {}\n\n # create the alias entry\n catalog_id = web.ctx.ermrest_registry.claim_id(id=doc.get('id'), id_owner=doc.get('owner'))\n\n # register the catalog descriptor\n entry = web.ctx.ermrest_registry.register(catalog_id, alias_target=doc.get('alias_target'))\n\n web.header('Content-Type', content_type)\n web.ctx.ermrest_request_content_type = content_type\n\n # set location header and status\n location = '/ermrest/catalog/%s' % catalog_id\n web.header('Location', location)\n web.ctx.status = '201 Created'\n\n if content_type == _text_plain:\n return str(catalog_id)\n else:\n assert content_type == _application_json\n return json.dumps(dict(id=catalog_id))",
"def __init__(self):\n super(CatalogProxy, self).new_instance(\"catalog\", Catalog)",
"def create(request: YardRequestCreate) -> Yard:\n logger.debug(f'Executing Yard create with request:{request}')\n return Yard(request.name)",
"def from_catalog(cls, catalog):\n objects = [Object.from_object(obj) for obj in catalog.objects]\n return Catalog(objects, catalog._chooser)",
"def create(self, request):\n if not request.data:\n return Response(status=status.HTTP_400_BAD_REQUEST, data={'detail': 'Missing composeinfo'})\n release_obj = lib.release__import_from_composeinfo(request, request.data)\n url = reverse('release-detail', args=[release_obj])\n return Response({'url': url}, status=status.HTTP_201_CREATED)",
"def manage_addAlissCatalog(self, REQUEST=None):\n ob = AlissCatalog()\n self._setObject(ALISS_CATALOG_ID, ob)\n ob = self._getOb(ALISS_CATALOG_ID)\n if REQUEST is not None:\n return self.manage_main(self, REQUEST, update_menu=1)",
"def initCatalog(list_type):\n catalog = model.newCatalog(list_type)\n return catalog",
"def post(self, request):\n\n try:\n\n industry_data = Industry.objects.get(\n naics_code=request.data['naics_code'])\n category_data = JobCategory.objects.get(\n o_net_soc_code=request.data['category'])\n data, __ = JobCatalog.objects.get_or_create(\n naics_code=industry_data, category=category_data)\n if __:\n message = \"Catalog created\"\n else:\n message = \"Catalog already exists\"\n\n return Response({\"message\": message},\n status=status.HTTP_201_CREATED)\n except Exception as e:\n return Response({\"error\": \"{}\".format(e)},\n status=status.HTTP_400_BAD_REQUEST)",
"def __init__(self, catalog: cat.Catalog) -> None:\n self._catalog = catalog\n self._control_dict = self._create_control_dict()",
"def catalog_clone(self, args):\n try:\n catalog = self.server.connect_ermrest(args.id)\n print(\"Attempting to clone catalog %s into new catalog. Please wait...\" % args.id)\n dest_cat = catalog.clone_catalog(copy_data=args.no_copy_data,\n copy_annotations=args.no_copy_annotations,\n copy_policy=args.no_copy_policy,\n truncate_after=args.no_truncate_after,\n exclude_schemas=args.exclude_schemas)\n print(\"Catalog successfully cloned into new catalog: %s\" % dest_cat.catalog_id)\n except HTTPError as e:\n if e.response.status_code == requests.codes.not_found:\n raise ResourceException('Catalog not found', e)\n else:\n raise e",
"def create_catalog_item(\n self,\n request: catalog_service.CreateCatalogItemRequest = None,\n *,\n retry: retries.Retry = gapic_v1.method.DEFAULT,\n timeout: float = None,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> catalog.CatalogItem:\n # Create or coerce a protobuf request object.\n\n request = catalog_service.CreateCatalogItemRequest(request)\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method.wrap_method(\n self._transport.create_catalog_item,\n default_timeout=None,\n client_info=_client_info,\n )\n\n # Send the request.\n response = rpc(request, retry=retry, timeout=timeout, metadata=metadata)\n\n # Done; return the response.\n return response",
"def __init__(self, catalog_path):\n self.catalog_path = catalog_path\n self.load_catalog()\n return",
"def initCatalog(tad_list_type):\n catalog = model.newCatalog(tad_list_type)\n return catalog",
"def initCatalog():\n t = \"SINGLE_LINKED\"\n catalog = model.newCatalog(t)\n return catalog",
"def new(context, request):\n print(\"new - request.context: \", str(request.context.__repr__()))\n if request.params.get('name') in ['view', 'new']: raise HTTPBadRequest\n\n kwargs = dict()\n kwarg_keys = (\n (\"foo_name\", app_model.Foo),\n (\"bar_name\", app_model.Bar),\n (\"baz_name\", app_model.Baz),\n (\"qux_name\", app_model.Qux),\n )\n for key, cls in kwarg_keys:\n if hasattr(request.context, key) is True:\n kwargs[key] = getattr(request.context, key)\n else:\n kwargs[key] = request.params.get('name')\n break\n\n new_obj = cls(**kwargs)\n app_model.Session.add(new_obj)\n success = app_model.try_commit()\n raise HTTPFound(request.resource_url(new_obj, route_name=\"view\"))",
"def get_catalog(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bin\n return Catalog(\n self._provider_manager,\n self._get_provider_session('catalog_lookup_session').get_catalog(*args, **kwargs),\n self._runtime,\n self._proxy)"
] | [
"0.7075962",
"0.66169626",
"0.65908253",
"0.6559741",
"0.6491398",
"0.6491398",
"0.6491398",
"0.6474749",
"0.64458245",
"0.63912857",
"0.6327027",
"0.6295636",
"0.624926",
"0.61907876",
"0.6131978",
"0.61135054",
"0.60304767",
"0.60023105",
"0.60003024",
"0.5982443",
"0.5968106",
"0.592177",
"0.5913516",
"0.5837793",
"0.5831484",
"0.5820308",
"0.5814932",
"0.5805782",
"0.5786242",
"0.5709991"
] | 0.6687406 | 1 |
Lists the subscribers for a particular vendor. | def list_subscribers_for_development_events_v0(self, vendor_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, ListSubscribersResponse_d1d01857, BadRequestError_a8ac8b44, Error_d660d58]
operation_name = "list_subscribers_for_development_events_v0"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'vendor_id' is set
if ('vendor_id' not in params) or (params['vendor_id'] is None):
raise ValueError(
"Missing the required parameter `vendor_id` when calling `" + operation_name + "`")
resource_path = '/v0/developmentEvents/subscribers'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
if 'vendor_id' in params:
query_params.append(('vendorId', params['vendor_id']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.development_events.subscriber.list_subscribers_response.ListSubscribersResponse", status_code=200, message="Successful operation."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v0.development_events.subscriber.list_subscribers_response.ListSubscribersResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def subscribers(id):\n return core.query(schema.streamBySubscribers, id)",
"def get_subscribers(self) -> Iterator[Any]:\n for subscription in self._subscriptions[self.id]:\n yield subscription.subscriber",
"def list_subscriptions_for_development_events_v0(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, ListSubscriptionsResponse_c033036c, Error_d660d58]\n operation_name = \"list_subscriptions_for_development_events_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/developmentEvents/subscriptions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'subscriber_id' in params:\n query_params.append(('subscriberId', params['subscriber_id']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.development_events.subscription.list_subscriptions_response.ListSubscriptionsResponse\", status_code=200, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v0.development_events.subscription.list_subscriptions_response.ListSubscriptionsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def do_command(self, args):\n vendorops = dbops.Vendors()\n listing = vendorops.list(args)\n ordering = ['vendor_name']\n do_list(listing, ordering)",
"def get(self, orgname):\n permission = AdministerOrganizationPermission(orgname)\n if permission.can():\n organization = model.organization.get_organization(orgname)\n query = model.organization_skus.get_org_subscriptions(organization.id)\n\n if query:\n subscriptions = list(query.dicts())\n for subscription in subscriptions:\n subscription[\"sku\"] = marketplace_subscriptions.get_subscription_sku(\n subscription[\"subscription_id\"]\n )\n return subscriptions\n else:\n return []\n abort(401)",
"def subscribers_by_name(self, username, repository_name, access_token=None):\n return self._complete_request_by_name(\n username, repository_name, \"subscribers\", access_token)",
"def test_listVendorWithNoParams(self):\r\n result = self.client.listVendors({'i_customer': 1})\r\n assert result['result']=='OK'",
"def get_subscriptions(self):\n url = '{}/v2/subscriptions'.format(self.url)\n r = requests.get(url, headers=self.headers_v2)\n return r.json()",
"def get_subscribers(self, \n order=\"created_at desc\",\n offset=None,\n count=None):\n req_data = [ None, order, fmt_paging(offset, count)]\n return self.request(\"query:Contact.stats\", req_data)",
"def listSubscriptions() -> object:\n\n db = Db()\n return db.Subscriptions.objects().to_json()",
"def get_subscriptions(self):\n return self.subscriptions.all()",
"def list(cls, **kwargs):\n response = Yola().list_subscriptions(**kwargs)\n return [cls(**sub) for sub in response['results']]",
"def subscribers_by_id(self, repository_id, access_token=None):\n return self._complete_request_by_id(\n repository_id, \"subscribers\", access_token)",
"def getAllSubscriptions(self):\n return self.request(\n \"getAllSubscriptions\",\n )",
"def get_vendor_list_v1(self, **kwargs):\n # type: (**Any) -> Union[ApiResponse, object, Error_fbe913d9, Vendors_f5f1b90b]\n operation_name = \"get_vendor_list_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n\n resource_path = '/v1/vendors'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.vendor_management.vendors.Vendors\", status_code=200, message=\"Return vendor information on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.vendor_management.vendors.Vendors\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_subscribers():\n # TODO: make calls to each device asynchronous so we don't block\n # trying to read from an unresponsive device on start up.\n PortList = serial.tools.list_ports.comports()\n manager.executor = ThreadPoolExecutor(max_workers=len(PortList))\n for port in PortList:\n if port.device in IGNORE_LIST:\n continue\n log.info('Found {}'.format(port.device))\n ser = serial.Serial(port.device, baudrate=115200)\n looping = True\n while looping:\n b = pyvesc.encode(pyvesc.ReqSubscription('t'))\n ser.reset_input_buffer()\n ser.write(b)\n l = ser.read()\n if l == b'\\x02' or l == b'\\x03':\n # It's a VESC message!\n looping = not init_vesc_driver(port, ser, l)\n else:\n # It's a JSON message!\n looping = not init_json_driver(port, ser, l)",
"def list_subscriptions(\n connection, project_id, fields=None, offset=0, limit=-1, error_msg=None\n):\n return connection.get(\n url=f'{connection.base_url}/api/subscriptions',\n params={'offset': offset, 'limit': limit, 'fields': fields},\n headers={'X-MSTR-ProjectID': project_id},\n )",
"def list_subscriptions(self):\n return {'abonnementen': self.customer.abonnementen}",
"def subscribers(self) -> Iterator[Any]:\n yield from self.get_subscribers()",
"def subscriptions(self):\r\n return v3.Subscriptions(self)",
"def subscribed(cls, team):\n return cls.query(\n cls.status == 'subscribe',\n cls.team == team.lower()\n ).fetch(100)",
"def test_admin_sms_subscriber_view_list(self):\n response = self.client.get('/admin/sms_module/smscampaignsubscriber/')\n self.failUnlessEqual(response.status_code, 200)",
"def list(self, **params):\n\n _, _, vouchers = self.http_client.get(\"/vouchers\", params=params)\n return vouchers",
"def get(self):\n user = get_authenticated_user()\n account_number = marketplace_users.get_account_number(user)\n if not account_number:\n raise NotFound()\n\n user_subscriptions = marketplace_subscriptions.get_list_of_subscriptions(account_number)\n\n for subscription in user_subscriptions:\n bound_to_org, organization = organization_skus.subscription_bound_to_org(\n subscription[\"id\"]\n )\n # fill in information for whether a subscription is bound to an org\n if bound_to_org:\n subscription[\"assigned_to_org\"] = organization.username\n else:\n subscription[\"assigned_to_org\"] = None\n\n return user_subscriptions",
"def GetSubscriptionsFrom(self):\n\n return self.__GetJson(\"/subscriptions/from\", True)",
"def count_subscribers(self):\n return self.request(\"count:Contact\", [ None ])",
"async def get_subscriptions(\n self,\n\t\tfields: Optional[List[BaseUserGroupFields]] = None,\n\t\toffset: Optional[int] = None,\n\t\tcount: Optional[int] = None,\n\t\t**kwargs\n ) -> donut.GetSubscriptionsResponseModel:\n\n params = self.get_set_params(locals())\n response = await self.api.request(\"donut.getSubscriptions\", params)\n model = donut.GetSubscriptionsResponse\n return model(**response).response",
"def subscriptions(self):\r\n return subs.AccountSubscriptions(self)",
"def get_vendors_and_products_seen(cls, cb):\n url = \"/device_control/v3/orgs/{0}/products\".format(cb.credentials.org_key)\n resp = cb.get_object(url)\n return resp.get(\"results\", [])",
"def GetSubscriptions(self):\n\n return self.__GetJson(\"/subscriptions\", True)"
] | [
"0.61201715",
"0.608175",
"0.5926131",
"0.5878165",
"0.5822366",
"0.5820727",
"0.5819338",
"0.5757884",
"0.5748074",
"0.57391936",
"0.5663166",
"0.5601533",
"0.5574416",
"0.55726206",
"0.55469656",
"0.55281115",
"0.55225855",
"0.5510666",
"0.5506967",
"0.5494915",
"0.5494254",
"0.54782575",
"0.5456985",
"0.5454922",
"0.5441924",
"0.5432611",
"0.54283434",
"0.54093254",
"0.53937536",
"0.5366473"
] | 0.6614901 | 0 |
Creates a new subscriber resource for a vendor. | def create_subscriber_for_development_events_v0(self, create_subscriber_request, **kwargs):
# type: (CreateSubscriberRequest_a96d53b9, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, Error_d660d58]
operation_name = "create_subscriber_for_development_events_v0"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'create_subscriber_request' is set
if ('create_subscriber_request' not in params) or (params['create_subscriber_request'] is None):
raise ValueError(
"Missing the required parameter `create_subscriber_request` when calling `" + operation_name + "`")
resource_path = '/v0/developmentEvents/subscribers'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_subscriber_request' in params:
body_params = params['create_subscriber_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message="Created. Returns a URL to retrieve the subscriber in 'Location' header."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def handle_create(self):\n subscription = self.client().subscription(\n self.properties[self.QUEUE_NAME],\n subscriber=self.properties[self.SUBSCRIBER],\n ttl=self.properties[self.TTL],\n options=self.properties[self.OPTIONS]\n )\n self.resource_id_set(subscription.id)",
"def add_subscription(self):\n schema = schemas.load(schemas.Subscription, self.request)\n subscription = self.customer.add_subscription(**schema)\n self.request.db.flush()\n self.request.response.status_int = 201\n return {'abonnement': subscription}",
"def create(self, validated_data):\n subscription = super().create(validated_data)\n subscription.send_verification_email()\n return subscription",
"def create_subscription(connection, project_id, body, fields=None, error_msg=None):\n return connection.post(\n url=f'{connection.base_url}/api/subscriptions',\n params={'fields': fields},\n headers={'X-MSTR-ProjectID': project_id},\n json=body,\n )",
"def _create_subscription(self):\n try:\n self.client.create_subscription(\n name=self.subscription_path, topic=self.topic_path\n )\n except NotFound:\n # suitable topic does not exist in the Pitt-Google project\n raise ValueError(\n (\n f\"A subscription named {self.subscription_name} does not exist\"\n \"in the Google Cloud Platform project \"\n f\"{settings.GOOGLE_CLOUD_PROJECT}, \"\n \"and one cannot be automatically create because Pitt-Google \"\n \"does not publish a public topic with the same name.\"\n )\n )\n else:\n self._log_and_print(f\"Created subscription: {self.subscription_path}\")",
"def create_subscription(self, user, standard):\r\n\r\n subscription = self.create(\r\n user=user,\r\n standard=standard,\r\n )\r\n\r\n return subscription",
"def subscribe(request):\n address = request.POST.get('address')\n\n new_sub = Subscription(**{\n \"address\": address\n })\n new_sub.save()\n\n return HttpResponse(json.dumps({\n \"status\": \"success\"\n }, default=helpers.json_custom_parser), content_type='application/json')",
"def subscribe(self, request):\n email = self.cleaned_data.get('email')\n\n email_name, domain_part = email.rsplit('@', 1)\n domain_name = '@' + domain_part\n email_domain, created = Domain.objects.get_or_create(name=domain_name)\n\n subscriber, created = Subscriber.objects.get_or_create(email=email, mailing_list=self.mailing_list, defaults={\n 'domain': email_domain\n })\n subscriber.status = Status.PENDING\n subscriber.optin_ip_address = get_client_ip(request)\n subscriber.optin_date = timezone.now()\n subscriber.save()\n\n if not created:\n subscriber.tokens.filter(description='confirm_subscription').delete()\n\n token = subscriber.tokens.create(description='confirm_subscription')\n current_site = get_current_site(request)\n protocol = 'https' if request.is_secure() else 'http'\n domain = current_site.domain\n path = reverse('subscribers:confirm_double_optin_token', kwargs={\n 'mailing_list_uuid': self.mailing_list.uuid,\n 'token': token.text\n })\n confirm_link = '%s://%s%s' % (protocol, domain, path)\n\n confirm_email = self.mailing_list.get_confirm_email_template()\n confirm_email.send(subscriber.get_email(), {\n 'confirm_link': confirm_link\n })\n\n return subscriber",
"def create_subscription(self, client_URI_endpoint, event_destination_id,\n name, subscription_context):\n self.client_URI_endpoints[client_URI_endpoint] = \\\n Event(event_destination_id, name, subscription_context)\n self.write_subscriptions_to_tmp(self.client_URI_endpoints)",
"def create_subscription(self,\n body):\n\n return super().new_api_call_builder.request(\n RequestBuilder().server('default')\n .path('/v2/subscriptions')\n .http_method(HttpMethodEnum.POST)\n .header_param(Parameter()\n .key('Content-Type')\n .value('application/json'))\n .body_param(Parameter()\n .value(body))\n .header_param(Parameter()\n .key('accept')\n .value('application/json'))\n .body_serializer(APIHelper.json_serialize)\n .auth(Single('global'))\n ).response(\n ResponseHandler()\n .deserializer(APIHelper.json_deserialize)\n .is_api_response(True)\n .convertor(ApiResponse.create)\n ).execute()",
"def _create_sub(name, rostype, topic_callback, *args, **kwargs):\n # counting subscriber instance per topic name\n if name in TopicBack.sub_instance_count.keys():\n TopicBack.sub_instance_count[name] += 1\n else:\n TopicBack.sub_instance_count[name] = 1\n\n return rospy.Subscriber(name, rostype, topic_callback, *args, **kwargs)",
"def test_create_subscription(self):\n pass",
"def subscribePost() -> object:\n log = logging.getLogger(__name__)\n db = Db()\n\n body = request.get_json()\n\n if body is None:\n return jsonify({\"error\": \"json body is required\"}), HTTPStatus.HTTPStatus.BAD_REQUEST\n\n if not('datasetId') in body:\n return jsonify({\"error\": \"datasetId is a required attribute\"}), HTTPStatus.HTTPStatus.BAD_REQUEST\n\n if not('notificationUrl') in body:\n return jsonify({\"error\": \"notificationUrl is a required attribute\"}), HTTPStatus.HTTPStatus.BAD_REQUEST\n\n\n subscription = db.Subscriptions(\n datasetId=body['datasetId'],\n notificationUrl=body['notificationUrl']\n )\n\n subscription.save()\n\n subscription = json.loads(subscription.to_json())\n subscription['id'] = subscription['_id'][\"$oid\"]\n subscription.pop(\"_id\")\n log.debug(\"subscription created\")\n\n return jsonify(subscription), HTTPStatus.CREATED",
"async def create_subscription(user: int, redis: RedisDB):\n subscription_data = {\n \"subscriber_id\": user.id,\n \"cost\": str(os.getenv(\"AMOUNT\")),\n \"currency\": \"NANO\",\n \"period\": int(os.getenv(\"PERIOD\"))\n }\n json_data = json.dumps(subscription_data)\n r = requests.post(f\"{os.getenv('API_ENDPOINT')}create_subscription?token={os.getenv('NR_TOKEN')}\", json_data)\n rx = r.json()\n await redis.set(user.id, rx['subscription_id'])\n return r.json()",
"def post(self):\n data = request.json\n return new_subscription(data=data)",
"async def create_and_subscribe(user_id):\n client = gql(\n query=Query,\n mutation=Mutation,\n subscription=Subscription,\n consumer_attrs={\"strict_ordering\": True, \"confirm_subscriptions\": True},\n )\n await client.connect_and_init()\n\n sub_id = await client.send(\n msg_type=\"start\",\n payload={\n \"query\": textwrap.dedent(\n \"\"\"\n subscription op_name($user_id: UserId) {\n on_chat_message_sent(user_id: $user_id) { event }\n }\n \"\"\"\n ),\n \"variables\": {\"user_id\": user_id},\n \"operationName\": \"op_name\",\n },\n )\n\n # Receive the subscription confirmation message.\n resp = await client.receive(assert_id=sub_id, assert_type=\"data\")\n assert resp == {\"data\": None}\n\n return sub_id, client",
"def create_subscription(self, organization, collaborations, contractors):\r\n\r\n subscription = self.create(\r\n organization=organization,\r\n collaborations=collaborations,\r\n contractors=contractors,\r\n partner_discovery=partner_discovery,\r\n )\r\n return subscription",
"def sample_publisher(name='testname', phone='09100000000', address='testaddress'):\n return Publisher.objects.create(name=name, phone=phone, address=address)",
"async def create_subscription(self, installed_app_id: str, data: dict) -> dict:\r\n return await self.post(\r\n API_SUBSCRIPTIONS.format(installed_app_id=installed_app_id), data\r\n )",
"def create(self, *args, **kwargs):\n\n if not args and not kwargs:\n raise Exception('attributes for Voucher are missing')\n\n initial_attributes = args[0] if args else kwargs\n attributes = dict((k, v) for k, v in initial_attributes.items())\n attributes.update({'service': self.SERVICE})\n _, _, voucher = self.http_client.post(\"/vouchers\", body=attributes)\n return voucher",
"def _subscribe(self, sub_type: str, sub_version: str, condition: dict, callback) -> str:\n self.__logger.debug(f'subscribe to {sub_type} version {sub_version} with condition {condition}')\n data = {\n 'type': sub_type,\n 'version': sub_version,\n 'condition': condition,\n 'transport': {\n 'method': 'webhook',\n 'callback': f'{self.callback_url}/callback',\n 'secret': self.secret\n }\n }\n r_data = self.__api_post_request(TWITCH_API_BASE_URL + 'eventsub/subscriptions', data=data)\n result = r_data.json()\n error = result.get('error')\n if r_data.status_code == 500:\n raise TwitchBackendException(error)\n if error is not None:\n if error.lower() == 'conflict':\n raise EventSubSubscriptionConflict(result.get('message', ''))\n raise EventSubSubscriptionError(result.get('message'))\n sub_id = result['data'][0]['id']\n self.__add_callback(sub_id, callback)\n if self.wait_for_subscription_confirm:\n timeout = datetime.datetime.utcnow() + datetime.timedelta(\n seconds=self.wait_for_subscription_confirm_timeout)\n while timeout >= datetime.datetime.utcnow():\n if self.__callbacks[sub_id]['active']:\n return sub_id\n asyncio.get_event_loop().run_until_complete(asyncio.sleep(0.01))\n self.__callbacks.pop(sub_id, None)\n raise EventSubSubscriptionTimeout()\n return sub_id",
"def CreateSubscribeTransaction(self, dest, once=False):\n c = Subscribe(dest, self.node_id, once)\n self.connections.append((\"REACTIVE\", c))\n return c",
"def create_subscriber(self, exchange_name=None, callback=None):\n\n if not exchange_name:\n #@todo - remove this! it does not belong here!\n\n # if not create a new one based on the process id\n exchange_name = '%s_subscriber_%d' % (self.process.id, self._subscriber_cnt)\n self._subscriber_cnt += 1\n\n # create an XN\n xn = self.container.ex_manager.create_xn_queue(exchange_name)\n\n # create an XP\n # xp = self.container.ex_manager.create_xp(self.xp_base)\n # bind it on the XP\n # xn.bind(exchange_name, xp)\n\n return StreamSubscriber(from_name=xn, process=self.process, callback=callback, node=self.container.node)",
"def create_subscription(chid, use_time=False, use_ctrl=False,\n mask=None, callback=None):\n mask = mask or DEFAULT_SUBSCRIPTION_MASK\n\n ftype = promote_type(chid, use_ctrl=use_ctrl, use_time=use_time)\n\n uarg = ctypes.py_object(callback)\n evid = ctypes.c_void_p()\n poll()\n ret = libca.ca_create_subscription(ftype, 0, chid, mask,\n _CB_EVENT, uarg, ctypes.byref(evid))\n PySEVCHK('create_subscription', ret)\n\n poll()\n return (_CB_EVENT, uarg, evid)",
"def do_create_subscription(csp: CloudProviderInterface, environment_id=None):\n environment = Environments.get(environment_id)\n payload = build_subscription_payload(environment)\n try:\n csp.create_subscription(payload)\n except GeneralCSPException as e:\n app.logger.warning(\n \"Unable to create subscription for environment %s.\", environment.id,\n )\n raise e",
"def post_create_subscription(\n self, response: pubsub.Subscription\n ) -> pubsub.Subscription:\n return response",
"def create_topic ( sns_conn, topicname, subscription_email ) :\n t_result = sns_conn.create_topic( topicname )\n topic = t_result[ 'CreateTopicResponse' ][ 'CreateTopicResult' ][ 'TopicArn' ]\n sns_conn.subscribe( topic, 'email', subscription_email )\n\n return topic",
"def create_entity(self, context, listener):\n ncc_listener = self.payload_preparer.prepare_listener_for_creation(\n listener)\n msg = _(\"NetScaler driver listener creation: %s\") % repr(ncc_listener)\n LOG.debug(msg)\n resource_path = \"%s/%s\" % (RESOURCE_PREFIX, LISTENERS_RESOURCE)\n self.client.create_resource(context.tenant_id, resource_path,\n LISTENER_RESOURCE, ncc_listener)",
"def Create(sliver_name):\n rec = sliver_name\n if rec['instantiation'] == 'delegated':\n account.get(rec['name']).ensure_created(rec)\n logger.log(\"api_calls: Create %s\"%rec['name'])\n else:\n raise Exception, \"Only PLC can create non delegated slivers.\"",
"def createCustomer(sender, instance, **kwargs):\n Customer.objects.get_or_create(user=instance)"
] | [
"0.64551383",
"0.59768575",
"0.5970595",
"0.595671",
"0.59108967",
"0.58701646",
"0.584349",
"0.5834306",
"0.5730402",
"0.5714144",
"0.5700782",
"0.5666716",
"0.56383765",
"0.5575891",
"0.5572123",
"0.5554688",
"0.5541579",
"0.5495667",
"0.5487416",
"0.5486775",
"0.54239213",
"0.54188955",
"0.5403677",
"0.5394284",
"0.5362764",
"0.5362506",
"0.53493845",
"0.53472286",
"0.5345754",
"0.53427416"
] | 0.60352266 | 1 |
Associate skill with catalog. | def associate_catalog_with_skill_v0(self, skill_id, catalog_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, Error_d660d58]
operation_name = "associate_catalog_with_skill_v0"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'catalog_id' is set
if ('catalog_id' not in params) or (params['catalog_id'] is None):
raise ValueError(
"Missing the required parameter `catalog_id` when calling `" + operation_name + "`")
resource_path = '/v0/skills/{skillId}/catalogs/{catalogId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'catalog_id' in params:
path_params['catalogId'] = params['catalog_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message="Successful operation."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="PUT",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def addSkill(self, newskill):\n self.skills.append( newskill )",
"def addSkill(self, skillName, maxLevel, creditStart, creditIncrement):\r\n self.skills[skillName] = SkillObject(skillName, maxLevel, creditStart, creditIncrement)\r\n self.orderedSkills.append(skillName)",
"def addSkill(skill, db, **kwargs):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if skill_data:\n return colored(\"ERROR: Skill {S} is already in the skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n db.execute(\n 'INSERT INTO mystatus (skill, power, points)'\n 'VALUES (?, ?, ?)', (str(skill), str(kwargs['power']), \"0\"))\n db.commit()\n return colored(\"Add new skill: \" + str(skill), 'cyan')",
"def new_skill_interaction(self, skill):\n self.skill_interact[skill] = True",
"def setSkillInfo(self, name, information):\r\n skills[name].info = information",
"def add_skill(skill_list, skill): #inputs the skill dictionary and skill\r\n\tif skill==\"Gun Combat\":\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in guns:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\t\telse:\r\n\t\t\t\t\tskill=stellagama.random_choice(guns)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(guns)\r\n\telif skill in [\"Blade Combat\", \"Blade Cbt\"]:\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in melee:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\t\telse:\r\n\t\t\t\t\tskill=stellagama.random_choice(melee)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(melee)\r\n\telif skill==\"Vehicle\":\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in vehicles:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\telse:\r\n\t\t\t\tskill=stellagama.random_choice(vehicles)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(vehicles)\r\n\tif skill in skill_list:\r\n\t\tskill_list[skill] += 1\r\n\telif skill not in skill_list:\r\n\t\tskill_list[skill] = 1\r\n\treturn skill_list #outputs the skill dictionary\r",
"def _set_skill(caller, _, **kwargs):\n pool = _skill_pool(caller, kwargs.get(\"skill\"))\n caller.db.d1_skills[kwargs.get(\"skill\")][\"rank\"] += 1\n caller.ndb.pregen[\"skills\"] = pool\n\n return \"node_skills\"",
"async def skill(self, ctx, *, skill: str):\n\n try:\n skill = self.get_entry('Skill', skill.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = skill['Name']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://skill.png')\n embed.add_field(name='Learned', value=skill['Class/Rank'], inline=False)\n embed.add_field(name='Effect', value=skill['Effect'])\n\n await ctx.send(file=discord.File(f'xenox/skills/{name}.png', 'skill.png'), embed=embed)",
"def associate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"associate_isp_with_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def create_skill(skillname, skillpath, category):\n if Skill.query.filter_by(path=skillpath).first():\n raise AttributeError\n new_skill = Skill(name=skillname, path=skillpath)\n if not category:\n new_skill.root = True\n db.session.add(new_skill)\n db.session.commit()\n database_controller.create_hierarchy(category, skillpath)",
"def setup_class(cls):\n super().setup_class()\n cls.add_item(\"skill\", str(cls.GENERIC_SELLER.public_id), local=False)",
"def add_skills_to_profile():\n # get specific objects\n profile = storage.get(\"Profile\", profile_id)\n skills = storage.get(\"Skills\", skills_id)\n if profile is not None and skills is not None:\n # check every skill in profile\n for profile_skill in profile.skills:\n # if the given skill is already linked to profile, return\n if profile_skill.id == skills.id:\n return jsonify(skills.to_dict()), 200\n # if skill is not in profile, append skill and save\n profile.skills.append(skills)\n profile.save()\n return jsonify(skills.to_dict()), 201\n\n # if id not in database, abort\n abort(404)",
"def insert_skills(cursor):\n # Get the class of every skill\n skills_classes = dict()\n with open(CLASSES_PATH, encoding='UTF-8') as classes_file:\n classes_dict = ujson.load(classes_file)\n for class_id, _class in classes_dict.items():\n class_skills = _class.get(\"skills\", list())\n for class_skill in class_skills:\n skills_classes[class_skill.lower()] = class_id\n\n with open(SKILLS_PATH, encoding='UTF-8') as skills_file:\n skills_dict = ujson.load(skills_file)\n skills = list()\n # Get list of sorted skills\n sorted_skills_ids = list()\n for skill_id, skill in skills_dict.items():\n if skill_id:\n sorted_skills_ids.append((skill_id, int(skill.get(\"id\", 0))))\n else:\n sorted_skills_ids.append((skill_id, 0))\n sorted_skills_ids.sort(key=lambda tup: tup[1])\n # Start processing them\n for skill_id, _ in sorted_skills_ids:\n skill = skills_dict[skill_id]\n skill_info = list()\n # Get Skill Id\n skill_info.append(int(get_value(skill, \"Skill\", \"id\", str)))\n # Get Skill Name\n skill_info.append(get_value(skill, \"Skill\", \"name\", str))\n # Get Skill Identifier\n identifier = get_value(skill, \"Skill\", \"ident\", str).lower()\n skill_info.append(identifier)\n # Get Skill Icon\n skill_info.append(format_icon(get_value(skill, \"Skill\", \"icon\", str)))\n # Get Skill Circle\n skill_info.append(int(get_value(skill, \"Skill\", \"circle\", str)))\n # Get Skill Rank Level\n skill_info.append(int(get_value(skill, \"Skill\", \"rankLevel\", str)))\n # Get Skill Max Level\n skill_info.append(int(get_value(skill, \"Skill\", \"maxLevel\", str)))\n # Get Skill Video\n skill_info.append(get_value(skill, \"Skill\", \"video\", str))\n # Get Skill Desc\n skill_info.append(get_value(skill, \"Skill\", \"desc\", str))\n # Get Skill Details\n skill_info.append(get_value(skill, \"Skill\", \"desc2\", str))\n # Get Skill Type 1\n skill_info.append(get_value(skill, \"Skill\", \"type1\", str))\n # Get Skill Type 2\n skill_info.append(get_value(skill, \"Skill\", \"type2\", str))\n # Get Skill Cooldown\n skill_info.append(get_value(skill, \"Skill\", \"cooldown\", int))\n # Get Skill Element\n skill_info.append(get_value(skill, \"Skill\", \"element\", str))\n # Get Skill Required Stance\n skill_info.append(get_value(skill, \"Skill\", \"reqStance\", str))\n # Get Skill Level List\n skill_info.append(ujson.dumps(get_value(skill, \"Skill\", \"levelList\", dict)))\n # Get Skill Use Overheat\n skill_info.append(get_value(skill, \"Skill\", \"useOverHeat\", int))\n # Get Skill Class\n skill_info.append(get_skill_class(cursor, skills_classes.get(identifier, '')))\n\n\n skills.append(tuple(skill_info))\n\n skills = tuple(skills)\n\n cursor.executemany(\"INSERT INTO skills (id, name, identifier, icon, circle, rank_level, max_level, video, \"\n \"desc, details, type1, type2, cooldown, element, req_stance, level_list, use_overheat, \"\n \"class) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\", skills)",
"def use_skill(self, g, i, x, y):\n # @ param g a reference to the game engine\n # @ param i the index of the skill (basically what skill)\n # @ param x the x target coordinate in game pixels\n # @ param y the y target coordinate in game pixels\n if self.attackTimer < self.attackDelay:\n print(\"attack on CD\")\n return\n \n if self.skill[i].skillAttr == 0:\n g.fire_skill_sound.play()\n elif self.skill[i].skillAttr == 1:\n g.ice_skill_sound.play()\n elif self.skill[i].skillAttr == 2:\n g.lightning_skill_sound.play()\n elif self.skill[i].skillAttr == 3:\n g.poison_skill_sound.play()\n \n \n if self.skill[i].skillKey == 0: #Aura\n #turn the aura on/off\n if self.skill[i].active == False:\n #print(\"aura on\")\n self.skill[i].active = True\n else:\n self.skill[i].active = False\n #print(\"aura off\")\n \n elif self.skill[i].skillKey == 1: #Missile\n if self.mana[0] > self.skill[i].skillCost:\n self.mana[0] -= self.skill[i].skillCost\n self.attackTimer = 0\n target = Target(x, y)\n center_x = self.rect.x + (self.rect.width / 2)\n center_y = self.rect.y + (self.rect.height / 2)\n #bullet types: fire 5, ice 6, lightning 7\n #skill types: fire 0, ice 1, lightning 2\n g.bullets.append(self.bulletFactory.createBullet(g, self.skill[i].skillAttr + 5, 0, self.attack, 1024, target, center_x, center_y))\n #print(\"missile\")\n\n elif self.skill[i].skillKey == 2: #Breath\n #for each creep in the AoE cone, do damage.\n if self.mana[0] > self.skill[i].skillCost:\n self.mana[0] -= self.skill[i].skillCost\n self.attackTimer = 0\n #get low and high angle (-45 degrees and +45 degrees from player -> point angle)\n lowAngle = math.atan2(y - self.rect.centery, x - self.rect.centerx) - 3.1415 / 2.0\n highAngle = math.atan2(y - self.rect.centery, x - self.rect.centerx) + 3.1415 / 2.0\n for creep in g.creeps:\n #get angle to creep\n creepAngle = math.atan2(creep.rect.centery - self.rect.centery, creep.rect.centerx - self.rect.centerx)\n \n #if angle to the creep is between the two angles\n if creepAngle > lowAngle and creepAngle < highAngle:\n #and the distance to the creep is below the skill's range\n if ( (creep.rect.centerx - self.rect.centerx) ** 2 + (creep.rect.centery - self.rect.centery) ** 2 ) ** 0.5 < 4 * 24:\n creep.take_damage( self.attack )\n #print(\"breath\")\n #apply debuffs, based on type\n if self.skill[i].skillAttr == 0: #fire\n creep.applyBurning()\n elif self.skill[i].skillAttr == 1: #frost\n creep.applyChilled()\n elif self.skill[i].skillAttr == 2: #lightning\n creep.applyShocked()",
"def create(self):\n # type: () -> AbstractSkill\n raise NotImplementedError",
"def add_card(handler_input, response):\n # type: (HandlerInput, Response) -> None\n response.card = SimpleCard(\n title=skill_name,\n content=convert_speech_to_text(response.output_speech.ssml))",
"def add_card(handler_input, response):\n # type: (HandlerInput, Response) -> None\n response.card = SimpleCard(\n title=skill_name,\n content=convert_speech_to_text(response.output_speech.ssml))",
"def add_card(handler_input, response):\n # type: (HandlerInput, Response) -> None\n response.card = SimpleCard(\n title=skill_name,\n content=convert_speech_to_text(response.output_speech.ssml))",
"def upgrade_skill(self, skill_string):\r\n skill = self.__skills[skill_string]\r\n skill.skill_level += 1\r\n\r\n # Downgrading enabled the first time a skill is upgraded.\r\n if skill.skill_level == 1:\r\n self.skill_down_enable(skill_string)\r\n\r\n # Updates the UI and skill point value\r\n self.update_skill_level_info(skill_string)\r\n self.deduct_skill_points(skill.points_to_up)\r\n self.update_skill_info_box(skill_string)\r\n\r\n # Checks other requirements.\r\n for skill_string2 in self.__skills:\r\n self.check_skill_requirements(skill_string2)",
"def __init__(__self__, *,\n alexa_skill_id: pulumi.Input[str],\n is_enabled: pulumi.Input[bool]):\n pulumi.set(__self__, \"alexa_skill_id\", alexa_skill_id)\n pulumi.set(__self__, \"is_enabled\", is_enabled)",
"def manage_addAlissCatalog(self, REQUEST=None):\n ob = AlissCatalog()\n self._setObject(ALISS_CATALOG_ID, ob)\n ob = self._getOb(ALISS_CATALOG_ID)\n if REQUEST is not None:\n return self.manage_main(self, REQUEST, update_menu=1)",
"def register_catalog(catalog_name, catalog_config):\n _registered_catalogs[catalog_name] = catalog_config",
"def create_skill_for_vendor_v1(self, create_skill_request, **kwargs):\n # type: (CreateSkillRequest_92e74e84, **Any) -> Union[ApiResponse, object, CreateSkillResponse_2bad1094, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_skill_for_vendor_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'create_skill_request' is set\n if ('create_skill_request' not in params) or (params['create_skill_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_skill_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_skill_request' in params:\n body_params = params['create_skill_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.create_skill_response.CreateSkillResponse\", status_code=202, message=\"Accepted; Returns a URL to track the status in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.create_skill_response.CreateSkillResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def set_skills(username, skillpaths):\n cdate = Date()\n user = database_controller.get_user(username)\n db.session.add(cdate)\n db.session.commit()\n for skillpath, level in skillpaths.items():\n new_skill = database_controller.get_skill(skillpath)\n if not new_skill:\n raise NameError('The Skill {0} does not exist in the database!'.format(skillpath))\n database_controller.add_milestone(username, skillpath, cdate.date, \"Level {0}\".format(level), level)\n assoc = Association(level=level)\n assoc.skill_assoc = new_skill\n assoc.date_assoc = cdate\n assoc.users_assoc = user\n db.session.commit()",
"def upload_catalog(self, catalog: Catalog) -> None:\n self._status.check_authority_for_draft()\n\n put_data: Dict[str, Any] = {\"catalog\": catalog.dumps()}\n if not put_data:\n raise TypeError(\"Empty catalog\")\n put_data.update(self._status.get_status_info())\n\n self._client.open_api_do(\"PUT\", \"labels/catalogs\", self.dataset_id, json=put_data)",
"def skill(ctx: Context, public_id: PublicId):\n _eject_item(ctx, \"skill\", public_id)",
"def insert_skill_abilities(cursor):\n # Get the skill of every ability\n abilities_skills = dict()\n with open(SKILL_ABILITIES_PATH, encoding='UTF-8') as skills_file:\n skills_dict = ujson.load(skills_file)\n for skill_id, skill_abilities in skills_dict.items():\n for skill_ability in skill_abilities:\n abilities_skills[skill_ability.lower()] = skill_id.lower()\n\n # Get info from HTML\n abilities_html_dict = dict()\n with open(ABILITIES_HTML_PATH, encoding='UTF-8') as abilities_html_file:\n soup = BeautifulSoup(abilities_html_file, 'html.parser')\n for ability in soup.findAll('div'):\n # Remove clutter from attribute ID\n ability_id = ability.attrs['id'][18:-8]\n ability_name = ability.b.text\n ability_type = ''\n ability_max_level = 0\n ability_req_skill_level = 0\n ability_desc = ability.contents[-1].strip()\n # Parse all except the name and desc that we already got\n for i in range(2, len(ability.contents)-2):\n if isinstance(ability.contents[i], Tag):\n if ability.contents[i].text == \"Type:\":\n ability_type = ability.contents[i+1].strip()\n elif ability.contents[i].text == \"Max Level:\":\n ability_max_level = int(ability.contents[i+1].strip())\n elif ability.contents[i].text == \"Required Skill Level:\":\n ability_req_skill_level = int(ability.contents[i+1].strip())\n elif ability.contents[i].text == \"Circle:\":\n pass\n else:\n if ability.contents[i].name != 'br':\n l.warning(\"There is a non handled tag {} in ability: {}\".format(ability.contents[i].text,\n ability))\n abilities_html_dict[ability_id.lower()] = {\n 'name': ability_name,\n 'type': ability_type,\n 'max_level': ability_max_level,\n 'req_skill_level': ability_req_skill_level,\n 'desc': ability_desc\n }\n\n with open(ABILITIES_JSON_PATH, encoding='UTF-8') as abilities_file:\n abilities_dict = ujson.load(abilities_file)\n abilities = list()\n # Get list of sorted abilities\n sorted_abilities_ids = list()\n for ability_id, ability in abilities_dict.items():\n if ability_id:\n sorted_abilities_ids.append((ability_id, int(ability.get(\"ClassID\", 0))))\n else:\n sorted_abilities_ids.append((ability_id, 0))\n sorted_abilities_ids.sort(key=lambda tup: tup[1])\n # Start processing them\n for ability_id, _ in sorted_abilities_ids:\n ability = abilities_dict[ability_id]\n html_ability = abilities_html_dict.get(ability.get(\"ClassName\", \"\").lower(), dict())\n ability_info = list()\n # Get Ability Id\n ability_info.append(int(get_value(ability, \"Ability\", \"ClassID\", str)))\n # Get Ability Name\n ability_info.append(get_value(html_ability, \"Ability\", \"name\", str))\n # Get Ability Type\n ability_info.append(get_value(html_ability, \"Ability\", \"type\", str))\n # Get Ability Required Circle\n ability_info.append(int(get_value(ability, \"Ability\", \"ReqCircle\", int)))\n # Get Ability Max Level\n ability_info.append(get_value(html_ability, \"Ability\", \"max_level\", int))\n # Get Ability Desc\n ability_info.append(get_value(html_ability, \"Ability\", \"desc\", str))\n # Get Ability Icon\n ability_info.append(format_icon(get_value(ability, \"Ability\", \"Icon\", str)))\n # Get Skill Class\n ability_info.append(get_ability_skill(cursor, abilities_skills.get(ability_id.lower(), '')))\n # Get Ability Required Skill Level\n ability_info.append(get_value(html_ability, \"Ability\", \"req_skill_level\", int))\n\n abilities.append(tuple(ability_info))\n\n abilities = tuple(abilities)\n\n cursor.executemany(\"INSERT INTO skill_abilities (id, name, type, circle, max_level, desc, icon, skill_id, \"\n \"req_skill_level) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\", abilities)",
"def test_skills_updated(self):\n assert self.agent_config.skills == {self.new_skill_id}",
"def test_skills_updated(self):\n assert self.skill_config.skills == {self.new_skill_id}",
"def addSkillIntoPlayerDatabase(self, userid, name, level = 0):\r\n if not isinstance(userid, int):\r\n userid = self.getUserIdFromSteamId(userid)\r\n self.execute(\"INSERT OR IGNORE INTO Skill (UserID, name, level) VALUES (?,?,?)\", userid, name, level)\r\n return self.cursor.lastrowid"
] | [
"0.6664767",
"0.6635394",
"0.612437",
"0.5970023",
"0.59050703",
"0.5865405",
"0.584907",
"0.561355",
"0.55675197",
"0.5513248",
"0.5433672",
"0.5427542",
"0.5261133",
"0.5227878",
"0.5173006",
"0.5169779",
"0.5169779",
"0.5169779",
"0.516817",
"0.5143061",
"0.50991553",
"0.5071152",
"0.5038589",
"0.50385326",
"0.50143206",
"0.5013568",
"0.49905846",
"0.49568385",
"0.49123773",
"0.48980862"
] | 0.70367885 | 0 |
Lists all the catalogs associated with a skill. | def list_catalogs_for_skill_v0(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, ListCatalogsResponse_3dd2a983, BadRequestError_a8ac8b44, Error_d660d58]
operation_name = "list_catalogs_for_skill_v0"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v0/skills/{skillId}/catalogs'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.catalog.list_catalogs_response.ListCatalogsResponse", status_code=200, message="Successful operation."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v0.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v0.catalog.list_catalogs_response.ListCatalogsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list_catalogs(self):\n return self._json_object_field_to_list(\n self._get_catalogs_json(), self.__MISSION_STRING)",
"def list_detail_catalog(self, catalog_name):\n # list catalog\n self._list_catalog(catalog_name)\n # detail catalog\n self._details_catalog(catalog_name)",
"def get_catalogs(self):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bins_template\n catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs()\n cat_list = []\n for cat in catalogs:\n cat_list.append(Catalog(self._provider_manager, cat, self._runtime, self._proxy))\n return CatalogList(cat_list)",
"def catalogs(env):\n envs = environments()\n check_env(env, envs)\n\n if app.config['ENABLE_CATALOG']:\n nodenames = []\n catalog_list = []\n query = AndOperator()\n\n if env != '*':\n query.add(EqualsOperator(\"catalog_environment\", env))\n\n query.add(NullOperator(\"catalog_timestamp\", False))\n\n order_by_str = '[{\"field\": \"certname\", \"order\": \"asc\"}]'\n nodes = get_or_abort(puppetdb.nodes,\n query=query,\n with_status=False,\n order_by=order_by_str)\n nodes, temp = tee(nodes)\n\n for node in temp:\n nodenames.append(node.name)\n\n for node in nodes:\n table_row = {\n 'name': node.name,\n 'catalog_timestamp': node.catalog_timestamp\n }\n\n if len(nodenames) > 1:\n form = CatalogForm()\n\n form.compare.data = node.name\n form.against.choices = [(x, x) for x in nodenames\n if x != node.name]\n table_row['form'] = form\n else:\n table_row['form'] = None\n\n catalog_list.append(table_row)\n\n return render_template(\n 'catalogs.html',\n nodes=catalog_list,\n envs=envs,\n current_env=env)\n else:\n log.warn('Access to catalog interface disabled by administrator')\n abort(403)",
"def skills():\n with app.app_context():\n results = Skill.query.all()\n return SkillsResponse(skills=results).json(), 200",
"def get_catalog(self):\n\n rep = req.get_json(self.CATALOG)\n repo_list = rep[\"repositories\"]\n\n for repo in repo_list:\n self.list.append(Repository(repo))\n\n return self.list",
"def getCatalogs():",
"def get(self):\n return GenericGet().get_catalogs()",
"def catalog():\n session['target'] = \"/\"\n sqlsession = SQLSESSION()\n items = sqlsession.query(Item, Category)\\\n .join(Category).order_by(Item.create_date).limit(10)\n categories = sqlsession.query(Category).all()\n return render_template(\"catalog.html\",\n items=items,\n categories=categories,\n item_title=\"Latest Items\")",
"def search_catalog(self, query):\n scope = datacatalog.SearchCatalogRequest.Scope()\n scope.include_project_ids.append(self.__project_id)\n\n request = datacatalog.SearchCatalogRequest()\n request.scope = scope\n request.query = query\n request.page_size = 1000\n\n return [\n result for result in self.__datacatalog.search_catalog(request)\n ]",
"def get_catalog(self) -> Catalog:\n params: Dict[str, Any] = self._status.get_status_info()\n\n response = self._client.open_api_do(\n \"GET\", \"labels/catalogs\", self.dataset_id, params=params\n ).json()\n return Catalog.loads(response[\"catalog\"])",
"def catalog(self) -> str:\n return pulumi.get(self, \"catalog\")",
"def catalogs(self):\n return sorted(self._catalog_comp_info_dicts.keys())",
"def associate_catalog_with_skill_v0(self, skill_id, catalog_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, Error_d660d58]\n operation_name = \"associate_catalog_with_skill_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/skills/{skillId}/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def showCatalog(sport_id):\n\n sport = session.query(Sport).filter_by(id=sport_id).one()\n items = session.query(Item).filter_by(sport_id=sport_id).all()\n return render_template('catalog.html', sport=sport, items=items)",
"def get_catalog_items(id):\n\n username = login_session.get('username', None)\n catalogs = session.query(Catalog).all()\n selected_catalog = session.query(Catalog).filter_by(id=id).one()\n items = selected_catalog.items\n catalogs_display = [\n {\n 'id': catalog.id,\n 'name': catalog.name\n } for catalog in catalogs]\n items_display = [{'id': item.id, 'title': item.title} for item in items]\n items_summary = '{0} Items ({1} items)'.format(\n selected_catalog.name,\n len(items_display))\n return render_template(\n 'home.html',\n catalogs_display=catalogs_display,\n items_display=items_display,\n items_summary=items_summary,\n username=username)",
"def list_interaction_model_catalogs_v1(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, ListCatalogResponse_bc059ec9]\n operation_name = \"list_interaction_model_catalogs_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.list_catalog_response.ListCatalogResponse\", status_code=200, message=\"Returns list of catalogs for the vendor.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no catalog defined for the catalogId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.list_catalog_response.ListCatalogResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def rest_get_catalogue_handler():\n cats = category.get_all_categories()\n items = item.get_all_items()\n result = {}\n result['categories'] = [c.serialize for c in cats]\n result['items'] = [i.serialize for i in items]\n return jsonify(result)",
"def get_catalog_options(self):\n catalog_api = CourseCatalogApiClient(self.user)\n catalogs = catalog_api.get_all_catalogs()\n # order catalogs by name.\n catalogs = sorted(catalogs, key=lambda catalog: catalog.get('name', '').lower())\n\n return BLANK_CHOICE_DASH + [\n (catalog['id'], catalog['name'],)\n for catalog in catalogs\n ]",
"def get_catalogs_by_query(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinQuerySession.get_bins_by_query_template\n return self._get_provider_session('catalog_query_session').get_catalogs_by_query(*args, **kwargs)",
"def get_catalogs_by_record_type(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bins_by_record_type\n catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs_by_record_type(*args, **kwargs)\n cat_list = []\n for cat in catalogs:\n cat_list.append(Catalog(self._provider_manager, cat, self._runtime, self._proxy))\n return CatalogList(cat_list)",
"def get_catalog(self, command):\n return self._catalogs.get(str(command))",
"def catalog_json():\n all_categories = (session.query(Categories).all())\n all_items = (session.query(Items).all())\n return jsonify(categories=([all_categories.serialize\n for all_categories in all_categories]),\n items=([all_items.serialize\n for all_items in all_items]))",
"def get_catalogs_by_provider(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bins_by_provider\n catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs_by_provider(*args, **kwargs)\n cat_list = []\n for cat in catalogs:\n cat_list.append(Catalog(self._provider_manager, cat, self._runtime, self._proxy))\n return CatalogList(cat_list)",
"def get_catalogs_by_ids(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinLookupSession.get_bins_by_ids\n catalogs = self._get_provider_session('catalog_lookup_session').get_catalogs_by_ids(*args, **kwargs)\n cat_list = []\n for cat in catalogs:\n cat_list.append(Catalog(self._provider_manager, cat, self._runtime, self._proxy))\n return CatalogList(cat_list)",
"def show_catalogue(self):\n\n data = cur.execute(\"\"\"SELECT productid, productname, unitcost, stock, location \n FROM catalogue WHERE vendorname = ?\"\"\", (self.vendorname,)).fetchall()\n print(tabulate(data, headers=[\"Product ID\", \"Name\", \"Unit Cost\", \"Stock\", \"Location\"]))",
"def print_catalog(self):\n for book in self.books.keys():\n print(book)",
"def print_catalog(self):\n for book in self.books.keys():\n print(book)",
"def get_catalog():\n return jsonify(getCatalog())",
"def list_silos(self, kwargs):\n verbose = kwargs.get(\"verbose\", False)\n attributes = ALL if verbose else [\"cn\", \"objectClass\"]\n\n self.display(\n self.engine.query(\n self.engine.SILOS_FILTER(),\n attributes, base=','.join([\"CN=AuthN Policy Configuration,CN=Services,CN=Configuration\", self.engine.base_dn])\n ),\n verbose\n )"
] | [
"0.6852084",
"0.6113749",
"0.5815595",
"0.56907815",
"0.5633595",
"0.5573647",
"0.555769",
"0.5518518",
"0.5516258",
"0.5426061",
"0.53878295",
"0.5378777",
"0.53384465",
"0.5309134",
"0.53046465",
"0.5283861",
"0.52456987",
"0.5202846",
"0.5156608",
"0.51344407",
"0.5128742",
"0.5105541",
"0.50934035",
"0.5091146",
"0.5067696",
"0.5046782",
"0.5031933",
"0.5031933",
"0.500826",
"0.49923477"
] | 0.72920567 | 0 |
Create new upload Creates a new upload for a catalog and returns location to track the upload process. | def create_catalog_upload_v1(self, catalog_id, catalog_upload_request_body, **kwargs):
# type: (str, CatalogUploadBase_d7febd7, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "create_catalog_upload_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'catalog_id' is set
if ('catalog_id' not in params) or (params['catalog_id'] is None):
raise ValueError(
"Missing the required parameter `catalog_id` when calling `" + operation_name + "`")
# verify the required parameter 'catalog_upload_request_body' is set
if ('catalog_upload_request_body' not in params) or (params['catalog_upload_request_body'] is None):
raise ValueError(
"Missing the required parameter `catalog_upload_request_body` when calling `" + operation_name + "`")
resource_path = '/v1/catalogs/{catalogId}/uploads'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'catalog_id' in params:
path_params['catalogId'] = params['catalog_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'catalog_upload_request_body' in params:
body_params = params['catalog_upload_request_body']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message="Accepted"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_upload(projectArn=None, name=None, type=None, contentType=None):\n pass",
"def create_content_upload_v0(self, catalog_id, create_content_upload_request, **kwargs):\n # type: (str, CreateContentUploadRequest_bf7790d3, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, CreateContentUploadResponse_75cd6715, Error_d660d58]\n operation_name = \"create_content_upload_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'create_content_upload_request' is set\n if ('create_content_upload_request' not in params) or (params['create_content_upload_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_content_upload_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/catalogs/{catalogId}/uploads'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_content_upload_request' in params:\n body_params = params['create_content_upload_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.catalog.upload.create_content_upload_response.CreateContentUploadResponse\", status_code=201, message=\"Content upload created.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v0.catalog.upload.create_content_upload_response.CreateContentUploadResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def upload_catalog(self, catalog: Catalog) -> None:\n self._status.check_authority_for_draft()\n\n put_data: Dict[str, Any] = {\"catalog\": catalog.dumps()}\n if not put_data:\n raise TypeError(\"Empty catalog\")\n put_data.update(self._status.get_status_info())\n\n self._client.open_api_do(\"PUT\", \"labels/catalogs\", self.dataset_id, json=put_data)",
"def upload(self, upload_id):\r\n return u.Upload(self, upload_id)",
"def upload(self, upload_request):\n raise NotImplementedError",
"def put_upload(self):\n # print \"starting upload...\", self.current_upload['filepath']\n self.touch()\n self.log(\"STARTING_UPLOAD\", level=INFO)\n try:\n Backend.put_file(self.fileobj, self.current_upload[\"gcs_url\"])\n except exceptions.FilePutError as err:\n self.handle_put_error(err, self.fileobj)\n raise",
"def upload_to(instance, filename):\n return upload_image_path(filename, 'products')",
"def upload(ctx: click.Context, **kwargs):\n root_commands.cmd_upload(ctx.obj, **kwargs)",
"def upload():\n return handle_upload(app, request)",
"def upload(upload_type):\n env_banner()\n\n if upload_type not in Upload.ACCEPTED_TYPES:\n click.echo('Upload of only certain types are accepted.')\n click.echo('UPLOAD_TYPE can be [users | players | scores | all]')\n return\n\n upload_data = Upload()\n if upload_type == 'users':\n upload_data.file_name = config.USER_FILE_NAME\n if upload_type == 'all':\n result = Upload.upload_all()\n else:\n result = upload_data(upload_type)\n if result != Upload.SUCCESS:\n click.echo(f'Error Code: {result}. Error in upload.')\n return\n click.echo('Upload done!')",
"def initiate_multipart_upload(self):\n request = self.s3.create_request(\"OBJECT_POST\", uri = self.uri, headers = self.headers_baseline, extra = \"?uploads\")\n response = self.s3.send_request(request)\n data = response[\"data\"]\n self.upload_id = getTextFromXml(data, \"UploadId\")\n return self.upload_id",
"def upload(api_token, base_url, upload_file, metadata):\n\n upload_url = f\"{base_url}data_files/api_create?auth_token={api_token}\"\n files = {'file': open(upload_file, 'rb')}\n response = requests.post(upload_url, files=files, data=metadata)\n\n # Print out the outcome of the upload\n if response.status_code == 200:\n print(f'File {upload_file} successfully uploaded to HIEv')\n else:\n print(\n f'ERROR - There was a problem uploading file {upload_file} to HIEv')",
"def upload_start(self, local_path, cloud_file, size):\n\t\telog(\"uploading {1} ({2})\".format(local_path, cloud_file.path, bytes_scaled(size)))",
"def action(self):\n return blobstore.create_upload_url(self.upload_url)",
"def upload(self, filename, file_path):\n return",
"def create_file_upload(self, upload_filename,\n pub_user, module_supplier_id):\n up_response = self.do_request(\n self.base_url +\n \"/oasis/createFileUpload/\" +\n pub_user + \"/\" +\n upload_filename + \"/\" +\n str(module_supplier_id) + \"/\"\n )\n logger.debug(\"createFileUpload respons: {resp}\".format(\n resp=up_response.content\n ))\n up_id = int(json.loads(up_response.content)['taskId'])\n return up_id",
"async def upload(self, request):\n\n userid = await authenticated_userid(request)\n project = await request.app.context_project(request, userid)\n\n payload = await request.post()\n\n filename = payload['file'].filename\n upload_stream = payload['file'].file\n\n ext = os.path.splitext(filename)[1]\n\n if not re_filename_ext.match(ext):\n # paranoid check in case a script doesn't protect from code injection\n raise web.HTTPBadRequest(text='file extension not supported: %s' % filename)\n\n camera_id = uuid.uuid1().hex\n\n log = request['slog']\n log.debug('request: camera upload', filename=filename)\n\n config = request.app.config\n\n tmppath = dump_stream(config['media']['tempdir'], upload_stream)\n\n log.debug('file dump', camera_id=camera_id, tmppath=tmppath)\n\n await Camera.insert(request,\n camera_id=camera_id,\n filename=filename,\n project_id=project.project_id)\n\n await request.app.task_broker.publish('camera_upload', {\n 'userid': userid,\n 'project_id': project.project_id,\n 'camera_id': camera_id,\n 'tmppath': tmppath,\n 'filename': filename\n }, log=log)\n\n response_js = {\n 'camera_file_id': camera_id\n }\n\n return web.json_response(response_js, status=HTTPStatus.CREATED)",
"def api_upload():\n return make_response(file_manager.save_uploaded_file(), 200)",
"def create_upload_session(self, upload_file):\n upload = UploadedData.objects.create(\n user=self.request.user, state='UPLOADED', complete=True)\n upload_file.upload = upload\n upload_file.save()\n upload.size = upload_file.file.size\n upload.name = upload_file.name\n upload.file_type = self.get_file_type(upload_file.file.path)\n upload.save()\n\n description = self.get_fields(upload_file.file.path)\n\n for layer in description:\n configuration_options = DEFAULT_LAYER_CONFIGURATION.copy()\n configuration_options.update({'index': layer.get('index')})\n upload.uploadlayer_set.add(\n UploadLayer(\n upload_file=upload_file,\n name=layer.get('name'),\n fields=layer.get(\n 'fields',\n {}),\n index=layer.get('index'),\n feature_count=layer.get('feature_count'),\n configuration_options=configuration_options))\n upload.save()\n return upload",
"def image_create_and_upload(self, upload=True, **kwargs):\n if 'name' not in kwargs:\n name = data_utils.rand_name(self.__name__ + \"-image\")\n kwargs['name'] = name\n\n params = dict(kwargs)\n image = self.create_image(**params)\n self.assertEqual('queued', image['status'])\n if not upload:\n return image\n\n file_content = data_utils.random_bytes()\n image_file = io.BytesIO(file_content)\n self.client.store_image_file(image['id'], image_file)\n\n image = self.client.show_image(image['id'])\n return image",
"def begin_upload(self, request):\n def error(msg):\n return BeginUploadResponse(\n status=BeginUploadResponse.Status.ERROR,\n error_message=msg)\n\n hash_algo = _HASH_ALGO_MAPPING[request.hash_algo]\n if not impl.is_valid_hash_digest(hash_algo, request.file_hash):\n return error('Invalid hash digest format')\n\n service = impl.get_cas_service()\n if service is None:\n raise endpoints.InternalServerErrorException('Service is not configured')\n\n if service.is_object_present(hash_algo, request.file_hash):\n return BeginUploadResponse(\n status=BeginUploadResponse.Status.ALREADY_UPLOADED)\n\n upload_session, upload_session_id = service.create_upload_session(\n hash_algo,\n request.file_hash,\n auth.get_current_identity())\n return BeginUploadResponse(\n status=BeginUploadResponse.Status.SUCCESS,\n upload_session_id=upload_session_id,\n upload_url=upload_session.upload_url)",
"def _upload(\n self,\n client: demisto_client,\n marketplace: MarketplaceVersions,\n ) -> None:\n try:\n upload_method = self._client_upload_method(client=client)\n except NotImplementedError as e:\n raise NotImplementedError(\n f\"missing overriding upload method for {self.content_type}\"\n ) from e\n\n with TemporaryDirectory() as f:\n dir_path = Path(f)\n self.dump(\n dir_path,\n marketplace=marketplace,\n )\n response = upload_method(dir_path / self.normalize_name)\n parse_upload_response(\n response, path=self.path, content_type=self.content_type\n ) # raises on error",
"def upload():\n\treturn render_template(\"upload.html\", title=\"Upload a file\")",
"def action_upload(self):\n options=self.env['plm.config.settings'].GetOptions()\n status = 'uploaded'\n action = 'upload'\n default = {\n 'state': status,\n 'engineering_writable': False,\n }\n doc_default = {\n 'state': status,\n 'writable': False,\n }\n operationParams = {\n 'status': status,\n 'statusName': _('Uploaded'),\n 'action': action,\n 'docaction': 'uploaddoc',\n 'excludeStatuses': ['uploaded', 'confirmed', 'transmitted','released', 'undermodify', 'obsoleted'],\n 'includeStatuses': ['draft'],\n 'default': default,\n 'doc_default': doc_default,\n }\n if options.get('opt_showWFanalysis', False):\n return self.action_check_workflow(operationParams)\n else:\n ids=self._ids\n self.logging_workflow(ids, action, status)\n return self._action_to_perform(ids, operationParams, default)",
"def complete_catalog_upload_v0(self, catalog_id, upload_id, complete_upload_request_payload, **kwargs):\n # type: (str, str, CompleteUploadRequest_7b413950, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, Error_d660d58]\n operation_name = \"complete_catalog_upload_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'upload_id' is set\n if ('upload_id' not in params) or (params['upload_id'] is None):\n raise ValueError(\n \"Missing the required parameter `upload_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'complete_upload_request_payload' is set\n if ('complete_upload_request_payload' not in params) or (params['complete_upload_request_payload'] is None):\n raise ValueError(\n \"Missing the required parameter `complete_upload_request_payload` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/catalogs/{catalogId}/uploads/{uploadId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n if 'upload_id' in params:\n path_params['uploadId'] = params['upload_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'complete_upload_request_payload' in params:\n body_params = params['complete_upload_request_payload']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accepted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def main(upload, config):\n upload.obj = uploader.Uploader(config=config)",
"def test_upload(self):\n fake_file_name = 'fake_file_name'\n\n backend = self.test_init_valid()\n backend.upload(fake_file_name)\n\n backend.vault.concurrent_create_archive_from_file.assert_called_once_with(filename=fake_file_name, description='')",
"def file_upload():\n\n click.secho('*** Uploading image...', fg='green')\n uploaded = _uploaded_file('cover.jpg')\n click.secho(json.dumps(uploaded, indent=2, sort_keys=True), fg='yellow')\n\n click.secho('*** Creating a Picture document for it...', fg='green')\n picture = _make_document('picture', title='cover image', sys_filename=uploaded['path'])\n click.secho(json.dumps(picture, indent=2, sort_keys=True), fg='yellow')\n\n click.secho('*** Attaching it to a Blueray as cover...', fg='green')\n slp = _make_document('movie', title='Silver Linings Playbook')\n blueray = _make_document('blueray', movie_id=slp['_id'], cover_id=picture['_id'])\n click.secho(json.dumps(blueray, indent=2, sort_keys=True), fg='yellow')",
"def create_multipart_upload(ACL=None, Bucket=None, CacheControl=None, ContentDisposition=None, ContentEncoding=None, ContentLanguage=None, ContentType=None, Expires=None, GrantFullControl=None, GrantRead=None, GrantReadACP=None, GrantWriteACP=None, Key=None, Metadata=None, ServerSideEncryption=None, StorageClass=None, WebsiteRedirectLocation=None, SSECustomerAlgorithm=None, SSECustomerKey=None, SSECustomerKeyMD5=None, SSEKMSKeyId=None, SSEKMSEncryptionContext=None, RequestPayer=None, Tagging=None, ObjectLockMode=None, ObjectLockRetainUntilDate=None, ObjectLockLegalHoldStatus=None):\n pass",
"def upload():\n storeapps = APP.config[\"storage\"]\n binary = request.data\n\n # Add compatibility with POST requests\n if 'file' in request.files:\n binary = request.files['file'].read()\n\n logging.debug(\"Received file with size: %i\", len(binary))\n\n try:\n app = nativeapps.application.from_binary(binary)\n filepath = app.write(storeapps)\n return \"written: \" + filepath, 201 # 201 CREATED\n except nativeapps.application.InvalidApplicationError as exception:\n return exception, 400"
] | [
"0.6831696",
"0.64513546",
"0.63524556",
"0.6309491",
"0.61442155",
"0.6086827",
"0.6079612",
"0.6052322",
"0.6010462",
"0.5990453",
"0.59298205",
"0.58892775",
"0.58816016",
"0.5851181",
"0.58465827",
"0.58310765",
"0.5784714",
"0.57691616",
"0.5760394",
"0.5739012",
"0.57346",
"0.5724888",
"0.57106084",
"0.56926644",
"0.567371",
"0.564923",
"0.56297255",
"0.5616449",
"0.5608483",
"0.55817455"
] | 0.65958726 | 1 |
The SMAPI Audit Logs API provides customers with an audit history of all SMAPI calls made by a developer or developers with permissions on that account. | def query_development_audit_logs_v1(self, get_audit_logs_request, **kwargs):
# type: (AuditLogsRequest_13316e3e, **Any) -> Union[ApiResponse, object, Error_fbe913d9, AuditLogsResponse_bbbe1918, BadRequestError_f854b05]
operation_name = "query_development_audit_logs_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'get_audit_logs_request' is set
if ('get_audit_logs_request' not in params) or (params['get_audit_logs_request'] is None):
raise ValueError(
"Missing the required parameter `get_audit_logs_request` when calling `" + operation_name + "`")
resource_path = '/v1/developmentAuditLogs/query'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'get_audit_logs_request' in params:
body_params = params['get_audit_logs_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.audit_logs.audit_logs_response.AuditLogsResponse", status_code=200, message="Returns a list of audit logs for the given vendor."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Invalid request"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="Unauthorized"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=403, message="Forbidden"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="Not Found"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too Many Requests"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.audit_logs.audit_logs_response.AuditLogsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_auditlogs(self):\n res = self.get_object(\"/integrationServices/v3/auditlogs\")\n return res.get(\"notifications\", [])",
"def getAllActivityLog(self):\n url=self._v2BaseURL + \"/api/v2/activity/activityLog\"\n headers = {'Content-Type': \"application/json\", 'Accept': \"application/json\",\"icSessionID\":self._v2icSessionID}\n infapy.log.info(\"GetAllActivityLog URL - \" + url)\n infapy.log.info(\"API Headers: \" + str(headers))\n infapy.log.info(\"Body: \" + \"This API requires no body\")\n # The below format is for post\n # bodyV3={\"username\": userName,\"password\": password}\n # r3 = re.post(url=urlV3, json=bodyV3, headers=headers)\n try:\n response = re.get(url=url, headers=headers)\n infapy.log.debug(str(response.json()))\n except Exception as e:\n infapy.log.exception(e)\n raise\n infapy.log.info(\"Fetched the all the Activity log from IICS\")\n data = response.json()\n return data",
"def describe_audit_records(\n self,\n request: dds_20151201_models.DescribeAuditRecordsRequest,\n ) -> dds_20151201_models.DescribeAuditRecordsResponse:\n runtime = util_models.RuntimeOptions()\n return self.describe_audit_records_with_options(request, runtime)",
"def get_audit(self, query, session):\n raise NotImplementedError()",
"def test_getAuditLogsWithNoParams(self):\r\n logs = self.client.getAuditLogs()\r\n return logs",
"def loginAudit(self, params):\n\n sortLimitParams = self.setSortLimitParameters(params)\n \n filterObj = Q()\n\n if params.get('searchEmail'):\n user_ids = []\n users = WebUsers.objects.filter(mail__icontains=params.get('searchEmail'))\n for user in users:\n user_ids.append(user.uid)\n \n filterObj = filterObj & Q(created_by_id__in=user_ids)\n if params.get('searchIpAddress'):\n filterObj = filterObj & Q(ip_address__icontains=params.get('searchIpAddress'))\n if params.get('searchStartLoginDate'):\n filterObj = filterObj & Q(date_created__gte=params.get('searchStartLoginDate'))\n if params.get('searchEndLoginDate'):\n filterObj = filterObj & Q(date_created__lte=params.get('searchEndLoginDate'))\n if params.get('searchIds'):\n filterObj = filterObj & Q(id__in=params.get('searchIds').split(\",\"))\n\n result = LoginAudit.objects.filter(filterObj).order_by(sortLimitParams['dir'] + sortLimitParams['sort']) [sortLimitParams['start']: sortLimitParams['limit']]\n count = LoginAudit.objects.filter(filterObj).count()\n\n cursor = connection.cursor()\n records = []\n for item in result:\n record = {}\n \n record['id'] = item.id\n record['ip_address'] = item.ip_address\n record['login_date'] = item.date_created\n record['logout_date'] = item.logout_date\n #get the details of this user\n user = WebUsers.objects.get(uid=item.created_by_id)\n record['email'] = user.mail\n \n records.append(record)\n\n cursor.close()\n \n return {'totalCount': count, 'records': records}",
"def getAuditList(self, user_id=None, name=None, updated_at__gte=None, updated_at__lte=None, ip_address=None, device_name=None, folder=None, folder_id=None, sub_folder_file=None, action_type=None, recipient=None, permissions=None): \n # Queryset\n return self.handler.getAuditList(\n user_id=user_id,\n name__icontains=name,\n updated_at__date__gte=updated_at__gte,\n updated_at__date__lte=updated_at__lte,\n ip_address__icontains=ip_address,\n device_name__icontains=device_name,\n folder__icontains=folder,\n folder_id=folder_id,\n sub_folder_file__icontains=sub_folder_file,\n action_type=action_type,\n recipient__icontains=recipient,\n permissions=permissions).order_by('-updated_at')",
"def dwl_auditlog_entry_report(session):\n url = session.get_url('audit', 'dwl')\n\n req = re.Request('GET', url)\n\n return session.send_recv(req, 'Audit log entry report downloaded.')",
"def __get_incidents_history(date='*'):\n assert (date == '*' or datetime.strptime(date, \"%Y%m%d\") ), \"date must be of format YYYYMMDD!\"\n\n # Prepare the IN clause from WHITELIST_USERS. For e.g:\n # Convert: \"[email protected] AND [email protected]\" to \"'[email protected]', '[email protected]'\"\n IN_clause = map(lambda x: x.replace(' ', ''), WHITELIST_USERS.split('AND'))\n IN_clause = map(lambda x: '\\'{}\\''.format(x), IN_clause)\n IN_clause = ','.join(IN_clause)\n\n query1 = 'SELECT timestamp, resource.labels.project_id as project, protopayload_auditlog.authenticationInfo.principalEmail as offender, \\\n \\'IAM Policy Tampering\\' as offenceType FROM `{}.{}.cloudaudit_googleapis_com_activity_{}` \\\n WHERE resource.type = \"project\" AND protopayload_auditlog.serviceName = \"cloudresourcemanager.googleapis.com\" \\\n AND protopayload_auditlog.methodName = \"SetIamPolicy\"'.format(PROJECT_ID, LOGS_SINK_DATASET_ID, date)\n\n query2 = 'SELECT timestamp, resource.labels.project_id as project, protopayload_auditlog.authenticationInfo.principalEmail as offender, \\\n \\'Bucket Permission Tampering\\' as offenceType FROM `{}.{}.cloudaudit_googleapis_com_activity_{}` \\\n WHERE resource.type = \"gcs_bucket\" AND protopayload_auditlog.serviceName = \"storage.googleapis.com\" \\\n AND(protopayload_auditlog.methodName = \"storage.setIamPermissions\" OR protopayload_auditlog.methodName = \"storage.objects.update\")'.\\\n format(PROJECT_ID, LOGS_SINK_DATASET_ID, date)\n\n query3 = 'SELECT timestamp, resource.labels.project_id as project, protoPayload_auditlog.authenticationInfo.principalEmail as offender, \\\n \\'Unexpected Bucket Access\\' as offenceType FROM `{}.{}.cloudaudit_googleapis_com_data_access_{}` \\\n WHERE resource.type = \\'gcs_bucket\\' AND(protoPayload_auditlog.resourceName LIKE \\'%{}\\' OR \\\n protoPayload_auditlog.resourceName LIKE \\'%{}\\') AND protoPayload_auditlog.authenticationInfo.principalEmail \\\n NOT IN({})'.format(PROJECT_ID, LOGS_SINK_DATASET_ID, date, LOGS_BUCKET_ID, DATA_BUCKET_ID, IN_clause)\n\n final_query = '{} UNION DISTINCT {} UNION DISTINCT {} ORDER BY timestamp DESC'.format(query1, query2, query3)\n\n save_string(final_query, 'tmp_query.sql')\n\n run_command('bq query --use_legacy_sql=false < tmp_query.sql')\n\n # When done, remove the temp file.\n run_command('rm tmp_query.sql')",
"def getAuditListPage(self, user_id=None, name=None, updated_at__gte=None, updated_at__lte=None, ip_address=None, device_name=None, folder=None, folder_id=None, sub_folder_file=None, action_type=None, recipient=None, permissions=None, per_page = 10, **kwargs): \n # Queryset\n audit_log_list = self.getAuditList(\n user_id=user_id,\n name=name,\n updated_at__gte=updated_at__gte,\n updated_at__lte=updated_at__lte,\n ip_address=ip_address,\n device_name=device_name,\n folder=folder,\n folder_id=folder_id,\n sub_folder_file=sub_folder_file,\n action_type=action_type,\n recipient=recipient,\n permissions=permissions)\n # Pagination\n paginator = Paginator(audit_log_list, per_page)\n\n # return page object_list\n return paginator",
"def create_audit_log_for_request(response):\n try:\n method = flask.request.method\n endpoint = flask.request.path\n audit_data = getattr(flask.g, \"audit_data\", {})\n request_url = endpoint\n if flask.request.query_string:\n # could use `flask.request.url` but we don't want the root URL\n request_url += f\"?{flask.request.query_string.decode('utf-8')}\"\n\n if method == \"GET\" and endpoint.startswith(\"/data/download/\"):\n flask.current_app.audit_service_client.create_presigned_url_log(\n status_code=response.status_code,\n request_url=request_url,\n guid=endpoint[len(\"/data/download/\") :],\n action=\"download\",\n **audit_data,\n )\n elif method == \"GET\" and endpoint.startswith(\"/login/\"):\n request_url = _clean_authorization_request_url(request_url)\n if audit_data: # ignore login calls with no `username`/`sub`/`idp`\n flask.current_app.audit_service_client.create_login_log(\n status_code=response.status_code,\n request_url=request_url,\n **audit_data,\n )\n except Exception:\n # TODO monitor this somehow\n traceback.print_exc()\n logger.error(f\"!!! Unable to create audit log! Returning response anyway...\")\n\n return response",
"def getAuditListArray(self, user_id=None, name=None, updated_at__gte=None, updated_at__lte=None, ip_address=None, device_name=None, folder=None, folder_id=None, sub_folder_file=None, action_type=None, recipient=None, permissions=None, **kwargs): \n return self.getAuditList(\n user_id=user_id,\n name=name,\n updated_at__gte=updated_at__gte,\n updated_at__lte=updated_at__lte,\n ip_address=ip_address,\n device_name=device_name,\n folder=folder,\n folder_id=folder_id,\n sub_folder_file=sub_folder_file,\n action_type=action_type,\n recipient=recipient,\n permissions=permissions).values()",
"def audit_log(self, account_id):\n from pureport_client.commands.accounts.audit_log import Command\n return Command(self.client, account_id)",
"def req_auditlog_entry_report(session: ZIAConnector, startTime: str, endTime: str, page=None, pageSize=500,\n actionTypes: list = False, category: str = \"\", subcategories: list = False,\n actionResult: str = \"\", actionInterface: str = \"\", objectName=\"\", clientIP: str = \"\",\n adminName: str = \"\", targetOrgId: int = None, full=False):\n startTime = int(parse(timestr=startTime).timestamp()) * 1000 # Converting starttime to epoch\n endTime = int(parse(timestr=endTime).timestamp()) * 1000 # Converting endtime to epoch\n\n parameters = locals()\n url = session.get_url('audit', 'main')\n\n parameters = u.clean_args(parameters, 'session', 'full')\n\n return session.full_retrieval('POST', url, json_content=parameters, page_size=pageSize,\n message='Request to create audit log entry report sucessfully sent.', full=full)",
"def test_getAuditTrailsByDate(self):\n\n c = suds.client.Client(\n self.wsdl, username=self.username, password=self.password)\n\n # create a bunch of old Audit Trails, older than 1 hour\n event1_date = timezone.localtime(\n timezone.now()) - timedelta(days=3 * 365)\n self.createAuditTrail(date=event1_date)\n\n event2_date = timezone.localtime(timezone.now()) - timedelta(days=25)\n self.createAuditTrail(date=event2_date)\n\n event3_date = timezone.localtime(timezone.now()) - timedelta(days=151)\n self.createAuditTrail(date=event3_date)\n\n # take the date and time of today\n date = datetime.today().date()\n\n # and create an Audit Trail of right now\n event4_date = date - timedelta(hours=5)\n self.createAuditTrail(date=event4_date)\n\n # okay we got 4 ATs in the past, and 2 in the future.\n # If we now ask for ATs not older than 1 hour in the future, we\n # should only get the ones +1hr in the future.\n\n # login AT is created NOW, but we're asking for the future!\n soap_result = c.service.getAuditTrailsByDate(date)\n self.assertTrue(len(soap_result.AuditTrailComplexType) >= 3)\n\n # check results for correct user are returned\n [self.assertEqual(trail.user_id, self.user.id)\n for trail in soap_result.AuditTrailComplexType]\n # check ordering\n self.assertEqual(soap_result.AuditTrailComplexType[\n 0].date, soap_result.AuditTrailComplexType[1].date)\n # check max entries\n self.assertTrue(\n len(soap_result.AuditTrailComplexType) <= settings.SOAP_MAX_ENTRIES)",
"async def _get_auditresults(\n self,\n channel: TextChannel,\n start: datetime,\n end: Optional[datetime] = None,\n ) -> AuditResults:\n counter: int = 0\n name_set: MutableSet[str] = set()\n if end is None:\n history_cor = channel.history(after=start)\n else:\n history_cor = channel.history(after=start, before=end)\n\n async for past_message in history_cor:\n counter += 1\n name_set.add(\n f\"{past_message.author.display_name},{past_message.author},{past_message.author.id}\" # noqa\n )\n\n return AuditResults(\n counter=counter,\n channel=channel.name,\n channel_id=channel.id,\n authors=name_set,\n start=start,\n end=end,\n )",
"def getTenantAttributeUpdateAuditTrail(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def get(self, audit_uuid):\n audit = AuditResource.get_by_id(audit_uuid=audit_uuid, withContacts=True, withScans=True)\n return audit",
"async def describe_audit_records_async(\n self,\n request: dds_20151201_models.DescribeAuditRecordsRequest,\n ) -> dds_20151201_models.DescribeAuditRecordsResponse:\n runtime = util_models.RuntimeOptions()\n return await self.describe_audit_records_with_options_async(request, runtime)",
"def test_getRecentAuditTrailsByUsername(self):\n\n c = suds.client.Client(\n self.wsdl, username=self.username, password=self.password)\n result = c.service.getRecentAuditTrailsByUsername(self.user.username)\n self.assertTrue(len(result.AuditTrailComplexType) >= 2)\n\n [self.assertEqual(trail.user_id, self.user.id)\n for trail in result.AuditTrailComplexType]",
"async def view_audit_actions(self, ctx: Context) -> None:\n\n assert ctx.guild is not None # handle by `cog_check`\n\n if logging_info := (await typed_retrieve_query(\n self.bot.database,\n int,\n 'SELECT BITS FROM LOGGING WHERE GUILD_ID=?',\n (ctx.guild.id,))\n ):\n await ctx.send(embed=build_actions_embed(LoggingActions.all_enabled_actions((logging_info[0]))))\n else:\n await ctx.send('You must first set an audit channel before viewing audit actions.'\n '\\n_See `auditactions setchannel` for more information._')",
"def _save_logs(self):\n logger.info(\"Saving call logs\")\n data = [c.to_dict() for c in self.logs[:29]]\n tichy.Persistance('calls/logs').save(data)",
"def getTenantStatusUpdateAuditTrail(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def add_carton_activity_audit(self, carton_activity_id, carton_activity_audit, **kwargs):\n\n all_params = ['carton_activity_id', 'carton_activity_audit']\n all_params.append('callback')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method add_carton_activity_audit\" % key\n )\n params[key] = val\n del params['kwargs']\n\n # verify the required parameter 'carton_activity_id' is set\n if ('carton_activity_id' not in params) or (params['carton_activity_id'] is None):\n raise ValueError(\"Missing the required parameter `carton_activity_id` when calling `add_carton_activity_audit`\")\n # verify the required parameter 'carton_activity_audit' is set\n if ('carton_activity_audit' not in params) or (params['carton_activity_audit'] is None):\n raise ValueError(\"Missing the required parameter `carton_activity_audit` when calling `add_carton_activity_audit`\")\n\n resource_path = '/beta/cartonActivity/{cartonActivityId}/audit/{cartonActivityAudit}'.replace('{format}', 'json')\n path_params = {}\n if 'carton_activity_id' in params:\n path_params['cartonActivityId'] = params['carton_activity_id']\n if 'carton_activity_audit' in params:\n path_params['cartonActivityAudit'] = params['carton_activity_audit']\n\n query_params = {}\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.\\\n select_header_accept(['application/json'])\n if not header_params['Accept']:\n del header_params['Accept']\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.\\\n select_header_content_type(['application/json'])\n\n # Authentication setting\n auth_settings = ['api_key']\n\n response = self.api_client.call_api(resource_path, 'PUT',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type=None,\n auth_settings=auth_settings,\n callback=params.get('callback'))\n return response",
"def api_list_logs():\n if 'POST' == request.method:\n per_page = get_safe_int(request.form.get('per_page'))\n page_num = get_safe_int(request.form.get('page_num'))\n else:\n per_page = get_safe_int(request.args.get('per_page'))\n page_num = get_safe_int(request.args.get('page_num'))\n\n \"\"\"\n pagination = LogEntity.query.paginate(page_num, per_page, False)\n items = [i.serialize() for i in pagination.items]\n app.logger.debug(\"per_page: {}, page_num: {}\".format(per_page, page_num))\n return jsonify_success(dict(total_pages=pagination.pages,\n list_of_events=items))\n \"\"\"\n logs, total_pages = log_manager.get_logs(per_page, page_num)\n # logs_list = [x.to_visible() for x in logs]\n return jsonify_success(dict(list_of_events=logs, total_pages=total_pages))",
"def create_audit_records(self, status_records, session_key):\n uri = '/services/receivers/simple'\n getargs = {'index': '_audit', 'sourcetype': 'incident_review', 'output_mode': 'json'}\n # Double list-comprehension:\n # a. Comma-separate the fields in each record, replacing \"None\" with the\n # empty string\n # b. Newline-separate the records so that the incident_review sourcetype\n # can pick up the individual audit records via SHOULD_LINEMERGE=false.\n data = '\\n'.join([','.join([str(getattr(r, k)) if getattr(r, k) is not None else '' for k in self.DEFAULT_AUDIT_FIELD_ORDER]) for r in status_records])\n\n response, content = splunk.rest.simpleRequest(uri,\n sessionKey=session_key,\n method='POST',\n getargs=getargs,\n jsonargs=data)\n\n if response['status'] != str(httplib.OK):\n logger.error('HTTP error when auditing notable events: response=\"%s\"', response)\n return False\n else:\n parsed_content = json.loads(content)\n if len(data) != parsed_content['bytes']:\n # Some audit data was not received.\n logger.error('Audit records could not be created for some notable event updates: content=\"%s\"', content)\n return False\n\n return True",
"def activity_logs(self) -> api.ActivityLogs:\n return self._get_model(model=api.ActivityLogs)",
"def list_of_logs(self):\n log_line_obj = self.env['common.log.lines.ept']\n model_id = log_line_obj.get_model_id('amazon.vcs.tax.report.ept')\n records = log_line_obj.search(\n [('model_id', '=', model_id), ('res_id', '=', self.id)])\n action = {\n 'domain': \"[('id', 'in', \" + str(records.ids) + \" )]\",\n 'name': 'Mismatch Details',\n 'view_mode': 'tree',\n 'res_model': 'common.log.lines.ept',\n 'type': 'ir.actions.act_window',\n }\n return action",
"async def logs(\n self,\n *,\n latest: Optional[int] = None,\n oldest: Optional[int] = None,\n limit: Optional[int] = None,\n action: Optional[str] = None,\n actor: Optional[str] = None,\n entity: Optional[str] = None,\n additional_query_params: Optional[Dict[str, any]] = None,\n headers: Optional[Dict[str, str]] = None,\n ) -> AuditLogsResponse:\n query_params = {\n \"latest\": latest,\n \"oldest\": oldest,\n \"limit\": limit,\n \"action\": action,\n \"actor\": actor,\n \"entity\": entity,\n }\n if additional_query_params is not None:\n query_params.update(additional_query_params)\n query_params = {k: v for k, v in query_params.items() if v is not None}\n return await self.api_call(\n path=\"logs\",\n query_params=query_params,\n headers=headers,\n )",
"def enable_audit_monitoring():\n __enable_data_access_logging()\n __enable_log_streaming()\n __create_audit_alerts()\n __get_incidents_history()"
] | [
"0.629905",
"0.6203893",
"0.59034455",
"0.583267",
"0.57482004",
"0.56924",
"0.5659241",
"0.5658747",
"0.564397",
"0.56259894",
"0.5611631",
"0.5497883",
"0.54339087",
"0.5408425",
"0.53990036",
"0.53773606",
"0.53651124",
"0.53638005",
"0.53303605",
"0.53125095",
"0.52780914",
"0.52766985",
"0.5271919",
"0.5262109",
"0.52480674",
"0.5216508",
"0.52103204",
"0.5201075",
"0.51927",
"0.51892257"
] | 0.642645 | 0 |
Get the list of inskill products for the vendor. | def get_isp_list_for_vendor_v1(self, vendor_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListInSkillProductResponse_505e7307]
operation_name = "get_isp_list_for_vendor_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'vendor_id' is set
if ('vendor_id' not in params) or (params['vendor_id'] is None):
raise ValueError(
"Missing the required parameter `vendor_id` when calling `" + operation_name + "`")
resource_path = '/v1/inSkillProducts'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
if 'vendor_id' in params:
query_params.append(('vendorId', params['vendor_id']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'product_id' in params:
query_params.append(('productId', params['product_id']))
if 'stage' in params:
query_params.append(('stage', params['stage']))
if 'object_type' in params:
query_params.append(('type', params['object_type']))
if 'reference_name' in params:
query_params.append(('referenceName', params['reference_name']))
if 'status' in params:
query_params.append(('status', params['status']))
if 'is_associated_with_skill' in params:
query_params.append(('isAssociatedWithSkill', params['is_associated_with_skill']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse", status_code=200, message="Response contains list of in-skill products for the specified vendor and stage."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request. Returned when a required parameter is not present, badly formatted. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too many requests received."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error"))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list_products(self):\n url = self.base_url\n # TODO add filtering support when holvi api supports it\n obdata = self.connection.make_get(url)\n return ProductList(obdata, self)",
"def products(self):\n return list(Product.select())",
"def get_products(self):\n return [item.code for item in self._products]",
"def list_products(self):\n return self._make_get_request(self._urls['products'])",
"def source_products(self, uuid):\n return self._backend.source_products(uuid)",
"def products(self):\n response = requests.get(self._url(self._PRODUCTS_PATH), headers=self._headers)\n return response.json()",
"def products(self):\r\n return self._products",
"def get_all_products(self):\n\t\tpass",
"def products(self):\r\n return products.Products(self)",
"def products(self):\n return self._products",
"def get_products(self):\n con = dbcon()\n cur = con.cursor()\n cur.execute(\"SELECT * FROM products;\")\n res = cur.fetchall()\n if res:\n prdcts=[]\n for prodct_item in res:\n picked_prdct = {\n 'product_id':prodct_item[0],\n 'product_name':prodct_item[1],\n 'price':prodct_item[2],\n 'quantity':prodct_item[3]\n }\n prdcts.append(picked_prdct)\n return jsonify({\"Products\": prdcts}), 200\n return jsonify({\"message\":\"No products in store\"})",
"def get_products(self, query_args={}):\n endpoint = '/v3/educator/products'\n result = self.request(endpoint, query_args)\n\n products = []\n for data in result.response:\n # Dynamically load product instance.\n class_name = data.type.capitalize()\n product = Product.instance(class_name, data)\n products.append(product)\n\n return products",
"def ListProducts(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def get(self):\n return Products().get_all_products()",
"def products(self, start=None, limit=None):\r\n params = base.get_params(None, locals())\r\n url = '{0}/products'.format(self.get_url())\r\n return http.Request('GET', url, params), parsers.parse_json",
"def return_items(self):\n cur = self.cursor\n cur.execute(f\"SELECT * FROM {self.product_name}\")\n products = cur.fetchall()\n return products",
"def list_products(admin):\n fields = [\n \"id\",\n \"name\",\n \"price\",\n \"barcode\",\n \"active\",\n \"countable\",\n \"purchase_sum\",\n \"replenishment_sum\",\n \"balance_score\",\n \"revocable\",\n \"imagename\",\n \"tags\",\n \"creation_date\",\n ]\n\n query = QueryFromRequestParameters(Product, request.args, fields)\n result, content_range = query.result()\n products = convert_minimal(result, fields)\n for product in products:\n product[\"tags\"] = [t.id for t in product[\"tags\"]]\n response = jsonify(products)\n response.headers[\"Content-Range\"] = content_range\n return response",
"def get_products(self):\n page = 1\n out = []\n while True:\n resp = self.get_session().Product.find(limit=10,page=page)\n if not len(resp):\n return\n yield resp\n page += 1",
"def vendor_list():\n return ['nxos', 'eos', 'cumulus']",
"def getListOfProducts(self, *args):\n return _libsbml.Reaction_getListOfProducts(self, *args)",
"def get_all_products():\n data = order_obj.get_all_products()\n return data",
"def listProducts(self):\n response = self.productClient.list_products(parent=self.locationPath)\n return [ProductSearch.Product._fromResponse(self.productSearch, x) for x in response]",
"def get_product_list(include_details = True):\n \n json_obj = requests.get(api_base_url + 'products')\n products_list = json.loads(json_obj.content)['products']\n d = OrderedDict(zip([x.pop('product') for x in products_list], \n products_list))\n if include_details: return d\n return d.keys()",
"def get_product_ingredients(self, driver):\n pass",
"def product_vendor(request, id=None):\n data = {}\n error = {\n 'status': False,\n 'name': None,\n 'text': None,\n 'level': None,\n 'debug': None\n }\n limit, error = get_limit(request, error)\n\n try:\n product_list = Product.objects.filter(\n productpreparation__vendorproduct__vendor__id__exact=id)[:limit]\n except Exception as e:\n data['error'] = {\n 'status': True,\n 'name': 'Vendor Not Found',\n 'text': 'Vendor with id %s not found!' % id,\n 'level': 'Error',\n 'debug': \"{0}: {1}\".format(type(e).__name__, str(e))\n }\n data['products'] = []\n return HttpResponse(\n json.dumps(data),\n content_type=\"application/json\"\n )\n\n serializer = FreshSerializer()\n\n if not product_list:\n error = {\n \"status\": True,\n \"name\": \"No Products\",\n \"text\": \"No Products found\",\n \"level\": \"Information\",\n \"debug\": \"\"\n }\n\n data = {\n \"products\": json.loads(serializer.serialize(product_list)),\n \"error\": error\n }\n\n return HttpResponse(json.dumps(data), content_type=\"application/json\")",
"def get_influencer_products_v2(influencer_ids,\n parameters,\n page_size,\n db_only=False,\n limit=10):\n from debra.models import ProductModelShelfMap\n\n # updating influencers to list and moving it to parameters for ES query builder\n if type(influencer_ids) != list:\n influencer_ids = [influencer_ids, ]\n\n # storing influencer's id in parameters for query builder\n if influencer_ids:\n parameters['influencer_ids'] = influencer_ids\n\n # Retrieving page number for ES query\n try:\n page = int(parameters.get('page', 1))\n page -= 1\n except TypeError:\n page = 0\n\n if db_only:\n db_params = {}\n highlighted_product_ids, total = [], None\n else:\n # Getting list of post ids from ES depending on search parameters\n product_ids, highlighted_product_ids, total = es_product_query_runner_v2(parameters,\n page,\n page_size,\n highlighted_first=True)\n db_params = dict(product_model__id__in=product_ids,)\n if settings.DEBUG:\n print('* Item IDS: %s' % product_ids)\n print('* Highlighted item IDs: %s' % highlighted_product_ids)\n print('* Total items: %s' % total)\n\n items_from_db = ProductModelShelfMap.objects.filter(\n influencer__id__in=influencer_ids,\n img_url_feed_view__isnull=False,\n **db_params\n ).prefetch_related('product_model') # .order_by('-product_model__insert_date')\n\n # list of ids for ProductModelShelfMap, not for product_model get from ES\n highlighted_items_ids = []\n\n if db_only:\n items = items_from_db[:limit]\n else:\n # sorting posts by list of ids from ES\n items = dict()\n for item in items_from_db:\n items[item.product_model.id] = item\n if item.product_model.id in highlighted_product_ids:\n highlighted_items_ids.append(item.id)\n\n items = [items[product_id] for product_id in product_ids if product_id in items]\n\n items_data = serialize_items_data_v2(items, highlighted_items_ids)\n\n return items_data, len(items_data)",
"def get_vendors_and_products_seen(cls, cb):\n url = \"/device_control/v3/orgs/{0}/products\".format(cb.credentials.org_key)\n resp = cb.get_object(url)\n return resp.get(\"results\", [])",
"def ListProducts(self):\n return copy.deepcopy(self._products)",
"def fetch_all_products():\n products = []\n client = ProductsClient()\n for product in client.get_products():\n products.append(Product(\n base_currency=product[0],\n quote_currency=product[1],\n ))\n return products",
"def see_products_for_rent_handler():\n\n products = ShowProductsAndCustomers()\n my_list = products.see_products_for_rent()\n my_result_list = []\n for product in my_list:\n my_result_list.append(product)\n print(product)\n return my_result_list"
] | [
"0.6733137",
"0.6547819",
"0.65187454",
"0.648127",
"0.63539016",
"0.6321409",
"0.6284851",
"0.62413895",
"0.62055516",
"0.61503416",
"0.6140966",
"0.61330837",
"0.6085362",
"0.6000095",
"0.5997312",
"0.59685934",
"0.5965533",
"0.592143",
"0.5869935",
"0.58443815",
"0.58426744",
"0.583679",
"0.5804229",
"0.5802333",
"0.5801858",
"0.5768896",
"0.5768242",
"0.57552826",
"0.57524866",
"0.57437027"
] | 0.66241527 | 1 |
Creates a new inskill product for given vendorId. | def create_isp_for_vendor_v1(self, create_in_skill_product_request, **kwargs):
# type: (CreateInSkillProductRequest_816cf44b, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ProductResponse_b388eec4, BadRequestError_f854b05]
operation_name = "create_isp_for_vendor_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'create_in_skill_product_request' is set
if ('create_in_skill_product_request' not in params) or (params['create_in_skill_product_request'] is None):
raise ValueError(
"Missing the required parameter `create_in_skill_product_request` when calling `" + operation_name + "`")
resource_path = '/v1/inSkillProducts'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_in_skill_product_request' in params:
body_params = params['create_in_skill_product_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.isp.product_response.ProductResponse", status_code=201, message="Success."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request. Returned when a required parameter is not present, badly formatted. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too many requests received."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error"))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.isp.product_response.ProductResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_product(self):\n product = self.product_obj.create({\n \"default_code\": 'A2330',\n \"product_tmpl_id\":\n self.ref(\"product.product_product_4_product_template\"),\n \"attribute_value_ids\": [(6, 0, [\n self.ref('product.product_attribute_value_1'),\n self.ref('product_lifecycle.product_attribute_value_6'),\n self.ref('product.product_attribute_value_5')])],\n \"replacement_product_ids\": [(\n 6, 0, [self.ref('product_lifecycle.product_product_4e')]\n )]})\n return product",
"def create_skill_for_vendor_v1(self, create_skill_request, **kwargs):\n # type: (CreateSkillRequest_92e74e84, **Any) -> Union[ApiResponse, object, CreateSkillResponse_2bad1094, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_skill_for_vendor_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'create_skill_request' is set\n if ('create_skill_request' not in params) or (params['create_skill_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_skill_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_skill_request' in params:\n body_params = params['create_skill_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.create_skill_response.CreateSkillResponse\", status_code=202, message=\"Accepted; Returns a URL to track the status in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.create_skill_response.CreateSkillResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def post(self):\n post_data = api_parser.parse_args()\n\n # Check if the product sku exits,\n # if it exits then throw an error,\n # else create one.\n product = Product.query.filter(Product.sku == post_data['sku']).first()\n if product:\n abort(400, description='Product Exists')\n\n product = Product()\n product.name = post_data['name']\n product.sku = post_data['sku']\n product.description = post_data.get('description')\n product.is_active = post_data.get('is_active', True)\n db.session.add(product)\n db.session.commit()\n\n return marshal(product, product_fields), 201",
"def __init__(self, vendor_id, product_id):\n self.vendor_id = vendor_id\n self.product_id = product_id",
"def register_product(p: Product) -> ExecRet:\n market = get_market()\n pid = p.pid\n if pid in market.products.keys():\n return ExecRet.err(message='pid %d already exists' % pid)\n market.add_product(p)\n LOGGER.info('added product %s' % p.json())\n return ExecRet.ok()",
"def add_product(cust_id,wishlist_id,pid):\n # \"\"\" Add product ID to a wishlist \"\"\"\n # TODO add products changes as well, for now just asses the wishlists\n if Customer.check_custid(cust_id):\n message = Customer.find_by_id(cust_id,wishlist_id)\n if message:\n result = Customer.addProduct(cust_id,wishlist_id,pid)\n res = Customer.find_by_id(cust_id,wishlist_id)\n return make_response(jsonify(res), status.HTTP_200_OK)\n else:\n message = {'Error': 'Wishlist with given ID not found'}\n return make_response(jsonify(message), status.HTTP_404_NOT_FOUND)\n else:\n message = {'Invalid' : 'Invalid customer ID'}\n return make_response(jsonify(message), status.HTTP_404_NOT_FOUND)",
"def create_item(self, obj):\n logger.info('ItemProduct adding item initiated')\n try:\n with Transaction().start(DBNAME, 1) as transaction:\n unit, = self.ProductUom.search([('name', '=', obj['units'])])\n template = self.ProductTemplate()\n try:\n if self.Product.search([('code', '=', obj['id']), ('description', '=', 'Stock'),\n ('type', '=', 'goods')])[-1]:\n return False\n except Exception:\n pass\n template.category = self.ProductCategory.search([('name', '=', obj['category'])])[-1]\n template.default_uom = unit\n template.purchase_uom = unit\n template.type = 'goods'\n rate = Decimal(obj['rate'])\n cost = rate / 2\n template.name = obj['name']\n template.list_price = Decimal(rate)\n template.cost_price = Decimal(cost)\n template.purchasable = True\n template.account_expense = self.accounts['expense']\n template.account_receivable = self.accounts['receivable']\n template.save()\n # transaction.cursor.commit()\n product = self.Product()\n product.template = template\n product.code = obj['id']\n product.description = 'Stock'\n product.save()\n transaction.cursor.commit()\n return True\n except Exception:\n if settings.level == 10:\n logger.exception('raised exception')\n return False",
"def add_product(self):\n self.owner.new_product(self.barcode, self.description, self.price, self._add_product_callback)",
"def create_product(new_product, owner_name):\n if not isinstance(new_product, dict):\n raise ValueError(f\"New product {new_product} is not a dict\")\n new_instance = Products(\n serial_number=new_product['serial_number'],\n type_name=new_product['type_name'],\n owner_name=owner_name,\n product_condition=new_product['product_condition'] == 'true',\n model=new_product['model'],\n producent=new_product['producent'],\n additonal_info=new_product['additional_info'],\n )\n if not get_critical_level(owner_name, [new_product['type_name']]).all():\n new_critical_entry = CriticalLevels(\n business=owner_name,\n type_name=new_product['type_name']\n )\n else:\n new_critical_entry = None\n return new_instance, new_critical_entry",
"def get_isp_list_for_vendor_v1(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListInSkillProductResponse_505e7307]\n operation_name = \"get_isp_list_for_vendor_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'product_id' in params:\n query_params.append(('productId', params['product_id']))\n if 'stage' in params:\n query_params.append(('stage', params['stage']))\n if 'object_type' in params:\n query_params.append(('type', params['object_type']))\n if 'reference_name' in params:\n query_params.append(('referenceName', params['reference_name']))\n if 'status' in params:\n query_params.append(('status', params['status']))\n if 'is_associated_with_skill' in params:\n query_params.append(('isAssociatedWithSkill', params['is_associated_with_skill']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse\", status_code=200, message=\"Response contains list of in-skill products for the specified vendor and stage.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def add_product(product_dict):\n product = models.Product(**product_dict)\n app.session.merge(product)\n app.session.commit()",
"def create_product():\n mongo = MongoClient(Config.MONGO_URI)\n db_operations = mongo.db.product\n data = request.get_json(force=True) or {}\n if 'title' not in data or 'description' not in data or 'params' not in data:\n return bad_request(t['empty_field'])\n new_product = Product()\n if Product.params_is_valid(data):\n new_product.save_to_db(data, db_operations)\n\n response = jsonify(new_product.to_dict())\n response.status_code = 201\n response.headers['Location'] = url_for('api.get_product_by_id', product_id=new_product._id)\n return response\n else:\n return bad_request(t['invalid_value'])",
"def create_provision_product(product_name: str, pp_name: str, pa_id: str, client: boto3.client, params=None, tags=None) -> dict:\n if params is None:\n params = []\n if tags is None:\n tags = []\n logging.info(f\"Creating pp_id:{pp_name} with ProvisionArtifactId:{pa_id} in ProductName:{product_name}\")\n logging.info(f\"Parameters used:{params}\")\n re = client.provision_product(\n ProductName=product_name,\n ProvisionedProductName=pp_name,\n ProvisioningArtifactId=pa_id,\n ProvisioningParameters=params,\n Tags=tags\n )\n logging.info(re)\n return re",
"def vendor_id(self, vendor_id):\n\n self._vendor_id = vendor_id",
"def associate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"associate_isp_with_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def vendorid(self, vendorid):\n\n self._vendorid = vendorid",
"def create(cls, **kwargs):\n response = cls.get_client().create_product(**kwargs)\n object_details = cls._flatten_object_details(response)\n return cls(**object_details)",
"def sli_create(obj, product_name, sli_file):\n client = get_client(obj)\n\n product = client.product_list(name=product_name)\n if not product:\n fatal_error('Product {} does not exist'.format(product_name))\n\n product = product[0]\n\n with Action('Creating SLI for product: {}'.format(product_name), nl=True) as act:\n sli = json.load(sli_file)\n\n validate_sli(obj, sli, act)\n\n if not act.errors:\n res = client.sli_create(product, sli['name'], sli['unit'], sli['source'])\n print(json.dumps(res, indent=4))",
"def add_new_product():\n name = request.args.get(\"name\")\n email = request.args.get(\"email\")\n description = request.args.get(\"description\")\n price = request.args.get(\"price\")\n recommended = request.args.get(\"recommended\", default=\"n\")\n funcs.add_product(name, price, description, recommended, email)\n return json.dumps({'success': True}), 200, {'ContentType': 'application/json'}",
"def post(self):\n products = get_products()\n data = request.get_json(force=True)\n product_id = len(products) + 1\n product_name = data[\"product_name\"]\n category = data[\"category_id\"]\n stock_amount = data[\"stock_amount\"]\n price = data['price']\n inventory_stock = data['low_inventory_stock']\n\n\n product = [product for product in products if product.product_name\n == request.json['product_name']]\n\n if (not request.json or \"product_name\" not in request.json):\n return make_response(jsonify({'Error': \"Request Not found\"}), 404)# Not Found\n\n if type(request.json['stock_amount'])not in [int, float]:\n return make_response(\n jsonify({\"Error\": \"Require int or float type\"}))\n\n new_product = {\n \"product_id\": product_id,\n \"product_name\": product_name,\n \"category_id\": category,\n \"stock_amount\": stock_amount,\n \"price\": price,\n \"low_inventory_stock\": inventory_stock\n }\n\n product_schema = ProductsSchema()\n new_product_detail = product_schema.load_object_into_schema(new_product)\n new_pro = Products(**new_product_detail)\n new_pro.save()\n return make_response(jsonify({\"New Product\": new_product}), 201) #Created",
"def create_product(admin):\n data = json_body()\n required = {\"name\": str, \"price\": int, \"tags\": list}\n optional = {\n \"barcode\": str,\n \"active\": bool,\n \"countable\": bool,\n \"revocable\": bool,\n \"imagename\": str,\n }\n\n # Check all required fields\n check_fields_and_types(data, required, optional)\n\n # Check if a product with this name already exists\n if Product.query.filter_by(name=data[\"name\"]).first():\n raise exc.EntryAlreadyExists()\n\n # Check if a product with this barcode already exists\n if \"barcode\" in data:\n if Product.query.filter_by(barcode=data[\"barcode\"]).first():\n raise exc.EntryAlreadyExists()\n\n # Check the product tags\n tags = data[\"tags\"]\n for tag_id in tags:\n if not isinstance(tag_id, int):\n raise exc.WrongType\n tag = Tag.query.filter_by(id=tag_id).first()\n if not tag:\n raise exc.EntryNotFound\n\n del data[\"tags\"]\n\n # Save the price and delete it from the data dictionary\n price = int(data[\"price\"])\n del data[\"price\"]\n\n try:\n product = Product(**data)\n product.created_by = admin.id\n db.session.add(product)\n db.session.flush()\n product.set_price(price=price, admin_id=admin.id)\n for tag_id in tags:\n tag = Tag.query.filter_by(id=tag_id).first()\n product.tags.append(tag)\n\n db.session.commit()\n except IntegrityError:\n raise exc.CouldNotCreateEntry()\n\n return jsonify({\"message\": \"Created Product.\"}), 201",
"def add_product(self, product_uid, userid=None, **kw):\n\n context = resolve_uid(product_uid)\n if context is None:\n raise ValueError('Product {} not found.'.format(product_uid))\n purchase_handler = IPurchaseHandler(context)\n\n needs_checkout = False\n if userid is None:\n userid = get_current_userid()\n\n cart_items = purchase_handler.get_cart_items(**kw)\n\n for lineitem_info in cart_items:\n lineitem_info['user'] = userid\n cart_id = lineitem_info['uid'] + '_' + (userid or '')\n if kw:\n cart_id += '_' + sha1(\n json.dumps(kw, sort_keys=True)).hexdigest()\n\n lineitem = LineItem(self, cart_id, lineitem_info)\n\n # If item is free, complete \"purchase\" immediately\n # rather than adding to cart.\n if not lineitem.price:\n purchase_handler.after_purchase(lineitem_info)\n continue\n else:\n needs_checkout = True\n\n # Update cart\n if cart_id in self._items:\n self[cart_id].quantity += 1\n else:\n self._items[cart_id] = lineitem_info\n\n # Make sure changes are persisted\n self.save()\n return needs_checkout",
"def post(self):\n data = request.json\n new_product = ProductModel(**data)\n new_product.save()\n response_object = {\n 'status': 'success',\n 'message': 'Product successfully created.',\n 'product_id': new_product.id\n }\n return response_object, 201",
"def createProduct(self):\n return _libsbml.Model_createProduct(self)",
"def put(self, product_id):\n data = Product.parser.parse_args()\n product = ProductModel.find_by_id(product_id)\n\n if product is None:\n if data['name'] and data['price']:\n product = ProductModel(**data)\n product.save_to_db()\n else:\n return {'message': \"This product doesn't exist, you should enter all data to create one\"}, 404\n else:\n product.name = data['name'] if data['name'] else product.name\n product.price = data['price'] if data['price'] else product.price\n\n product.save_to_db()\n\n return product.to_json()",
"def put(self, sku, page=None):\n put_data = api_parser.parse_args()\n product = Product.query.filter(Product.sku == put_data['sku']).first_or_404()\n product.name = put_data['name']\n product.description = put_data.get('description')\n product.is_active = put_data.get('is_active')\n db.session.add(product)\n db.session.commit()\n\n return marshal(product, product_fields), 200",
"def add_product(self, name, cost, stock, location):\n\n cur.execute(\"\"\"INSERT INTO catalogue(vendorname, productname, unitcost, stock, location) \n VALUES (?, ?, ?, ?, ?)\"\"\", (self.vendorname, name, cost, stock, location))",
"def product_vendor(request, id=None):\n data = {}\n error = {\n 'status': False,\n 'name': None,\n 'text': None,\n 'level': None,\n 'debug': None\n }\n limit, error = get_limit(request, error)\n\n try:\n product_list = Product.objects.filter(\n productpreparation__vendorproduct__vendor__id__exact=id)[:limit]\n except Exception as e:\n data['error'] = {\n 'status': True,\n 'name': 'Vendor Not Found',\n 'text': 'Vendor with id %s not found!' % id,\n 'level': 'Error',\n 'debug': \"{0}: {1}\".format(type(e).__name__, str(e))\n }\n data['products'] = []\n return HttpResponse(\n json.dumps(data),\n content_type=\"application/json\"\n )\n\n serializer = FreshSerializer()\n\n if not product_list:\n error = {\n \"status\": True,\n \"name\": \"No Products\",\n \"text\": \"No Products found\",\n \"level\": \"Information\",\n \"debug\": \"\"\n }\n\n data = {\n \"products\": json.loads(serializer.serialize(product_list)),\n \"error\": error\n }\n\n return HttpResponse(json.dumps(data), content_type=\"application/json\")",
"def add_product(self, name, energy_points):\n now = datetime.datetime.now()\n date = \"{}-{}-{}\".format(now.year, now.month, now.day)\n Product(productName=name, energyPoints=energy_points, date=date)",
"def add_product(self, label):\n print('Adding product:', label)\n client = self.application.__init_blockchain_client__()\n response = client.addProduct(label)\n client.close()\n\n return response"
] | [
"0.57748955",
"0.5632701",
"0.55772245",
"0.5560756",
"0.55527693",
"0.55176973",
"0.544083",
"0.5436239",
"0.54329205",
"0.54200816",
"0.5348453",
"0.53069866",
"0.5295919",
"0.5220665",
"0.52175814",
"0.5196625",
"0.5183925",
"0.5162375",
"0.5140223",
"0.5136836",
"0.5110529",
"0.51100636",
"0.5102616",
"0.5100634",
"0.5072105",
"0.5071314",
"0.50561225",
"0.5051242",
"0.5023439",
"0.50215584"
] | 0.66890377 | 0 |
Associates an inskill product with a skill. | def associate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "associate_isp_with_skill_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError(
"Missing the required parameter `product_id` when calling `" + operation_name + "`")
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'product_id' in params:
path_params['productId'] = params['product_id']
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request. Returned when a required parameter is not present, badly formatted. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="Request is forbidden."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="Requested resource not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too many requests received."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error"))
api_response = self.invoke(
method="PUT",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def addSkill(self, newskill):\n self.skills.append( newskill )",
"def new_skill_interaction(self, skill):\n self.skill_interact[skill] = True",
"def addSkill(self, skillName, maxLevel, creditStart, creditIncrement):\r\n self.skills[skillName] = SkillObject(skillName, maxLevel, creditStart, creditIncrement)\r\n self.orderedSkills.append(skillName)",
"def addSkill(skill, db, **kwargs):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if skill_data:\n return colored(\"ERROR: Skill {S} is already in the skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n db.execute(\n 'INSERT INTO mystatus (skill, power, points)'\n 'VALUES (?, ?, ?)', (str(skill), str(kwargs['power']), \"0\"))\n db.commit()\n return colored(\"Add new skill: \" + str(skill), 'cyan')",
"def add_skill(skill_list, skill): #inputs the skill dictionary and skill\r\n\tif skill==\"Gun Combat\":\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in guns:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\t\telse:\r\n\t\t\t\t\tskill=stellagama.random_choice(guns)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(guns)\r\n\telif skill in [\"Blade Combat\", \"Blade Cbt\"]:\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in melee:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\t\telse:\r\n\t\t\t\t\tskill=stellagama.random_choice(melee)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(melee)\r\n\telif skill==\"Vehicle\":\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in vehicles:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\telse:\r\n\t\t\t\tskill=stellagama.random_choice(vehicles)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(vehicles)\r\n\tif skill in skill_list:\r\n\t\tskill_list[skill] += 1\r\n\telif skill not in skill_list:\r\n\t\tskill_list[skill] = 1\r\n\treturn skill_list #outputs the skill dictionary\r",
"def _set_skill(caller, _, **kwargs):\n pool = _skill_pool(caller, kwargs.get(\"skill\"))\n caller.db.d1_skills[kwargs.get(\"skill\")][\"rank\"] += 1\n caller.ndb.pregen[\"skills\"] = pool\n\n return \"node_skills\"",
"def product(self, product):\n self._product = product",
"async def skill(self, ctx, *, skill: str):\n\n try:\n skill = self.get_entry('Skill', skill.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = skill['Name']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://skill.png')\n embed.add_field(name='Learned', value=skill['Class/Rank'], inline=False)\n embed.add_field(name='Effect', value=skill['Effect'])\n\n await ctx.send(file=discord.File(f'xenox/skills/{name}.png', 'skill.png'), embed=embed)",
"def use_skill(self, g, i, x, y):\n # @ param g a reference to the game engine\n # @ param i the index of the skill (basically what skill)\n # @ param x the x target coordinate in game pixels\n # @ param y the y target coordinate in game pixels\n if self.attackTimer < self.attackDelay:\n print(\"attack on CD\")\n return\n \n if self.skill[i].skillAttr == 0:\n g.fire_skill_sound.play()\n elif self.skill[i].skillAttr == 1:\n g.ice_skill_sound.play()\n elif self.skill[i].skillAttr == 2:\n g.lightning_skill_sound.play()\n elif self.skill[i].skillAttr == 3:\n g.poison_skill_sound.play()\n \n \n if self.skill[i].skillKey == 0: #Aura\n #turn the aura on/off\n if self.skill[i].active == False:\n #print(\"aura on\")\n self.skill[i].active = True\n else:\n self.skill[i].active = False\n #print(\"aura off\")\n \n elif self.skill[i].skillKey == 1: #Missile\n if self.mana[0] > self.skill[i].skillCost:\n self.mana[0] -= self.skill[i].skillCost\n self.attackTimer = 0\n target = Target(x, y)\n center_x = self.rect.x + (self.rect.width / 2)\n center_y = self.rect.y + (self.rect.height / 2)\n #bullet types: fire 5, ice 6, lightning 7\n #skill types: fire 0, ice 1, lightning 2\n g.bullets.append(self.bulletFactory.createBullet(g, self.skill[i].skillAttr + 5, 0, self.attack, 1024, target, center_x, center_y))\n #print(\"missile\")\n\n elif self.skill[i].skillKey == 2: #Breath\n #for each creep in the AoE cone, do damage.\n if self.mana[0] > self.skill[i].skillCost:\n self.mana[0] -= self.skill[i].skillCost\n self.attackTimer = 0\n #get low and high angle (-45 degrees and +45 degrees from player -> point angle)\n lowAngle = math.atan2(y - self.rect.centery, x - self.rect.centerx) - 3.1415 / 2.0\n highAngle = math.atan2(y - self.rect.centery, x - self.rect.centerx) + 3.1415 / 2.0\n for creep in g.creeps:\n #get angle to creep\n creepAngle = math.atan2(creep.rect.centery - self.rect.centery, creep.rect.centerx - self.rect.centerx)\n \n #if angle to the creep is between the two angles\n if creepAngle > lowAngle and creepAngle < highAngle:\n #and the distance to the creep is below the skill's range\n if ( (creep.rect.centerx - self.rect.centerx) ** 2 + (creep.rect.centery - self.rect.centery) ** 2 ) ** 0.5 < 4 * 24:\n creep.take_damage( self.attack )\n #print(\"breath\")\n #apply debuffs, based on type\n if self.skill[i].skillAttr == 0: #fire\n creep.applyBurning()\n elif self.skill[i].skillAttr == 1: #frost\n creep.applyChilled()\n elif self.skill[i].skillAttr == 2: #lightning\n creep.applyShocked()",
"def add_product(usr, guid, toolkit):\n if toolkit == 'add':\n graph.run(f\"MATCH (x:Toolkit), (y:Product) \"\n f\"WHERE x.guid='{tk_guid}' \"\n f\"AND y.guid='{guid}' \"\n f\"MERGE (x)-[r:is_using]->(y)\")\n else:\n pass",
"def product(self, product):\n\n self._product = product",
"def product(self, product):\n\n self._product = product",
"def add_product(product_dict):\n product = models.Product(**product_dict)\n app.session.merge(product)\n app.session.commit()",
"def setSkillInfo(self, name, information):\r\n skills[name].info = information",
"def skill(ctx: Context, public_id: PublicId):\n _eject_item(ctx, \"skill\", public_id)",
"def upgrade_skill(self, skill_string):\r\n skill = self.__skills[skill_string]\r\n skill.skill_level += 1\r\n\r\n # Downgrading enabled the first time a skill is upgraded.\r\n if skill.skill_level == 1:\r\n self.skill_down_enable(skill_string)\r\n\r\n # Updates the UI and skill point value\r\n self.update_skill_level_info(skill_string)\r\n self.deduct_skill_points(skill.points_to_up)\r\n self.update_skill_info_box(skill_string)\r\n\r\n # Checks other requirements.\r\n for skill_string2 in self.__skills:\r\n self.check_skill_requirements(skill_string2)",
"def insert(self, product):\n pass",
"def add(self, product):\n pass",
"def add(self, product, qty):\n product_id = str(product.id)\n\n if product_id in self.basket:\n self.basket[product_id]['qty'] = qty\n else:\n self.basket[product_id] = {'price': str(product.price), 'qty': qty}\n\n self.save()",
"def add_skills_to_profile():\n # get specific objects\n profile = storage.get(\"Profile\", profile_id)\n skills = storage.get(\"Skills\", skills_id)\n if profile is not None and skills is not None:\n # check every skill in profile\n for profile_skill in profile.skills:\n # if the given skill is already linked to profile, return\n if profile_skill.id == skills.id:\n return jsonify(skills.to_dict()), 200\n # if skill is not in profile, append skill and save\n profile.skills.append(skills)\n profile.save()\n return jsonify(skills.to_dict()), 201\n\n # if id not in database, abort\n abort(404)",
"def create_isp_for_vendor_v1(self, create_in_skill_product_request, **kwargs):\n # type: (CreateInSkillProductRequest_816cf44b, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ProductResponse_b388eec4, BadRequestError_f854b05]\n operation_name = \"create_isp_for_vendor_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'create_in_skill_product_request' is set\n if ('create_in_skill_product_request' not in params) or (params['create_in_skill_product_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_in_skill_product_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_in_skill_product_request' in params:\n body_params = params['create_in_skill_product_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.product_response.ProductResponse\", status_code=201, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.product_response.ProductResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def add(self, product):\n product_id = str(product.id)\n self.wishlist[product_id] = {'price': str(product.price)}\n self.save()",
"def register_product(p: Product) -> ExecRet:\n market = get_market()\n pid = p.pid\n if pid in market.products.keys():\n return ExecRet.err(message='pid %d already exists' % pid)\n market.add_product(p)\n LOGGER.info('added product %s' % p.json())\n return ExecRet.ok()",
"def add_product(self):\n self.owner.new_product(self.barcode, self.description, self.price, self._add_product_callback)",
"def update(self, product, qty):\n product_id = str(product)\n if product_id in self.basket:\n self.basket[product_id]['qty'] = qty\n self.save()",
"def target_product(self, target_product):\n\n self._target_product = target_product",
"def modifySkill(skill, db, pwr):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if not skill_data:\n return colored(\"ERROR: Skill {S} is not in your skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n pwr = int(pwr)\n if pwr < 0:\n return colored(\"ERROR: Power value should alwasy be positive.\", \"red\", \"on_white\")\n db.execute(\n 'UPDATE mystatus SET power = ? WHERE skill = ?', (str(pwr), str(skill)))\n db.commit()\n return colored(\"{S}\\' power is modified from {OLD} -> {NEW}\".format(\n S=str(skill), OLD=str(skill_data['power']), NEW=str(pwr)), 'cyan')",
"def add(self, product, product_qty):\n product_id = str(product.id)\n if product_id in self.cart:\n self.cart[product_id][\"qty\"] = product_qty\n else:\n self.cart[product_id] = {'price': str(product.price), 'qty':int(product_qty)}\n self.save()",
"def disassociate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"disassociate_isp_with_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def associate_catalog_with_skill_v0(self, skill_id, catalog_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, Error_d660d58]\n operation_name = \"associate_catalog_with_skill_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/skills/{skillId}/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None"
] | [
"0.6838665",
"0.6528498",
"0.63352215",
"0.6299897",
"0.62301195",
"0.6225925",
"0.59248406",
"0.58860654",
"0.5864585",
"0.5812439",
"0.5810612",
"0.5810612",
"0.57910365",
"0.57557166",
"0.5713672",
"0.57069767",
"0.56912553",
"0.55998117",
"0.55106634",
"0.55091727",
"0.5496832",
"0.5477622",
"0.54737896",
"0.5444919",
"0.53847826",
"0.5316113",
"0.5300943",
"0.5291275",
"0.52731884",
"0.5270824"
] | 0.6781893 | 1 |
Resets the entitlement(s) of the Product for the current user. | def reset_entitlement_for_product_v1(self, product_id, stage, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "reset_entitlement_for_product_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError(
"Missing the required parameter `product_id` when calling `" + operation_name + "`")
# verify the required parameter 'stage' is set
if ('stage' not in params) or (params['stage'] is None):
raise ValueError(
"Missing the required parameter `stage` when calling `" + operation_name + "`")
resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}/entitlement'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'product_id' in params:
path_params['productId'] = params['product_id']
if 'stage' in params:
path_params['stage'] = params['stage']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request. Returned when a required parameter is not present, badly formatted. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="Request is forbidden."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="Requested resource not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=412, message="Precondition failed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too many requests received."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error"))
api_response = self.invoke(
method="DELETE",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def reset_user(self):\n\n if self.resin.auth.is_logged_in():\n self.wipe_application()\n self.resin.models.key.base_request.request(\n 'user__has__public_key', 'DELETE',\n endpoint=self.resin.settings.get('pine_endpoint'), login=True\n )",
"def clear_products(self):\n self.product_displays.clear()",
"def products(self, products):\n\n self._products = products",
"def products(self, products):\n\n self._products = products",
"def free_resources(self, context):\n self.update_available_resource(context.elevated())",
"def reset(self):\n super().reset()\n self.policy.reset()",
"def reset(self):\n super().reset()\n self.policy.reset()",
"def product_groups(self, product_groups):\n\n self._product_groups = product_groups",
"def product(self, product):\n\n self._product = product",
"def product(self, product):\n\n self._product = product",
"def product(self, product):\n self._product = product",
"def resetUser(self):\n\t\turl = \"https://habitica.com/api/v4/user/reset\"\n\t\treturn(postUrl(url, self.credentials))",
"def revoke(self):\n # Set the application as unsucessful with the current datetime\n self.status = self.Status.REVOKED\n self.revoked_datetime = timezone.now()\n\n # Removes credentialing from the user\n self.user.is_credentialed = False\n self.user.credential_datetime = None\n\n with transaction.atomic():\n self.user.save()\n self.save()\n\n logger.info('Credentialing for user {0} has been removed.'.format(\n self.user.email))",
"def reset_all(self):\r\n for skill_string in self.__skills:\r\n self.reset(skill_string)\r\n self.check_skill_requirements(skill_string)",
"def resetSkills(self):\r\n \"\"\" Reset the default attributes \"\"\"\r\n self.player['level'] = 1\r\n self.player['xp'] = 0\r\n self.player['credits'] = int(startCredits)\r\n self.player['popup'] = int(popupStatus)\r\n self.player['name'] = self.player.name\r\n self.player['lastconnected'] = int(time.time())\r\n\r\n \r\n \"\"\" Iterate through the skills list then set each skill to 0 \"\"\"\r\n for skill in skills:\r\n self.player[skill.name] = 0\r\n\r\n \"\"\" Slay the player \"\"\"\r\n es.server.queuecmd(\"damage %s %s\" % (self.userid, es.getplayerprop(self.userid, \"CBasePlayer.m_iHealth\")))\r\n \r\n \"\"\" Notify the user \"\"\"\r\n tell(self.userid, 'info deleted')",
"def update(self, user, product, quantity):\n\n cart_product = CartProduct.update(user, product, quantity)\n CartProductsView.update(cart_product)",
"def reset(self):\n Show.objects.all().delete()\n User.objects.exclude(is_superuser=True).delete()",
"def reset():\n SwUsers._emails = set(['[email protected]'])",
"async def reset_alarm(self, product_type: ProductType, serial_no: str) -> None:\n await self._send_message_get_response(OutgoingMessage(OutgoingMessageType.reset_alarm, domain=product_type.name, serial_no=serial_no))",
"def emulate_off_api_manager_products(cls):\n cls.products = OFF_API_FILTERED_PRODUCTS",
"def update_user_entitlement(self, document, user_id):\n route_values = {}\n if user_id is not None:\n route_values['userId'] = self._serialize.url('user_id', user_id, 'str')\n content = self._serialize.body(document, '[JsonPatchOperation]')\n response = self._send(http_method='PATCH',\n location_id='8480c6eb-ce60-47e9-88df-eca3c801638b',\n version='6.0-preview.3',\n route_values=route_values,\n content=content,\n media_type='application/json-patch+json')\n return self._deserialize('UserEntitlementsPatchResponse', response)",
"def promotions_reset():\n Promotion.remove_all()\n return make_response('', status.HTTP_204_NO_CONTENT)",
"def clear_list(self):\n api_page = \"/configuration/object/clear_provisioning_ap_list\"\n url = \"{}{}?{}&UIDARUBA={}\".format(\n self.base_url,\n api_page,\n self.config_path,\n self.uidaruba)\n\n obj = {\"_action\": \"modify\"}\n json_obj = json.loads(json.dumps(obj))\n resp = self.post(url, json_obj)\n print(\"clear_list_resp: {}\".format(resp.status_code))\n # print(resp.text)",
"def product_types(self, product_types):\n\n self._product_types = product_types",
"def reset(self):\n for _id in self.created_ids:\n review = Review.get_by_id(_id)\n\n if review:\n review.delete()\n\n self.user.delete()\n self.business.delete()",
"def reset_use_case(self, save: bool=None):\n self.pm.reset_use_case()\n self.pm_persist(save)",
"def reset(self, reset_user=False, **kwargs):\n for attr in self._exp_defaults:\n setattr(self, attr, self._exp_defaults[attr])\n for attr in self._source_attrs:\n delattr(self, attr)\n self._source_attrs = []",
"def reset(self):\n\t\tself.permissions = set()\n\t\tself.unpacked = False\n\t\treturn self",
"def reset(self):\n self.entities = set()\n self.frozen = False",
"def reset(self, reset_from):\n self._grants.clear()\n self._groups.clear()\n self._reset_cached()\n self._id += 1\n for name, backend in self._backends.items():\n if name == reset_from:\n continue\n backend.reload()"
] | [
"0.56585646",
"0.54697764",
"0.52775943",
"0.52775943",
"0.51205343",
"0.5110504",
"0.5110504",
"0.5086956",
"0.5080355",
"0.5080355",
"0.5065258",
"0.5040448",
"0.5031072",
"0.5013237",
"0.49968353",
"0.49950162",
"0.4991405",
"0.49880537",
"0.49675336",
"0.49537265",
"0.4919084",
"0.48776293",
"0.4866611",
"0.48596898",
"0.4858815",
"0.48498747",
"0.4840566",
"0.4829929",
"0.48290274",
"0.48173958"
] | 0.60211426 | 0 |
Returns the inskill product definition for given productId. | def get_isp_definition_v1(self, product_id, stage, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, InSkillProductDefinitionResponse_4aa468ff, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "get_isp_definition_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError(
"Missing the required parameter `product_id` when calling `" + operation_name + "`")
# verify the required parameter 'stage' is set
if ('stage' not in params) or (params['stage'] is None):
raise ValueError(
"Missing the required parameter `stage` when calling `" + operation_name + "`")
resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'product_id' in params:
path_params['productId'] = params['product_id']
if 'stage' in params:
path_params['stage'] = params['stage']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.isp.in_skill_product_definition_response.InSkillProductDefinitionResponse", status_code=200, message="Response contains the latest version of an in-skill product for the specified stage."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request. Returned when a required parameter is not present, badly formatted. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="Requested resource not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too many requests received."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error"))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.isp.in_skill_product_definition_response.InSkillProductDefinitionResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_product_by_id(productId): # noqa: E501\n return 'do some magic!'",
"def _product_spec_by_id(self, product_id):\n if not isinstance(product_id, int):\n raise TypeError(\"Product ID should be integer\")\n\n for product_group in self.db:\n for db_id in self.db[product_group]:\n if product_id == db_id:\n return self.db[product_group][product_id]\n\n raise ProductDatabaseError('Wrong product ID. Not found in DB')",
"def product(self, product_id):\r\n return products.Product(self, product_id)",
"def get_product(cls, product_id):\n return Product.query.get(product_id)",
"def get_product(self, product_id):\n text, code = ApiClient(self._config, 'products/' + product_id).get()\n return Product.deserialize(text)",
"def get(self, product_id):\n\n return product.get_single_product(product_id)",
"def get(self, product_id):\n return Products().get_one_product(product_id)",
"def product_id(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"product_id\")",
"def specific_product(self, product_id):\n con = dbcon()\n cur = con.cursor()\n cur.execute(\"SELECT * FROM products WHERE product_id=%(product_id)s\",\\\n {'product_id':product_id})\n res = cur.fetchall()\n #check if the product exists\n if res:\n my_product=[]\n for a_product in res:\n product = {\n 'product_id':a_product[0],\n 'product_name':a_product[1],\n 'price':a_product[2],\n 'quantity':a_product[3]\n }\n my_product.append(product)\n return make_response(jsonify({\"Products\":my_product}), 200)\n return jsonify({\"message\":\"could not find product with that id\"}), 400",
"def product_id(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"product_id\")",
"def get_product_info(self, product_id: str) -> Dict:\n product_info_request = \"SELECT * FROM product WHERE id = %s\"\n return self.query(product_info_request, (product_id,))[0]",
"def return_product(product_id):\n with MY_CONNECTION as connection:\n cursor = connection.cursor()\n cursor.execute(\n \"\"\"\n SELECT id_product, product_name, product_price, in_stock, description\n FROM Products\n WHERE id_product=?\n \"\"\",\n (product_id,))\n return cursor.fetchone()",
"def get_product_detail(self, adi, product_id=None, product_name=None):\r\n obj = None\r\n if self.from_copy:\r\n if product_name is None:\r\n print(\"Need product_name to load from copy\")\r\n return\r\n with open(self.product_detail_copy.format(adi, product_name.translate({ord(c): None for c in \"\\\\/:*\\\"<>|\"})), encoding='utf-8') as f:\r\n obj = json.load(f)\r\n return obj\r\n else:\r\n if product_id is None:\r\n print(\"Need product_id to call API\")\r\n return\r\n return self.rf.get_product_detail(self.urls[adi], product_id)",
"def get_product(self, identifier):\n # try to find an id corresponding to the code\n for p in self['products']:\n if identifier in p.get('ids', []):\n return p\n # if no product associated with the code found, return None\n return None",
"def onchange_product_id(self, cr, uid, ids, product_id, product_uom_id, context=None):\n result = super(purchase_requisition_line, self).onchange_product_id(cr, uid, ids, product_id, product_uom_id, context=context)\n if product_id:\n product_obj = self.pool.get('product.product').browse(cr, uid, product_id, context=context)\n result['name'] = self.pool.get('product.product').name_get(cr, uid, [product_obj.id], context=context)[0][1]\n result['price_target'] = product_obj.purchase_price_unit\n if product_obj.description_sale:\n result['name'] += '\\n'+product_obj.description_sale\n return {'value': result}",
"def get_product_with_id(product_id: str) -> Product:\n return Product.query.filter_by(id=product_id).first()",
"def search_product_by_id(product_id): # 2.6.???? # TODO WHAT IS THIS\n\n for store in stores.get_all_stores().values():\n if product_id in store.inventory.products_dict:\n ans = store.inventory.products_dict[product_id]\n return ans\n raise Exception(\"product not found\")",
"def get(self, product_id):\n product = ProductModel.query.filter_by(id=product_id).first()\n if not product:\n product_api.abort(404, \"Product {} not found\".format(product_id))\n else:\n return product",
"def product_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"product_id\")",
"def get_product_by_id(product_id):\n mongo = MongoClient(Config.MONGO_URI)\n if ObjectId().is_valid(product_id) is False:\n return bad_request(t['invalid_id'])\n db_operations = mongo.db.product\n product = db_operations.find_one_or_404({'_id': ObjectId(product_id)})\n response_product = Product().from_dict(product).to_dict()\n return jsonify(response_product)",
"def get_product_by_id(pid: int) -> Optional[Product]:\n return get_market().get_product(pid)",
"def get_product_from_querystring_id(qs_product_id):\n if isinstance(qs_product_id, int) or qs_product_id.isdigit():\n product = Product.objects.get(id=int(qs_product_id))\n return product, product.content_object, None\n else:\n # Text IDs for Programs/CourseRuns have '+' characters, which represent spaces in URL-encoded strings\n parsed_product_text_id = qs_product_id.replace(\" \", \"+\")\n return get_product_from_text_id(parsed_product_text_id)",
"def get_product(admin, product_id):\n product = Product.query.filter(Product.id == product_id).first()\n if not product:\n raise exc.EntryNotFound()\n\n if not product.active and not admin:\n fields = [\n \"id\",\n \"name\",\n \"barcode\",\n \"active\",\n \"imagename\",\n \"tags\",\n \"creation_date\",\n ]\n else:\n fields = [\n \"id\",\n \"name\",\n \"price\",\n \"barcode\",\n \"active\",\n \"countable\",\n \"purchase_sum\",\n \"replenishment_sum\",\n \"balance_score\",\n \"revocable\",\n \"imagename\",\n \"tags\",\n \"creation_date\",\n ]\n\n # Convert the product to a dictionary\n product = convert_minimal(product, fields)[0]\n\n # Convert the product tags\n product[\"tags\"] = [t.id for t in product[\"tags\"]]\n\n return jsonify(product), 200",
"def get_product(self, id):\n endpoint = '/v3/educator/products/%s' % id\n result = self.request(endpoint)\n data = result.response\n\n # Dynamically load product instance.\n class_name = data.type.capitalize()\n product = Product.instance(class_name, data)\n\n return product",
"def _get_produce_line_prodlot_id(self, cr, uid, product_id, context=None):\n # Note: First my intention was to use the move_brw.prodlot_id to get\n # the prodlot_id but this field is not set, I imagine that is set\n # before the move is consumed.\n context = context or {}\n prodlot_obj = self.pool.get('stock.production.lot')\n prodlot_ids = \\\n prodlot_obj.search(\n cr, uid, [('product_id', '=', product_id)], context=context) \\\n or False\n return prodlot_ids and prodlot_ids[0] or False",
"def specific_product(self, product_id):\n for product in self.products_list:\n if product['product_id'] == product_id:\n return jsonify({\"Product\":product}), 200",
"def get_product_stock(product_id):\n\n # Check, whether the requested product exists\n product = Product.query.filter(Product.id == product_id).first()\n if not product:\n raise exc.EntryNotFound()\n\n # If the product is not countable, return None\n if not product.countable:\n return jsonify(None), 200\n\n # Get the theoretical stock level\n theoretical_stock = product_helpers.get_theoretical_stock_of_product(product_id)\n\n return jsonify(theoretical_stock), 200",
"def has_product_id(self, product_id):\n product = self.get_products().filter(id=product_id)\n\n if product.exists():\n return product[0]\n else:\n return None",
"def get_isp_list_for_skill_id_v1(self, skill_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListInSkillProductResponse_505e7307]\n operation_name = \"get_isp_list_for_skill_id_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/stages/{stage}/inSkillProducts'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse\", status_code=200, message=\"Response contains list of in-skill products for the specified skillId and stage.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def find_product_domain(regionid, prod_name):\n if regionid is not None and product is not None:\n for point in __endpoints:\n point_info = __endpoints.get(point)\n if regionid in point_info.get('regions'):\n prod_info = point_info.get('products')\n for prod in prod_info:\n if prod_name in prod:\n return prod.get(prod_name)\n return None"
] | [
"0.6464672",
"0.612124",
"0.605774",
"0.6039397",
"0.5857793",
"0.58464456",
"0.5832984",
"0.57331824",
"0.5726266",
"0.5706458",
"0.56913775",
"0.56698745",
"0.56065446",
"0.55776674",
"0.55651134",
"0.5551204",
"0.5525478",
"0.5506871",
"0.55012226",
"0.54999846",
"0.5465346",
"0.54323715",
"0.54102117",
"0.5400302",
"0.5398456",
"0.5388615",
"0.53714484",
"0.5349984",
"0.5347025",
"0.5330789"
] | 0.6508556 | 0 |
Updates inskill product definition for given productId. Only development stage supported. | def update_isp_for_product_v1(self, product_id, stage, update_in_skill_product_request, **kwargs):
# type: (str, str, UpdateInSkillProductRequest_ee975cf1, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "update_isp_for_product_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError(
"Missing the required parameter `product_id` when calling `" + operation_name + "`")
# verify the required parameter 'stage' is set
if ('stage' not in params) or (params['stage'] is None):
raise ValueError(
"Missing the required parameter `stage` when calling `" + operation_name + "`")
# verify the required parameter 'update_in_skill_product_request' is set
if ('update_in_skill_product_request' not in params) or (params['update_in_skill_product_request'] is None):
raise ValueError(
"Missing the required parameter `update_in_skill_product_request` when calling `" + operation_name + "`")
resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'product_id' in params:
path_params['productId'] = params['product_id']
if 'stage' in params:
path_params['stage'] = params['stage']
query_params = [] # type: List
header_params = [] # type: List
if 'if_match' in params:
header_params.append(('If-Match', params['if_match']))
body_params = None
if 'update_in_skill_product_request' in params:
body_params = params['update_in_skill_product_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request. Returned when a required parameter is not present, badly formatted. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="Request is forbidden."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="Requested resource not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=412, message="Precondition failed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too many requests received."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error"))
api_response = self.invoke(
method="PUT",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_product_form(productId, name=None, status=None): # noqa: E501\n return 'do some magic!'",
"def associate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"associate_isp_with_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_isp_definition_v1(self, product_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, InSkillProductDefinitionResponse_4aa468ff, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"get_isp_definition_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.in_skill_product_definition_response.InSkillProductDefinitionResponse\", status_code=200, message=\"Response contains the latest version of an in-skill product for the specified stage.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.in_skill_product_definition_response.InSkillProductDefinitionResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def put(self, product_id):\n\n product_name = request.get_json(\"product_name\")[\n \"product_name\"].strip(\" \")\n model = request.get_json(\"model\")[\"model\"].strip(\" \")\n product_price = request.get_json(\"product_price\")[\"product_price\"]\n quantity = request.get_json(\"quantity\")[\"quantity\"]\n category = request.get_json(\"category\")[(\"category\")]\n min_quantity = request.get_json(\"min_quantity\")[\"min_quantity\"]\n\n if not product_name or not model or not product_price or not quantity \\\n or not min_quantity:\n return jsonify({\n \"message\": \"Check all required fields\",\n \"status\": 400\n })\n\n current_user = get_jwt_identity()[\"username\"].lower()\n\n product = {\n \"product_id\": product_id,\n \"product_name\": product_name,\n \"model\": model,\n \"product_price\": product_price,\n \"quantity\": quantity,\n \"category\": category,\n \"min_quantity\": min_quantity,\n \"created_by\": current_user\n }\n\n return Product().update_product(**product)",
"def _onchange_product_id(self):\n if not self.product_id:\n return\n else :\n thisid = self.search([\n ('product_id', '=', self.product_id.id),\n\n ], order='id', limit=1)\n # return {\n # 'type': 'ir.actions.act_window',\n # 'res_model': 'rental.shopify_product',\n # 'views': [[False, 'form']],\n # 'res_id': thisid.id,\n # }\n\n\n self.update({\n 'is_Edit' : True,\n 'edit_id' : thisid.id,\n 'shopify_product_title': self.product_id.title,\n 'rental_pricing_ids' : thisid.rental_pricing_ids\n\n })",
"def update_product(admin, product_id):\n return generic_update(Product, product_id, json_body(), admin)",
"def modify_product(self, product_id,product_name,price,quantity):\n con = dbcon()\n cur = con.cursor()\n cur.execute(\"SELECT * FROM products WHERE product_id=%(product_id)s\",\\\n {\"product_id\":product_id})\n found_id = cur.fetchall()\n if found_id:\n cur.execute(\"UPDATE products SET product_name=%s, price=%s, \\\n quantity= %s WHERE product_id=%s\",\\\n (product_name, price, quantity, product_id))\n con.commit()\n return make_response(jsonify({'message': 'Product modified'}), 200)\n return jsonify({\"message\":\"Couldn't find product ID\"})",
"def reset_entitlement_for_product_v1(self, product_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"reset_entitlement_for_product_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}/entitlement'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=412, message=\"Precondition failed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def __edit_product_menu(self, product: Optional[db.SwimPool] = None):\n log.debug(\"Displaying __edit_product_menu\")\n # Create an inline keyboard with a single skip button\n cancel = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(self.loc.get(\"menu_skip\"),\n callback_data=\"cmd_cancel\")]])\n # Ask for the product name until a valid product name is specified\n while True:\n # Ask the question to the user\n self.bot.send_message(self.chat.id, self.loc.get(\"ask_product_name\"))\n # Display the current name if you're editing an existing product\n if product:\n self.bot.send_message(self.chat.id, self.loc.get(\"edit_current_value\", value=escape(product.name)),\n reply_markup=cancel)\n # Wait for an answer\n name = self.__wait_for_regex(r\"(.*)\", cancellable=bool(product))\n # Ensure a product with that name doesn't already exist\n if (product and isinstance(name, CancelSignal)) or \\\n self.session.query(db.Product).filter_by(name=name, deleted=False).one_or_none() in [None, product]:\n # Exit the loop\n break\n self.bot.send_message(self.chat.id, self.loc.get(\"error_duplicate_name\"))\n # Ask for the product description\n self.bot.send_message(self.chat.id, self.loc.get(\"ask_product_description\"))\n # Display the current description if you're editing an existing product\n if product:\n self.bot.send_message(self.chat.id,\n self.loc.get(\"edit_current_value\", value=escape(product.description)),\n reply_markup=cancel)\n # Wait for an answer\n description = self.__wait_for_regex(r\"(.*)\", cancellable=bool(product))\n # Ask for the product price\n self.bot.send_message(self.chat.id,\n self.loc.get(\"ask_product_price\"))\n # Display the current name if you're editing an existing product\n if product:\n self.bot.send_message(self.chat.id,\n self.loc.get(\"edit_current_value\",\n value=(str(self.Price(product.price))\n if product.price is not None else 'Non in vendita')),\n reply_markup=cancel)\n # Wait for an answer\n price = self.__wait_for_regex(r\"([0-9]+(?:[.,][0-9]{1,2})?|[Xx])\",\n cancellable=True)\n # If the price is skipped\n if isinstance(price, CancelSignal):\n pass\n elif price.lower() == \"x\":\n price = None\n else:\n price = self.Price(price)\n # Ask for the product image\n self.bot.send_message(self.chat.id, self.loc.get(\"ask_product_image\"), reply_markup=cancel)\n # Wait for an answer\n photo_list = self.__wait_for_photo(cancellable=True)\n # If a new product is being added...\n if not product:\n # Create the db record for the product\n # noinspection PyTypeChecker\n product = db.Product(name=name,\n description=description,\n price=int(price) if price is not None else None,\n deleted=False)\n # Add the record to the database\n self.session.add(product)\n # If a product is being edited...\n else:\n # Edit the record with the new values\n product.name = name if not isinstance(name, CancelSignal) else product.name\n product.description = description if not isinstance(description, CancelSignal) else product.description\n product.price = int(price) if not isinstance(price, CancelSignal) else product.price\n # If a photo has been sent...\n if isinstance(photo_list, list):\n # Find the largest photo id\n largest_photo = photo_list[0]\n for photo in photo_list[1:]:\n if photo.width > largest_photo.width:\n largest_photo = photo\n # Get the file object associated with the photo\n photo_file = self.bot.get_file(largest_photo.file_id)\n # Notify the user that the bot is downloading the image and might be inactive for a while\n self.bot.send_message(self.chat.id, self.loc.get(\"downloading_image\"))\n self.bot.send_chat_action(self.chat.id, action=\"upload_photo\")\n # Set the image for that product\n product.set_image(photo_file)\n # Commit the session changes\n self.session.commit()\n # Notify the user\n self.bot.send_message(self.chat.id, self.loc.get(\"success_product_edited\"))",
"def update_product(product_id, name, price, stock, description):\n with MY_CONNECTION as connection:\n connection.execute(\n \"\"\"\n UPDATE Products\n SET product_name=?, product_price=?, in_stock=?, description=?\n WHERE id_product=?\n \"\"\",\n (name, price, stock, description, product_id,))",
"def onchange_product_id(self, cr, uid, ids, product_id, product_uom_id, context=None):\n result = super(purchase_requisition_line, self).onchange_product_id(cr, uid, ids, product_id, product_uom_id, context=context)\n if product_id:\n product_obj = self.pool.get('product.product').browse(cr, uid, product_id, context=context)\n result['name'] = self.pool.get('product.product').name_get(cr, uid, [product_obj.id], context=context)[0][1]\n result['price_target'] = product_obj.purchase_price_unit\n if product_obj.description_sale:\n result['name'] += '\\n'+product_obj.description_sale\n return {'value': result}",
"def update_product(body): # noqa: E501\n if connexion.request.is_json:\n body = Product.from_dict(connexion.request.get_json()) # noqa: E501\n return 'do some magic!'",
"def product_id(self, product_id):\n self._product_id = product_id",
"def put(self, product_id):\n data = Product.parser.parse_args()\n product = ProductModel.find_by_id(product_id)\n\n if product is None:\n if data['name'] and data['price']:\n product = ProductModel(**data)\n product.save_to_db()\n else:\n return {'message': \"This product doesn't exist, you should enter all data to create one\"}, 404\n else:\n product.name = data['name'] if data['name'] else product.name\n product.price = data['price'] if data['price'] else product.price\n\n product.save_to_db()\n\n return product.to_json()",
"def product_id(self, product_id):\n\n self._product_id = product_id",
"def product_id(self, product_id):\n\n self._product_id = product_id",
"def update_product(self, product_id, name, archived=False):\n archived = 'y' if archived else 'n'\n return self._make_post_request(self._urls['product'] % product_id,\n data=dict(name=name, archived=archived))",
"def edit_product(conn, product_id: int, new_price: int) -> None:\n with conn.cursor() as cursor:\n cursor.execute(\"\"\"update products\n set price = '{0}'\n where id = '{1}'\"\"\".format(new_price, product_id))\n if cursor.rowcount:\n conn.commit()\n else:\n raise errors.StoreError",
"def create_isp_for_vendor_v1(self, create_in_skill_product_request, **kwargs):\n # type: (CreateInSkillProductRequest_816cf44b, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ProductResponse_b388eec4, BadRequestError_f854b05]\n operation_name = \"create_isp_for_vendor_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'create_in_skill_product_request' is set\n if ('create_in_skill_product_request' not in params) or (params['create_in_skill_product_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_in_skill_product_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_in_skill_product_request' in params:\n body_params = params['create_in_skill_product_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.product_response.ProductResponse\", status_code=201, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.product_response.ProductResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def delete_isp_for_product_v1(self, product_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"delete_isp_for_product_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n if 'if_match' in params:\n header_params.append(('If-Match', params['if_match']))\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=412, message=\"Precondition failed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_isp_list_for_skill_id_v1(self, skill_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListInSkillProductResponse_505e7307]\n operation_name = \"get_isp_list_for_skill_id_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/stages/{stage}/inSkillProducts'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse\", status_code=200, message=\"Response contains list of in-skill products for the specified skillId and stage.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.list_in_skill_product_response.ListInSkillProductResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_02_product_update(self):\n # Update new product state2 from default draft to sellable\n new_product = self.create_product()\n self.assertEqual(new_product.state2, 'draft')\n new_product.state2 = 'sellable'\n self.assertEqual(new_product.state2, 'sellable')\n\n # Same but to an existing demo product.\n demo_product = self.product_obj.browse(\n self.ref('product_lifecycle.product_product_4g'))\n self.assertEqual(demo_product.state2, 'sellable')\n demo_product.state2 = 'draft'\n self.assertEqual(demo_product.state2, 'draft')\n\n # Update new product invividual field (field defined in product.product\n # model).\n self.assertEqual(new_product.default_code, 'A2330')\n new_product.default_code = 'A2330-1'\n self.assertEqual(new_product.default_code, 'A2330-1')\n\n # Same but to an existing demo product.\n self.assertEqual(demo_product.default_code, 'A2329')\n demo_product.default_code = 'A2329-1'\n self.assertEqual(demo_product.default_code, 'A2329-1')\n\n # Update new product commom characteristic (field defined in\n # product.template) and check that affects the another product\n # variants\n self.assertFalse(new_product.description)\n new_product.description = 'This is a New Product'\n self.assertEqual(new_product.description, 'This is a New Product')\n self.assertEqual(demo_product.description, 'This is a New Product')\n demo_product.description = False\n self.assertFalse(demo_product.description)",
"def update(self, product, qty):\n product_id = str(product)\n if product_id in self.basket:\n self.basket[product_id]['qty'] = qty\n self.save()",
"def disassociate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"disassociate_isp_with_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def onchange_product_id(self):\n if not self.product_id:\n self.bom_id = False\n elif not self.bom_id or self.bom_id.product_tmpl_id != self.product_tmpl_id or (self.bom_id.product_id and self.bom_id.product_id != self.product_id):\n bom = self.env['mrp.bom']._bom_find(product=self.product_id, picking_type=self.picking_type_id, company_id=self.company_id.id, bom_type='normal')\n if bom:\n self.bom_id = bom.id\n self.product_qty = self.bom_id.product_qty\n self.product_uom_id = self.bom_id.product_uom_id.id\n else:\n self.bom_id = False\n self.product_uom_id = self.product_id.uom_id.id",
"def test_update_product(self):\n # create a product to update\n test_product = ProductFactory()\n test_product_name = test_product.name\n test_product_description = test_product.description\n test_product_price = test_product.price\n resp = self.app.post(\n \"/products\", json=test_product.serialize(), content_type=\"application/json\")\n self.assertEqual(resp.status_code, status.HTTP_201_CREATED)\n\n # update the product\n new_product = resp.get_json()\n new_product[\"category\"] = \"Education\"\n resp = self.app.put(\n \"/products/{}\".format(new_product[\"id\"]),\n json=new_product,\n content_type=\"application/json\")\n self.assertEqual(resp.status_code, status.HTTP_200_OK)\n updated_product = resp.get_json()\n self.assertEqual(updated_product[\"category\"], \"Education\")",
"def update_product(self):\n if len(self.lineEdit_name.text()) != 0 and len(self.lineEdit_desc.text()) != 0 and len(\n self.lineEdit_cost.text()) != 0 and len(self.lineEdit_cat.text()) != 0:\n item = ['name', 'description', 'cost', 'categories']\n id = self.lineEdit_id.text()\n list = self.product_list()\n for n in range(0, len(list)):\n try:\n update_product(item[n], list[n], id)\n self.frame_3.show()\n self.label_16.setText('UPDATE PRODUCT SUCESSFULLY!')\n except:\n self.frame_3.show()\n self.label_16.setText('ERROR UPDATE PRODUCT!')\n else:\n self.frame_3.show()\n self.label_16.setText('THERE CAN BE NO BLANCK FIELDS!')",
"def update(self, request, pk=None):\n order_product = Order_Products.objects.get(pk=pk)\n product = Product.objects.get(pk=request.data['product_id'])\n order = Order.objects.get(pk=request.data['order_id'])\n order_product.review = request.data['review']\n order_product.product = product\n order_product.order = order\n order_product.save()\n \n return Response({}, status=status.HTTP_204_NO_CONTENT)",
"def update(self, product, qty):\n product_id = str(product)\n if product_id in self.cart:\n self.cart[product_id]['qty'] = qty\n self.save()",
"def get_isp_associated_skills_v1(self, product_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, AssociatedSkillResponse_12067635, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"get_isp_associated_skills_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}/skills'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.associated_skill_response.AssociatedSkillResponse\", status_code=200, message=\"Returns skills associated with the in-skill product.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.associated_skill_response.AssociatedSkillResponse\")\n\n if full_response:\n return api_response\n return api_response.body"
] | [
"0.61609936",
"0.61382127",
"0.6079622",
"0.6055985",
"0.6021867",
"0.5917009",
"0.5853831",
"0.578811",
"0.5721086",
"0.5692899",
"0.56461924",
"0.5592242",
"0.5513153",
"0.54926187",
"0.54778296",
"0.54778296",
"0.547739",
"0.54153234",
"0.5413967",
"0.539913",
"0.5369796",
"0.5329344",
"0.5324368",
"0.52980036",
"0.52772474",
"0.5249264",
"0.5244384",
"0.52304435",
"0.5230083",
"0.5177024"
] | 0.7032969 | 0 |
Get the summary information for an inskill product. | def get_isp_summary_v1(self, product_id, stage, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, InSkillProductSummaryResponse_32ba64d7]
operation_name = "get_isp_summary_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'product_id' is set
if ('product_id' not in params) or (params['product_id'] is None):
raise ValueError(
"Missing the required parameter `product_id` when calling `" + operation_name + "`")
# verify the required parameter 'stage' is set
if ('stage' not in params) or (params['stage'] is None):
raise ValueError(
"Missing the required parameter `stage` when calling `" + operation_name + "`")
resource_path = '/v1/inSkillProducts/{productId}/stages/{stage}/summary'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'product_id' in params:
path_params['productId'] = params['product_id']
if 'stage' in params:
path_params['stage'] = params['stage']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.isp.in_skill_product_summary_response.InSkillProductSummaryResponse", status_code=200, message="Returns current in-skill product summary for productId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="Requested resource not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too many requests received."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error"))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.isp.in_skill_product_summary_response.InSkillProductSummaryResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def product_summary(self):\n # products = self.products.filter(type='S') # TODO: explain the usage of this commented line or remove it\n from .utils import process_products\n\n subscription_products = SubscriptionProduct.objects.filter(subscription=self)\n dict_all_products = {}\n for sp in subscription_products:\n dict_all_products[str(sp.product.id)] = str(sp.copies)\n return process_products(dict_all_products)",
"def inventory_report(self):\n mean_price = sum(Product.price for Product in sample) / len(sample)\n mean_weight = sum(Product.weight for Product in sample) / len(sample)\n mean_flam = sum(Product.flammability for Product in sample) / len(sample)\n return 'Unique Product Names: ', sample.unique, '/n Average Price: ', mean_price, \n '/n Average Weight: ', mean_weight, '/n Average Flammability: ', mean_flam",
"def product_details(self) -> MqexsProductDetails:\n return self.__product_details",
"def product_details(self):\n return self._product_details",
"def product(self) -> str:\n return pulumi.get(self, \"product\")",
"def summary(self):\n name = 'name : ' + self.get_name()\n description = 'description : ' + self.get_description()\n agility = 'agility : ' + str(self.get_agility())\n strength = 'strength : ' + str(self.get_strength())\n health_points = 'health_points : ' + str(self.get_health_points())\n summary = '\\n'.join([name, description, agility, strength, health_points])\n if self.take_weapon():\n summary += self.take_weapon().summary()\n return summary",
"def summary(self) -> str:\n return pulumi.get(self, \"summary\")",
"def retrieve_product_infos(self):\n\n # PRODUCT NAME\n try:\n product_name = self.product['product_name'].capitalize()\n except KeyError:\n product_name = None\n\n # PRODUCT CODE\n try:\n product_code = self.product['code'].capitalize()\n except KeyError:\n product_code = None\n\n # URL\n try:\n product_url = self.product['url'].lower()\n except KeyError:\n product_url = None\n\n # IMAGE URL\n try:\n image_url = self.product['image_url'].lower()\n except KeyError:\n image_url = None\n\n # QUANTITY\n try:\n quantity = self.product['quantity'].capitalize()\n except KeyError:\n quantity = None\n\n # INGREDIENTS\n try:\n ingredients = self.product['ingredients_text_fr'].capitalize()\n except KeyError:\n ingredients = None\n\n # BRAND\n brands = []\n try:\n for brand in self.product['brands'].split(','):\n brand = brand.strip().capitalize()\n if (\n brand != ''\n and brand not in brands\n ):\n brands.append(brand)\n except KeyError:\n pass\n\n # STORES\n stores = []\n try:\n for store in self.product['stores'].split(','):\n store = store.strip().capitalize()\n if (\n store != ''\n and store not in stores\n ):\n stores.append(store)\n except KeyError:\n pass\n\n # COUNTRY\n try:\n countries = self.product['countries'].capitalize()\n except KeyError:\n countries = None\n if 'France' in countries:\n countries = 'France'\n else:\n countries = None\n\n # COMPARE TO CATEGORY\n try:\n compare_to = self.product['compared_to_category'].capitalize().split(':')[1]\n except KeyError:\n compare_to = None\n try:\n Categories.objects.get(\n name=compare_to\n )\n except Categories.DoesNotExist:\n compare_to = None\n except:\n importable = False\n\n # CATEGORIES HIERARCHY\n try:\n categories_hierarchy = [\n category.split(':')[1] for category in self.product['categories_hierarchy']\n ]\n except KeyError:\n categories_hierarchy = None\n\n # NUTRISCORE GRADE\n nutriscore_labels = [\n 'nutrition_grade_fr',\n 'nutriscore_grade'\n ]\n nutriscore = 'F'\n i = 0\n while (\n i < len(nutriscore_labels)\n and nutriscore == 'F'\n ):\n try:\n nutriscore = self.product[nutriscore_labels[i]].upper()\n except KeyError:\n i += 1\n\n product_infos = {\n 'product_name': product_name,\n 'product_code': product_code,\n 'product_url': product_url,\n 'image_url': image_url,\n 'quantity': quantity,\n 'ingredients': ingredients,\n 'brands': brands,\n 'stores': stores,\n 'countries': countries,\n 'compare_to': compare_to,\n 'categories_hierarchy': categories_hierarchy,\n 'nutriscore': nutriscore\n }\n\n nutriments = self.product['nutriments']\n for nutriment in self.list_nutriments:\n try:\n product_infos[nutriment] = float(nutriments[nutriment])\n except KeyError:\n product_infos[nutriment] = 0\n\n return product_infos",
"def get_prod_infos(self, found_product_id):\n category = Categories.objects.filter(product_id=found_product_id)\n print(\"category:{}\".format(category))\n self.cat_name = category.values('name')[0]['name']\n print(\"category NAME:{}\".format(self.cat_name))\n self.found_prod = Product.objects.filter(\n pk=found_product_id)\n print(\"prod found:{}\".format(self.found_prod))\n self.nutriscore = self.found_prod.values('nutrition_grade')[\n 0]['nutrition_grade']\n return self.cat_name, self.nutriscore",
"def get_product_info(self, product):\n\n product_link = self.url + product.a['href']\n product_page = self.get_response(product_link)\n product_soup = BeautifulSoup(product_page.content, 'html.parser')\n\n # get product details\n product_brand = product_soup.find('h2').text.strip()\n product_name = product_soup.find('h1').text.strip()\n\n product_details = product_soup.find('div', id='z-pdp-detailsSection')\n\n product_attributes = []\n for detail_section in product_details.find_all('div', class_='h-container h-flex-no-shrink h-tabs__panel h-align-left'):\n for tag in detail_section.find_all('p'):\n product_attributes.append(tag.text.strip())\n\n # get product image\n product_img_thumbs = product_soup.find('div', id='z-pdp-topSection')\n product_img_thumbs = product_img_thumbs.find(\n 'div', class_='h-container h-carousel h-carousel-thumbnail vertical h-align-left')\n\n img_links = []\n product_img_link = ''\n for img_thumb in product_img_thumbs.find_all('picture'):\n img_link = img_thumb.find('img')['src'].replace('thumb', 'zoom')\n if 'packshot' in img_link:\n product_img_link = img_link\n else:\n img_links.append(img_link)\n\n # product_img_link = 'https:' + product_img.split('\"')[1].split('?')[0]\n product_img_id = product_img_link.split('/')[-1].split('@')[0]\n\n return {'name': product_name,\n 'brand': product_brand,\n 'id': product_img_id,\n 'img_url': product_img_link,\n 'model_img_urls': ', '.join(img_links),\n 'attributes': ', '.join(product_attributes)}",
"def skill(self):\n return self._get(\"skill\")",
"def inventory_report(products):\n unique_names = []\n total_price = 0\n total_weight = 0\n total_flammability = 0\n num_products = len(products)\n for i in range(num_products):\n if products[i].name not in unique_names:\n unique_names.append(products[i].name) \n total_price += products[i].price\n total_weight += products[i].weight\n total_flammability += products[i].flammability\n mean_price = total_price / num_products\n mean_weight = total_weight / num_products\n mean_flammability = total_flammability / num_products\n print('ACME CORPORATION OFFICIAL INVENTORY REPORT')\n print(f'Unique product names: {len(unique_names)}')\n print(f'Average price: {mean_price}')\n print(f'Average weight {mean_weight}')\n print(f'Average flammabilitiy {mean_flammability}')\n return unique_names, mean_price, mean_weight, mean_flammability",
"def product(self):\n return self.__values['product_name']",
"def getSummary(self):\n return self.summary",
"def get_product_info(self, product_id: str) -> Dict:\n product_info_request = \"SELECT * FROM product WHERE id = %s\"\n return self.query(product_info_request, (product_id,))[0]",
"def get_product_purity(product):\n return product.imass[products].sum() / product.F_mass",
"def getSummary(self):\n return self.base.get(\"summary\", [])",
"def GetBasicInformation(self):\n if self.cur_uid is None:\n return\n self._get_product_detail_id()",
"def skill_information():\r\n\r\n client = boto3.client('iot-data', region_name='us-west-2')\r\n\r\n session_attributes = {}\r\n card_title = \"Welcome\"\r\n should_end_session = True\r\n reprompt_text = None\r\n\r\n if(is_online()):\r\n speech_output = \"The coffee machine is offline.\"\r\n else:\r\n client.publish(topic=TOPIC_TURN_ON_OFF, qos=1, payload=json.dumps({\"state\": \"1\"}))\r\n speech_output = \"The coffee machine is on\"\r\n save_on_off_status(1)\r\n\r\n return build_response(session_attributes,\r\n build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))",
"def get_summary(self):\n return self.model.summary()",
"def summary(self):\n res = \", \".join(\n elem[\"summary\"] for elem in self.status[\"health\"][\"summary\"]\n )\n if res:\n return res\n elif self.detail:\n return self.detail[0]\n return \"\"",
"def summary(self):\n raise NotImplementedError",
"def _summary(obj):\n return obj.summary",
"def display_skill(self):\n return ', '.join([skill.name for skill in self.skill.all()[:3]])",
"def product(self):\n return self._product",
"def product(self):\n return self._product",
"def product(self):\n return self._product",
"def summary(self):\n if hasattr(self,\"_summary\"):\n return self._summary\n else:\n return {}",
"def inventory_report(products, prices, weights, flammabilities):\n num_product = len(products)\n avg_price = mean(prices)\n avg_weight = mean(weights)\n avg_flam = mean(flammabilities)\n\n print(\"ACME CORPORATION OFFICIAL INVENTORY REPORT\")\n print(\"Unique product names: {}\".format(num_product))\n print(\"Average price: {}\".format(avg_price))\n print(\"Average weight: {}\".format(avg_weight))\n print(\"Average flammability: {}\".format(avg_flam))",
"def print_product(product):\r\n try:\r\n print(\"\\n \\\r\n Name : {} \\n \\\r\n Categories : {} \\n \\\r\n Nutri-score : {} \\n \\\r\n Stores : {} \\n \\\r\n URL : {}\".format(product.name, product.category, product.nutri_score, product.stores, product.url))\r\n except TypeError:\r\n print(\"Désolé, il n'y a pas de substitut pour ce product...\")"
] | [
"0.6262818",
"0.6042343",
"0.5940665",
"0.59008634",
"0.58890253",
"0.5821843",
"0.5760935",
"0.5731772",
"0.57011896",
"0.569796",
"0.5634564",
"0.5575895",
"0.5570702",
"0.5545321",
"0.552987",
"0.55269814",
"0.54810643",
"0.5476215",
"0.54176176",
"0.5392869",
"0.53575855",
"0.53575027",
"0.5350498",
"0.5344194",
"0.53187656",
"0.53187656",
"0.53187656",
"0.5287469",
"0.5279185",
"0.52779937"
] | 0.61915576 | 1 |
List all the historical versions of the given catalogId. | def list_interaction_model_catalog_versions_v1(self, catalog_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, ListCatalogEntityVersionsResponse_aa31060e, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "list_interaction_model_catalog_versions_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'catalog_id' is set
if ('catalog_id' not in params) or (params['catalog_id'] is None):
raise ValueError(
"Missing the required parameter `catalog_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'catalog_id' in params:
path_params['catalogId'] = params['catalog_id']
query_params = [] # type: List
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'sort_direction' in params:
query_params.append(('sortDirection', params['sort_direction']))
if 'sort_field' in params:
query_params.append(('sortField', params['sort_field']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.version.list_catalog_entity_versions_response.ListCatalogEntityVersionsResponse", status_code=200, message="Returns list of catalogs for the vendor."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error e.g. the catalog definition is invalid."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The specified catalog does not exist."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.version.list_catalog_entity_versions_response.ListCatalogEntityVersionsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list_versions(self, service_id):\n return [self.fastly_cache[service_id]['service_details']]",
"def revision_history(self, uuid):\n return self.write.revision_history(rid=uuid)",
"def ListVersions(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def history_list(name):\n service_histories = request_service_history(name)\n table = present(lambda: service_histories,\n renderer='table',\n headers=['History Version', 'Service Name', 'Date Created', 'Manifest'],\n columns=['id', 'name', 'created_at', 'manifest'])\n if table:\n click.echo(table)\n else:\n click.echo('There is no record of your service deployments available.')\n # click.echo('https://docs.fandogh.cloud/docs/services.html\\n')",
"def list_versions(self, project_id, model_id):\n endpoint = \"/project/{}/model/{}/version\".format(project_id, model_id)\n return self._get(endpoint, _ModelVersionSchema(many=True))",
"def list_catalogs_for_vendor_v0(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, ListCatalogsResponse_3dd2a983, BadRequestError_a8ac8b44, Error_d660d58]\n operation_name = \"list_catalogs_for_vendor_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/catalogs'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.catalog.list_catalogs_response.ListCatalogsResponse\", status_code=200, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v0.catalog.list_catalogs_response.ListCatalogsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def versionHistory(self):\n url = self.metaData().getLink(\"version-history\")\n assert url is not None\n\n header = self._baseHeader.copy()\n response = self._adapter.getRequest(url, header)\n\n return json.loads(response['Body'])",
"def revision_list():\n for rev in orm.DataRevision.select():\n click.echo(rev.name)",
"def list_all_dataset_versions(self):\n assert self.dataset_id, 'dataset_id required!'\n return self._datasets_request('GET', dataset_id=self.dataset_id, versions_request=True)",
"def get_history(cls, api, history):\n api_base = api.split('/')[-1]\n cursor = cls.history_index.cursor()\n cursor.execute(\n \"select filename from history where api=? and ymdh=?;\",\n (api_base, history))\n files = [r[0] for r in cursor]\n cls.history_index.commit()\n if not files:\n return {}\n results = {}\n for fn in files:\n ts = re.split('[?@]', fn)[-1].replace('.gz', '')\n fn_full = os.path.join(config.base_store_dir, fn)\n fd = (gzip.open if fn.endswith('.gz') else open)(fn_full)\n results[ts] = json.load(fd, encoding='utf8')\n fd.close()\n return results",
"def list_catalogs(self):\n return self._json_object_field_to_list(\n self._get_catalogs_json(), self.__MISSION_STRING)",
"def get_catalog_items(id):\n\n username = login_session.get('username', None)\n catalogs = session.query(Catalog).all()\n selected_catalog = session.query(Catalog).filter_by(id=id).one()\n items = selected_catalog.items\n catalogs_display = [\n {\n 'id': catalog.id,\n 'name': catalog.name\n } for catalog in catalogs]\n items_display = [{'id': item.id, 'title': item.title} for item in items]\n items_summary = '{0} Items ({1} items)'.format(\n selected_catalog.name,\n len(items_display))\n return render_template(\n 'home.html',\n catalogs_display=catalogs_display,\n items_display=items_display,\n items_summary=items_summary,\n username=username)",
"def versions():\n result = timeline.versions()\n if result:\n click.echo('\\n'.join(result))",
"def list_dataset_version(self, version_id):\n assert self.dataset_id, 'dataset_id required!'\n return self._datasets_request('GET', dataset_id=self.dataset_id, versions_request=True,\n version_id=version_id)",
"def get_history():\n return response_texts_to_entries(make_post_request(HISTORY_API, data={\"k\": config[\"api_key\"]}))",
"def get_catalog_v0(self, catalog_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, CatalogDetails_912693fa, Error_d660d58]\n operation_name = \"get_catalog_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\", status_code=200, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\")\n\n if full_response:\n return api_response\n return api_response.body",
"def list_revisions(self, script_uid, limit=None):\n # We need to enable this once we add functionality for WSD\n if self._client.ICP_30 is None and not self._client.CLOUD_PLATFORM_SPACES and not self._client.ICP_PLATFORM_SPACES:\n raise WMLClientError(u'Not supported in this release')\n\n ##For CP4D, check if either space or project ID is set\n self._client._check_if_either_is_set()\n\n script_uid = str_type_conv(script_uid)\n Script._validate_type(script_uid, u'script_uid', STR_TYPE, True)\n\n url = self._href_definitions.get_asset_href(script_uid) + \"/revisions\"\n # /v2/assets/{asset_id}/revisions returns 'results' object\n script_resources = self._get_with_or_without_limit(url,\n limit,\n 'List Script revisions',\n summary=None,\n pre_defined=None)[u'results']\n script_values = [\n (m[u'metadata'][u'asset_id'],\n m[u'metadata'][u'revision_id'],\n m[u'metadata'][u'name'],\n m[u'metadata'][u'commit_info'][u'committed_at']) for m in\n script_resources]\n\n self._list(script_values, [u'GUID', u'REVISION_ID', u'NAME', u'REVISION_COMMIT'], limit, _DEFAULT_LIST_LENGTH)",
"def list_versions(self):\n version_url = self._get_base_version_url()\n\n resp, body = self.raw_request(version_url, 'GET')\n # NOTE: We need a raw_request() here instead of request() call because\n # \"list API versions\" API doesn't require an authentication and we can\n # skip it with raw_request() call.\n self._error_checker(resp, body)\n\n body = json.loads(body)\n self.validate_response(schema.list_versions, resp, body)\n return rest_client.ResponseBody(resp, body)",
"def history():\n \"\"\"Show portfolio of stocks\"\"\"\n all_rows = []\n rows = db.execute(\"SELECT * FROM history WHERE id = :id\",\n id=session['user_id'])\n if rows==None or len(rows) < 1:\n return render_template(\"history.html\", all_rows=all_rows)\n else:\n for row in rows:\n share_row = []\n share_row.append(row[\"symbol\"])\n share_row.append(row[\"shares\"])\n share_row.append(usd(row[\"price\"]))\n share_row.append(row[\"transacted\"])\n all_rows.append(share_row)\n return render_template(\"history.html\", all_rows=all_rows)",
"def get_revision_list(self):\n response = self._get_request(\n DeckhandClient.get_path(DeckhandPaths.REVISION_LIST)\n )\n self._handle_bad_response(response)\n revisions = yaml.safe_load(response.text)\n return revisions.get('results', [])",
"def index(self, request):\n versions = []\n for key, data in VERSIONS.items():\n v = BaseVersion(\n data[\"id\"],\n data[\"status\"],\n request.application_url,\n data[\"updated\"])\n versions.append(v)\n return wsgi.Result(VersionsDataView(versions))",
"def test_list_versions(self):\n self.metadata.create_or_update(data=self.create)\n\n # Find by name\n res_name = self.metadata.get_by_name(\n entity=Dashboard, fqn=self.entity.fullyQualifiedName\n )\n\n res = self.metadata.get_list_entity_versions(\n entity=Dashboard, entity_id=res_name.id.__root__\n )\n assert res",
"def create_interaction_model_catalog_version_v1(self, catalog_id, catalog, **kwargs):\n # type: (str, VersionData_af79e8d3, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_catalog_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'catalog' is set\n if ('catalog' not in params) or (params['catalog'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'catalog' in params:\n body_params = params['catalog']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Returns update status location link on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the catalog definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified catalog does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def history(self, maxresults=None, mindate=None):\n servers = [x for x in self.resources() if x.provides == 'server' and x.owned]\n hist = []\n for server in servers:\n conn = server.connect()\n hist.extend(conn.history(maxresults=maxresults, mindate=mindate, accountID=1))\n return hist",
"def all(self):\r\n if self._versions is None or \\\r\n len(self._versions) == 0:\r\n url = \"%s/versions\" % self._url\r\n params = {'f':'json'}\r\n res = self._con.get(url, params)\r\n self._versions = []\r\n if 'versions' in res:\r\n for v in res['versions']:\r\n guid = v['versionGuid'][1:-1]\r\n vurl = \"%s/versions/%s\" % (self._url, guid)\r\n self._versions.append(Version(url=vurl,\r\n flc=self._flc,\r\n gis=self._gis))\r\n return self._versions\r\n return self._versions",
"def ListVersions(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def get_all_versions(self, headers=None, **params):\r\n return self._get_all([('Version', self.key_class),\r\n ('CommonPrefixes', Prefix),\r\n ('DeleteMarker', DeleteMarker)],\r\n 'versions', headers, **params)",
"def get_historical_quotes(\n self, symbol: str, interval: str = None, start: date = None, end: date = None\n ) -> List[HistoricQuote]:\n url = \"/v1/markets/history\"\n params = {\"symbol\": symbol, \"interval\": interval, \"start\": start, \"end\": end}\n\n data = self.get(url, params)\n res = MarketsAPIResponse(**data)\n return res.history.day",
"def listHistory(*args, allConnections: bool=True, allFuture: bool=True, allGraphs: bool=True,\n breadthFirst: bool=True, future: bool=True, futureLocalAttr: bool=True,\n futureWorldAttr: bool=True, groupLevels: bool=True, historyAttr: bool=True,\n interestLevel: int=0, leaf: bool=True, levels: int=0, pruneDagObjects:\n bool=True, q=True, query=True, **kwargs)->Union[List[AnyStr], Any]:\n pass",
"def history():\n\n rows = db.execute('SELECT operation, symbol, shares, price, date FROM transactions WHERE id = :id',\n id=session['user_id'])\n\n return render_template('history.html', stocks=rows[::-1])"
] | [
"0.5942459",
"0.55616015",
"0.5546318",
"0.54795104",
"0.53538805",
"0.53490853",
"0.5348747",
"0.52081084",
"0.5199304",
"0.51704663",
"0.51683384",
"0.51576775",
"0.51349646",
"0.511972",
"0.51145464",
"0.5093436",
"0.50895435",
"0.50717413",
"0.50488883",
"0.50439376",
"0.5027778",
"0.5019758",
"0.49968797",
"0.49945092",
"0.4986591",
"0.49810848",
"0.49704388",
"0.49663952",
"0.493943",
"0.49359807"
] | 0.64333284 | 0 |
Create a new version of catalog entity for the given catalogId. | def create_interaction_model_catalog_version_v1(self, catalog_id, catalog, **kwargs):
# type: (str, VersionData_af79e8d3, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "create_interaction_model_catalog_version_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'catalog_id' is set
if ('catalog_id' not in params) or (params['catalog_id'] is None):
raise ValueError(
"Missing the required parameter `catalog_id` when calling `" + operation_name + "`")
# verify the required parameter 'catalog' is set
if ('catalog' not in params) or (params['catalog'] is None):
raise ValueError(
"Missing the required parameter `catalog` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'catalog_id' in params:
path_params['catalogId'] = params['catalog_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'catalog' in params:
body_params = params['catalog']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message="Returns update status location link on success."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error e.g. the catalog definition is invalid."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The specified catalog does not exist."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def save_catalog(self, catalog_form, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinAdminSession.update_bin\n if catalog_form.is_for_update():\n return self.update_catalog(catalog_form, *args, **kwargs)\n else:\n return self.create_catalog(catalog_form, *args, **kwargs)",
"def catalog_create(self, args):\n try:\n if args.id and self.server.connect_ermrest(args.id).exists():\n print(\"Catalog already exists\")\n return\n owner = args.owner if args.owner else None\n catalog = self.server.create_ermrest_catalog(args.id, owner)\n if args.auto_configure:\n model = catalog.getCatalogModel()\n model.configure_baseline_catalog(**args.configure_args)\n if not args.quiet:\n print(\"Created new catalog %s with the following default configuration:\\n\" % catalog.catalog_id)\n pp(catalog.get('/').json())\n except HTTPError as e:\n if e.response.status_code == requests.codes.not_found:\n raise ResourceException('Catalog not found', e)\n elif e.response.status_code == requests.codes.conflict:\n raise ResourceException(\"Catalog already exists\", e)\n else:\n raise e",
"def upload_catalog(self, catalog: Catalog) -> None:\n self._status.check_authority_for_draft()\n\n put_data: Dict[str, Any] = {\"catalog\": catalog.dumps()}\n if not put_data:\n raise TypeError(\"Empty catalog\")\n put_data.update(self._status.get_status_info())\n\n self._client.open_api_do(\"PUT\", \"labels/catalogs\", self.dataset_id, json=put_data)",
"def catalog_id(self, catalog_id):\n self._catalog_id = catalog_id",
"def create_interaction_model_catalog_v1(self, catalog, **kwargs):\n # type: (DefinitionData_ccdbb3c2, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, CatalogResponse_2f6fe800]\n operation_name = \"create_interaction_model_catalog_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog' is set\n if ('catalog' not in params) or (params['catalog'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'catalog' in params:\n body_params = params['catalog']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.catalog_response.CatalogResponse\", status_code=200, message=\"Returns the generated catalogId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the catalog definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=412, message=\"Precondition failed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.catalog_response.CatalogResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_catalog_v0(self, create_catalog_request, **kwargs):\n # type: (CreateCatalogRequest_f3cdf8bb, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, CatalogDetails_912693fa, Error_d660d58]\n operation_name = \"create_catalog_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'create_catalog_request' is set\n if ('create_catalog_request' not in params) or (params['create_catalog_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_catalog_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/catalogs'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_catalog_request' in params:\n body_params = params['create_catalog_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\", status_code=201, message=\"Catalog created.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_catalog(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinAdminSession.create_bin\n return Catalog(\n self._provider_manager,\n self._get_provider_session('catalog_admin_session').create_catalog(*args, **kwargs),\n self._runtime,\n self._proxy)",
"def catalog_key(catalog_name=DEFAULT_CATALOG_NAME):\n return ndb.Key('Catalog', catalog_name)",
"def catalog_clone(self, args):\n try:\n catalog = self.server.connect_ermrest(args.id)\n print(\"Attempting to clone catalog %s into new catalog. Please wait...\" % args.id)\n dest_cat = catalog.clone_catalog(copy_data=args.no_copy_data,\n copy_annotations=args.no_copy_annotations,\n copy_policy=args.no_copy_policy,\n truncate_after=args.no_truncate_after,\n exclude_schemas=args.exclude_schemas)\n print(\"Catalog successfully cloned into new catalog: %s\" % dest_cat.catalog_id)\n except HTTPError as e:\n if e.response.status_code == requests.codes.not_found:\n raise ResourceException('Catalog not found', e)\n else:\n raise e",
"def get_catalog_v0(self, catalog_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, CatalogDetails_912693fa, Error_d660d58]\n operation_name = \"get_catalog_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\", status_code=200, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\")\n\n if full_response:\n return api_response\n return api_response.body",
"def build_catalog_info(self, catalog_info):\n cat = SourceFactory.build_catalog(**catalog_info)\n catalog_info['catalog'] = cat\n # catalog_info['catalog_table'] =\n # Table.read(catalog_info['catalog_file'])\n catalog_info['catalog_table'] = cat.table\n catalog_info['roi_model'] =\\\n SourceFactory.make_fermipy_roi_model_from_catalogs([cat])\n catalog_info['srcmdl_name'] =\\\n self._name_factory.srcmdl_xml(sourcekey=catalog_info['catalog_name'])\n return CatalogInfo(**catalog_info)",
"def associate_catalog_with_skill_v0(self, skill_id, catalog_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, Error_d660d58]\n operation_name = \"associate_catalog_with_skill_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/skills/{skillId}/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def initCatalog():\n catalog = model.newCatalog()\n return catalog",
"def initCatalog():\n catalog = model.newCatalog()\n return catalog",
"def initCatalog():\n catalog = model.newCatalog()\n return catalog",
"def newCatalog(sgml):\n ret = libxml2mod.xmlNewCatalog(sgml)\n if ret is None:raise treeError('xmlNewCatalog() failed')\n return catalog(_obj=ret)",
"def get_interaction_model_catalog_version_v1(self, catalog_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, CatalogVersionData_86156352]\n operation_name = \"get_interaction_model_catalog_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.version.catalog_version_data.CatalogVersionData\", status_code=200, message=\"Returns the catalog version metadata for the given catalogId and version.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no catalog defined for the catalogId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.version.catalog_version_data.CatalogVersionData\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_interaction_model_catalog_definition_v1(self, catalog_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, CatalogDefinitionOutput_21703cd9]\n operation_name = \"get_interaction_model_catalog_definition_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.catalog_definition_output.CatalogDefinitionOutput\", status_code=200, message=\"the catalog definition\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"The catalog cannot be retrieved due to errors listed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no catalog defined for the catalogId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.catalog.catalog_definition_output.CatalogDefinitionOutput\")\n\n if full_response:\n return api_response\n return api_response.body",
"def POST(self, uri='catalog'):\n # content negotiation\n content_type = negotiated_content_type(self.supported_types, self.default_content_type)\n\n # registry acl enforcement\n allowed = web.ctx.ermrest_registry.can_create(web.ctx.webauthn2_context.attributes)\n if not allowed:\n raise rest.Forbidden(uri)\n\n # optional input\n docstr = web.ctx.env['wsgi.input'].read().decode().strip()\n if docstr:\n try:\n doc = json.loads(docstr)\n except:\n raise exception.rest.BadRequest('Could not deserialize JSON input.')\n else:\n doc = {}\n\n owner = doc.get('owner')\n annotations = doc.get('annotations')\n\n # create the catalog instance\n catalog_id = web.ctx.ermrest_registry.claim_id(id=doc.get('id'), id_owner=owner)\n catalog = web.ctx.ermrest_catalog_factory.create(catalog_id)\n\n # initialize the catalog instance\n pc = sanepg2.PooledConnection(catalog.dsn)\n try:\n next(pc.perform(lambda conn, cur: catalog.init_meta(conn, cur, owner=owner, annotations=annotations)))\n finally:\n pc.final()\n\n # register the catalog descriptor\n entry = web.ctx.ermrest_registry.register(catalog_id, descriptor=catalog.descriptor)\n\n web.header('Content-Type', content_type)\n web.ctx.ermrest_request_content_type = content_type\n\n # set location header and status\n location = '/ermrest/catalog/%s' % catalog_id\n web.header('Location', location)\n web.ctx.status = '201 Created'\n\n if content_type == _text_plain:\n return str(catalog_id)\n else:\n assert content_type == _application_json\n return json.dumps(dict(id=catalog_id))",
"def init():\n catalog = model.newCatalog()\n return catalog",
"def _build_catalog_node(self, catalog, language, resource, project, modified, long_modified):\n lid = TsV2CatalogHandler.sanitize_identifier(language['identifier'], lower=False)\n rid = TsV2CatalogHandler.sanitize_identifier(resource['identifier'])\n pid = TsV2CatalogHandler.sanitize_identifier(project['identifier'])\n\n # TRICKY: v2 api sorted obs with 1\n if pid == 'obs': project['sort'] = 1\n\n TsV2CatalogHandler._init_catalog_node(catalog, pid, lid, rid)\n\n # TRICKY: we must process the modified date in the order of resource, language, project to propagate dates correctly\n\n # resource\n res = catalog[pid]['_langs'][lid]['_res'][rid]\n r_modified = max_modified_date(res, modified) # TRICKY: dates bubble up from project\n r_long_modified = max_long_modified_date(res, long_modified) # TRICKY: dates bubble up from project\n comments = '' # TRICKY: comments are not officially supported in RCs but we use them if available\n if 'comment' in resource: comments = resource['comment']\n\n # add chunks to non-obs projects\n chunks_url = ''\n if rid != 'obs':\n chunks_url = 'https://api.unfoldingword.org/bible/txt/1/{}/chunks.json'.format(pid)\n # if not self.url_exists(chunks_url) and 'chunks_url' in project:\n # Use the v3 api chunks url if the legacy version cannot be found\n # chunks_url = project['chunks_url']\n\n source_url = '{}/{}/{}/{}/{}/v{}/source.json?date_modified={}'.format(\n self.cdn_url,\n TsV2CatalogHandler.cdn_root_path,\n pid, lid, rid, resource['version'], r_modified)\n source_text = ''\n source_text_version = ''\n if resource['source']:\n # TRICKY: some resources don't have a source\n source_text = resource['source'][0]['language']\n source_text_version = resource['source'][0]['version']\n # else:\n # self.report_error('Missing source translation in {} {}'.format(lid, rid))\n res.update({\n 'date_modified': r_modified,\n 'long_date_modified': r_long_modified,\n 'name': resource['title'],\n 'notes': '',\n 'slug': rid,\n 'status': {\n 'checking_entity': ', '.join(resource['checking']['checking_entity']),\n 'checking_level': resource['checking']['checking_level'],\n 'comments': comments,\n 'contributors': '; '.join(resource['contributor']),\n 'publish_date': resource['issued'],\n 'source_text': source_text, # v2 can only handle one source\n 'source_text_version': source_text_version, # v2 can only handle one source\n 'version': resource['version']\n },\n 'checking_questions': '',\n 'chunks': chunks_url,\n 'source': source_url,\n 'terms': '',\n 'tw_cat': ''\n })\n\n # TRICKY: use english tw catalog for all languages\n res.update({\n 'tw_cat': '{}/{}/{}/{}/tw_cat.json?date_modified={}'.format(\n self.cdn_url,\n TsV2CatalogHandler.cdn_root_path,\n pid, 'en', r_modified)\n })\n\n # bible projects have usfm\n if pid != 'obs':\n if 'formats' in project:\n for format in project['formats']:\n if 'text/usfm' == format['format'] or 'text/usfm3' == format['format'] or 'text/usfm2' == format['format']:\n res.update({\n 'usfm': '{}?date_modified={}'.format(format['url'], r_modified)\n })\n break\n\n # language\n lang = catalog[pid]['_langs'][lid]\n l_modified = max_modified_date(lang['language'], r_modified) # TRICKY: dates bubble up from resource\n l_long_modified = max_long_modified_date(lang['language'], r_long_modified) # TRICKY: dates bubble up from resource\n description = ''\n if rid == 'obs': description = resource['description']\n project_meta = list(project['categories']) # default to category ids\n if 'category_labels' in language:\n project_meta = []\n for cat_id in project['categories']:\n if cat_id in language['category_labels']:\n project_meta.append(language['category_labels'][cat_id])\n else:\n project_meta.append(cat_id)\n\n cat_lang = {\n 'language': {\n 'date_modified': l_modified,\n 'long_date_modified': l_long_modified,\n 'direction': language['direction'],\n 'name': language['title'],\n 'slug': lid\n },\n 'project': {\n 'desc': description,\n 'meta': project_meta,\n 'name': project['title']\n },\n 'res_catalog': '{}/{}/{}/{}/resources.json?date_modified={}'.format(self.cdn_url,\n TsV2CatalogHandler.cdn_root_path, pid,\n lid, l_modified)\n }\n if project['sort']:\n cat_lang['project']['sort'] = '{}'.format(project['sort'])\n lang.update(cat_lang)\n\n # project\n p_modified = max_modified_date(catalog[pid], l_modified)\n p_long_modified = max_long_modified_date(catalog[pid], l_long_modified)\n catalog[pid].update({\n 'date_modified': p_modified,\n 'long_date_modified': p_long_modified,\n 'lang_catalog': '{}/{}/{}/languages.json?date_modified={}'.format(self.cdn_url,\n TsV2CatalogHandler.cdn_root_path, pid,\n p_modified),\n 'meta': project['categories'],\n 'slug': pid,\n 'sort': '{}'.format(project['sort']).zfill(2)\n })",
"def update_catalog(self, *args, **kwargs):\n # Implemented from kitosid template for -\n # osid.resource.BinAdminSession.update_bin\n # OSID spec does not require returning updated catalog\n return Catalog(\n self._provider_manager,\n self._get_provider_session('catalog_admin_session').update_catalog(*args, **kwargs),\n self._runtime,\n self._proxy)",
"def from_catalog(cls, catalog):\n objects = [Object.from_object(obj) for obj in catalog.objects]\n return Catalog(objects, catalog._chooser)",
"def create_version_on_save(context, event):\n # according to Products.CMFEditions' update_version_on_edit script\n\n # only version the modified object, not its container on modification\n if IContainerModifiedEvent.providedBy(event):\n return\n\n # XXX dirty hack for stagingbehavior, which triggers a event with\n # a aq_based context when deleting the working copy\n try:\n pr = context.portal_repository\n except AttributeError:\n return\n\n if not pr.isVersionable(context):\n # cancel, the object is not versionable\n return\n\n create_version = False\n\n if getattr(context, \"REQUEST\", None):\n changeNote = get_change_note(context.REQUEST, None)\n else:\n changeNote = None\n\n if changeNote:\n # user has entered a change note. create a new version even if nothing\n # has changed.\n create_version = True\n\n elif pr.supportsPolicy(context, \"at_edit_autoversion\"):\n # automatic versioning is enabled for this portal type\n\n if not base_hasattr(context, \"version_id\"):\n # we do not have a initial version\n create_version = True\n else:\n try:\n create_version = not pr.isUpToDate(context, context.version_id)\n except ArchivistUnregisteredError:\n # The object is not actually registered, but a version is\n # set, perhaps it was imported, or versioning info was\n # inappropriately destroyed\n create_version = True\n\n # create new version if needed\n if create_version:\n pr.save(obj=context, comment=changeNote)",
"def create_initial_version_after_adding(context, event):\n\n pr = getToolByName(context, \"portal_repository\", None)\n if pr is None:\n # This can happen, e.g., when adding a Plone Site with versioning\n # and portal_repository is not yet created\n return\n\n if not pr.isVersionable(context):\n # object is not versionable\n return\n\n if not pr.supportsPolicy(context, \"at_edit_autoversion\"):\n # automatic versioning disabled for this portal type, so we don't\n # need to create an initial version\n return\n\n # get the change not\n default_changeNote = _(\"initial_version_changeNote\", default=\"Initial version\")\n if getattr(context, \"REQUEST\", None):\n changeNote = get_change_note(context.REQUEST, default_changeNote)\n else:\n changeNote = None\n\n changed = False\n if not base_hasattr(context, \"version_id\"):\n # no initial version, let's create one..\n changed = True\n\n else:\n try:\n changed = not pr.isUpToDate(context, context.version_id)\n except ArchivistUnregisteredError:\n # The object is not actually registered, but a version is\n # set, perhaps it was imported, or versioning info was\n # inappropriately destroyed\n changed = True\n\n if not changed:\n return\n\n try:\n context.portal_repository.save(obj=context, comment=changeNote)\n except FileTooLargeToVersionError:\n pass # the on edit save will emit a warning",
"def new_version(self, latest_version_id: uplink.Path(name=\"id\")):\n pass",
"def update_interaction_model_catalog_version_v1(self, catalog_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_interaction_model_catalog_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions/{version}/update'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'catalog_update' in params:\n body_params = params['catalog_update']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no catalog defined for the catalogId\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def register_catalog(catalog_name, catalog_config):\n _registered_catalogs[catalog_name] = catalog_config",
"def __init__(self, catalog_path):\n self.catalog_path = catalog_path\n self.load_catalog()\n return",
"def get_by_id(cls, catalog_id):\n return db_session.query(cls).filter(cls.id == catalog_id).first()"
] | [
"0.63733524",
"0.60968757",
"0.59381574",
"0.5849364",
"0.5631473",
"0.56290007",
"0.5573641",
"0.541416",
"0.5320255",
"0.5284916",
"0.51846284",
"0.5158538",
"0.5151632",
"0.5151632",
"0.5151632",
"0.5143142",
"0.50983435",
"0.5016219",
"0.5011444",
"0.48950619",
"0.48684195",
"0.4865647",
"0.48466584",
"0.48168117",
"0.48166585",
"0.48162293",
"0.48089048",
"0.4797754",
"0.4755056",
"0.47543335"
] | 0.64581627 | 0 |
Get catalog version data of given catalog version. | def get_interaction_model_catalog_version_v1(self, catalog_id, version, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, CatalogVersionData_86156352]
operation_name = "get_interaction_model_catalog_version_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'catalog_id' is set
if ('catalog_id' not in params) or (params['catalog_id'] is None):
raise ValueError(
"Missing the required parameter `catalog_id` when calling `" + operation_name + "`")
# verify the required parameter 'version' is set
if ('version' not in params) or (params['version'] is None):
raise ValueError(
"Missing the required parameter `version` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions/{version}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'catalog_id' in params:
path_params['catalogId'] = params['catalog_id']
if 'version' in params:
path_params['version'] = params['version']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.version.catalog_version_data.CatalogVersionData", status_code=200, message="Returns the catalog version metadata for the given catalogId and version."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="There is no catalog defined for the catalogId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.version.catalog_version_data.CatalogVersionData")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def getCatalog(self, version=None, level=None, cubeInfo=True):\n print('WaPOR API: Loading catalog WaPOR.v{v}_l{lv}...'.format(\n v=version, lv=level))\n self.isAPITokenSet()\n\n isFound = False\n\n # if isinstance(version, int) and isinstance(level, int):\n # print('| int')\n # if 0 < version < 3 and 0 < level < 4:\n # print('| range')\n if version == self.version and level == self.level:\n # print('| equal')\n if self.catalog is not None:\n # print('| not None')\n isFound = True\n\n if isFound:\n df = self.catalog\n\n print('WaPOR API: Loading catalog WaPOR.v{v}_l{lv} found.'.format(\n v=version, lv=level))\n else:\n df = self._query_catalog(version, level)\n\n print('WaPOR API: Loading catalog WaPOR.v{v}_l{lv} loaded.'.format(\n v=version, lv=level))\n\n if cubeInfo:\n cubes_measure = []\n cubes_dimension = []\n for cube_code in df['code'].values:\n cubes_measure.append(self._query_cubeMeasures(cube_code))\n cubes_dimension.append(self._query_cubeDimensions(cube_code))\n df['measure'] = cubes_measure\n df['dimension'] = cubes_dimension\n\n self.catalog = df\n return self.catalog",
"def retrieve_catalog(self, catalog_hash):\n return self.repository.retrieve_catalog(catalog_hash)",
"def loadData(catalog):\n return controller.loadData(catalog)",
"def loadData(catalog):\n return controller.loadData(catalog)",
"def get_release_info(self, version):\r\n try:\r\n return self._detail[\"releases\"][version]\r\n except KeyError as key_error:\r\n log.warning(key_error)\r\n return []",
"def read_vsys_data(command, version):\n # Send request through vsys (for slice context).\n data = read_vsys_data_direct(command)\n\n if 'data' not in data:\n collectd.error('%s: returned value has no \"data\" field.' % command)\n return {}\n\n if 'version' not in data:\n collectd.error('%s: returned value has no \"version\" field.' % command)\n return {}\n\n if 'message_type' in data and data['message_type'] != command:\n collectd.error('Returned message_type does not match request.')\n collectd.error('Requested: %s' % command)\n collectd.error('Received : %s' % data['message_type'])\n return {}\n\n if data['version'] != version:\n msg = '%s: version mismatch: found (%d), expected (%d)' % (\n command, data['version'], version)\n collectd.warning(msg)\n\n return data['data']",
"def get_catalog(self) -> Catalog:\n params: Dict[str, Any] = self._status.get_status_info()\n\n response = self._client.open_api_do(\n \"GET\", \"labels/catalogs\", self.dataset_id, params=params\n ).json()\n return Catalog.loads(response[\"catalog\"])",
"def get_catalog(self) -> Dict[str, str]:\n return self.catalog",
"def getversion_context(self,category, version):\r\n return self[category][version]",
"def get_svn_version():\n return crds.__version__",
"def get_version_details(self, project_id, document_id, version=None):\n url = base_url + 'portal/' + str(self.portal_id) + '/projects/' + str(project_id) + '/documents/' + str(document_id) + '/'\n if version is not None: \n param = {\n 'version': version\n }\n else:\n param = None\n response = zoho_http_client.get(url, self.details, param)\n return parser.get_documents(response)[0]",
"def get_version(self):\n return self.http_call(\"get\", url=f\"{self.base_url}/version\").json()",
"def split_comp_info_dict(self, catalog_name, split_ver):\n return self._split_comp_info_dicts[\"%s_%s\" % (catalog_name, split_ver)]",
"def get_version(self):\n verxml = self._ncc.nxoscli('show version')\n self.logger.debug(verxml)\n verparsed = _begin_parse(verxml)\n sysmgrclischema = parse_get_nsmap(verparsed)\n self.logger.debug(\"NSMAP: {}\".format(sysmgrclischema))\n showversion = find_element(['sys_ver_str', 'chassis_id', 'host_name', 'loader_ver_str'], sysmgrclischema,\n verparsed)\n self.logger.debug(str(showversion))\n self.hostname = showversion['host_name']\n self.chassis_id = showversion['chassis_id']\n self.system_version = showversion['sys_ver_str']",
"def get_version_info(self):\n return self._jadeRpc('get_version_info')",
"def load_catalog(self):\n self.catalog = pd.read_csv(self.catalog_path, \n index_col=0, parse_dates=True)\n self.unique_years = self.catalog.index.year.unique()\n return",
"def show_version(self, version):\n\n version_url = urljoin(self._get_base_version_url(), version + '/')\n headers = self.get_headers()\n headers['X-Auth-Token'] = self.token\n resp, body = self.raw_request(version_url, 'GET', headers=headers)\n self._error_checker(resp, body)\n body = json.loads(body)\n self.validate_response(schema.volume_api_version_details, resp, body)\n return rest_client.ResponseBody(resp, body)",
"def getData(version, scriptPath):\n print(\"getData\")\n popd=os.getcwd()\n dssvuePath = \"C:/Program Files (x86)/HEC/HEC-DSSVue/\"\n os.chdir(dssvuePath)\n # Path to script that extracts data from DSS file\n with open(scriptPath + \"version.txt\", 'wb') as vFile:\n pickle.dump([version], vFile)\n # Use HEC-DSSVue to run script (only way to use hec package that accesses DSS files)\n print(\"HEC-DSSVue.cmd\", \"-s\", scriptPath + \"getStageData.py\")\n call([\"HEC-DSSVue.cmd\", \"-s\", scriptPath + \"getStageData.py\"], shell=True)\n os.chdir(popd)",
"def get_version(self):\n return self.__make_api_call('get/version')",
"def get(self):\n return {'version': get_version()}",
"def get_version(self) -> Dict[str, str]:\n return self.http.get(self.config.paths.version)",
"def read_versionInfo(self):\n # PROTECTED REGION ID(SdpMasterLeafNode.versionInfo_read) ENABLED START #\n return self.attr_map[\"versionInfo\"]\n # PROTECTED REGION END # // SdpMasterLeafNode.versionInfo_read",
"def get_version_info():\n from docplex.cp.model import CpoModel\n try:\n with CpoSolver(CpoModel()) as slvr:\n return slvr.agent.version_info\n except:\n if config.context.log_exceptions:\n traceback.print_exc()\n pass\n return {}",
"def get_catalog():\n return jsonify(getCatalog())",
"def version(self, version: Optional[str]) -> Optional[ChartVersionInfo]:\n if version is None or version == \"\":\n return self.latest\n\n versionspec = semantic_version.SimpleSpec(version)\n\n for r in self.versions:\n if versionspec.match(r.version_info):\n return r\n return None",
"def get_version():\n\n with open('__init__.py') as f:\n for line in f.readlines():\n if '__version__' in line:\n apicem_version = line.strip().split(\"=\")[-1].strip(\" '\")\n if '__first_release_date__' in line:\n first_release_data_str = line.strip().split(\"=\")[-1].strip(\" '\")\n first_release_data = date(*[int(num) for num in first_release_data_str.split('.')])\n num_commits = get_cr_num(first_release_data)\n return '{apicem_version}.{num_commits}'.format(\n apicem_version=apicem_version, num_commits=num_commits)\n\n raise ValueError(\"could not read version\")",
"def get_version(self):\n res = requests.get(self.base_url + '/version')\n\n return res",
"def GetDataVersion(**argd):\n flag, ret = CGateway.core.GetCurrentDataVersion(argd[\"session\"])\n xFlag = CGateway._HandleExceptionAndUnauthorized(flag, ret, argd[\"session\"])\n if xFlag is not None:\n return xFlag\n return CGateway._SuccessResponse({'return': ret})",
"def _get_catalog_object(self):\n return self.cluster.catalogd.service.read_debug_webpage(\n \"catalog_object?object_type=TABLE&object_name=functional.alltypes\")",
"def _get_version(self):\n if _cbc_version is None:\n return _extract_version('')\n return _cbc_version"
] | [
"0.62205946",
"0.6113081",
"0.6053204",
"0.6053204",
"0.6001308",
"0.59186375",
"0.5852233",
"0.5814686",
"0.5786393",
"0.57854307",
"0.57852215",
"0.57809806",
"0.5762735",
"0.5731641",
"0.5727272",
"0.5722372",
"0.5708852",
"0.56849897",
"0.5638192",
"0.56319714",
"0.56276083",
"0.56234396",
"0.56209636",
"0.5581769",
"0.55690783",
"0.5563099",
"0.5540318",
"0.5499245",
"0.54964006",
"0.54845566"
] | 0.6464466 | 0 |
Get catalog values from the given catalogId & version. | def get_interaction_model_catalog_values_v1(self, catalog_id, version, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, CatalogValues_ef5c3823, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "get_interaction_model_catalog_values_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'catalog_id' is set
if ('catalog_id' not in params) or (params['catalog_id'] is None):
raise ValueError(
"Missing the required parameter `catalog_id` when calling `" + operation_name + "`")
# verify the required parameter 'version' is set
if ('version' not in params) or (params['version'] is None):
raise ValueError(
"Missing the required parameter `version` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions/{version}/values'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'catalog_id' in params:
path_params['catalogId'] = params['catalog_id']
if 'version' in params:
path_params['version'] = params['version']
query_params = [] # type: List
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.version.catalog_values.CatalogValues", status_code=200, message="Returns list of catalog values for the given catalogId and version."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="There is no catalog defined for the catalogId"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.version.catalog_values.CatalogValues")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_interaction_model_catalog_version_v1(self, catalog_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, CatalogVersionData_86156352]\n operation_name = \"get_interaction_model_catalog_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.version.catalog_version_data.CatalogVersionData\", status_code=200, message=\"Returns the catalog version metadata for the given catalogId and version.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no catalog defined for the catalogId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.version.catalog_version_data.CatalogVersionData\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_catalog_v0(self, catalog_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, CatalogDetails_912693fa, Error_d660d58]\n operation_name = \"get_catalog_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\", status_code=200, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v0.catalog.catalog_details.CatalogDetails\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_items_for_catalog(catalog_id):\n pass",
"def retrieve_catalog(self, catalog_hash):\n return self.repository.retrieve_catalog(catalog_hash)",
"async def get_catalog(self, board_id):\n\n route = f'{board_id}/catalog'\n\n data = await self.interact(route)\n\n value = Asset(data)\n\n return value",
"def split_comp_info_dict(self, catalog_name, split_ver):\n return self._split_comp_info_dicts[\"%s_%s\" % (catalog_name, split_ver)]",
"def getCatalog(unique_name):",
"def getCatalogs():",
"def getCatalog(self, version=None, level=None, cubeInfo=True):\n print('WaPOR API: Loading catalog WaPOR.v{v}_l{lv}...'.format(\n v=version, lv=level))\n self.isAPITokenSet()\n\n isFound = False\n\n # if isinstance(version, int) and isinstance(level, int):\n # print('| int')\n # if 0 < version < 3 and 0 < level < 4:\n # print('| range')\n if version == self.version and level == self.level:\n # print('| equal')\n if self.catalog is not None:\n # print('| not None')\n isFound = True\n\n if isFound:\n df = self.catalog\n\n print('WaPOR API: Loading catalog WaPOR.v{v}_l{lv} found.'.format(\n v=version, lv=level))\n else:\n df = self._query_catalog(version, level)\n\n print('WaPOR API: Loading catalog WaPOR.v{v}_l{lv} loaded.'.format(\n v=version, lv=level))\n\n if cubeInfo:\n cubes_measure = []\n cubes_dimension = []\n for cube_code in df['code'].values:\n cubes_measure.append(self._query_cubeMeasures(cube_code))\n cubes_dimension.append(self._query_cubeDimensions(cube_code))\n df['measure'] = cubes_measure\n df['dimension'] = cubes_dimension\n\n self.catalog = df\n return self.catalog",
"def get_catalog(self) -> Dict[str, str]:\n return self.catalog",
"def getversion_context(self,category, version):\r\n return self[category][version]",
"def split_comp_info(self, catalog_name, split_ver, split_key):\n return self._split_comp_info_dicts[\"%s_%s\" % (catalog_name, split_ver)][split_key]",
"def catalog_components(self, catalog_name, split_ver):\n return sorted(self._split_comp_info_dicts[\"%s_%s\" % (catalog_name, split_ver)].keys())",
"def get(self):\n return GenericGet().get_catalogs()",
"def get_catalog(self) -> Catalog:\n params: Dict[str, Any] = self._status.get_status_info()\n\n response = self._client.open_api_do(\n \"GET\", \"labels/catalogs\", self.dataset_id, params=params\n ).json()\n return Catalog.loads(response[\"catalog\"])",
"def get_v3_catalog(self, user_id, tenant_id, metadata=None):\n v2_catalog = self.get_catalog(user_id, tenant_id, metadata=metadata)\n v3_catalog = []\n\n for region_name, region in six.iteritems(v2_catalog):\n for service_type, service in six.iteritems(region):\n service_v3 = {\n 'type': service_type,\n 'endpoints': []\n }\n\n for attr, value in six.iteritems(service):\n # Attributes that end in URL are interfaces. In the V2\n # catalog, these are internalURL, publicURL, and adminURL.\n # For example, <region_name>.publicURL=<URL> in the V2\n # catalog becomes the V3 interface for the service:\n # { 'interface': 'public', 'url': '<URL>', 'region':\n # 'region: '<region_name>' }\n if attr.endswith('URL'):\n v3_interface = attr[:-len('URL')]\n service_v3['endpoints'].append({\n 'interface': v3_interface,\n 'region': region_name,\n 'url': value,\n })\n continue\n\n # Other attributes are copied to the service.\n service_v3[attr] = value\n\n v3_catalog.append(service_v3)\n\n return v3_catalog",
"def get_release_info(self, version):\r\n try:\r\n return self._detail[\"releases\"][version]\r\n except KeyError as key_error:\r\n log.warning(key_error)\r\n return []",
"def getvversionpreferencescatalogoffers(\n self, version, ms_correlation_id=None, ms_request_id=None, custom_headers=None, raw=False, **operation_config):\n # Construct URL\n url = self.getvversionpreferencescatalogoffers.metadata['url']\n path_format_arguments = {\n 'version': self._serialize.url(\"version\", version, 'str')\n }\n url = self._client.format_url(url, **path_format_arguments)\n\n # Construct parameters\n query_parameters = {}\n\n # Construct headers\n header_parameters = {}\n header_parameters['Content-Type'] = 'application/json; charset=utf-8'\n if self.config.generate_client_request_id:\n header_parameters['x-ms-client-request-id'] = str(uuid.uuid1())\n if custom_headers:\n header_parameters.update(custom_headers)\n if ms_correlation_id is not None:\n header_parameters['MS-CorrelationId'] = self._serialize.header(\"ms_correlation_id\", ms_correlation_id, 'str')\n if ms_request_id is not None:\n header_parameters['MS-RequestId'] = self._serialize.header(\"ms_request_id\", ms_request_id, 'str')\n if self.config.accept_language is not None:\n header_parameters['accept-language'] = self._serialize.header(\"self.config.accept_language\", self.config.accept_language, 'str')\n\n # Construct and send request\n request = self._client.get(url, query_parameters)\n response = self._client.send(request, header_parameters, stream=False, **operation_config)\n\n if response.status_code not in [200, 201, 400, 401, 403, 404, 500]:\n exp = CloudError(response)\n exp.request_id = response.headers.get('x-ms-request-id')\n raise exp\n\n deserialized = None\n\n if response.status_code in [200, 201]:\n deserialized = self._deserialize('[str]', response)\n\n if raw:\n client_raw_response = ClientRawResponse(deserialized, response)\n return client_raw_response\n\n return deserialized",
"def slice(self, keys: list[str]) -> Catalog:\n cat_cp = self.copy()\n cat = Catalog()\n for k in keys:\n for v in cat_cp[k].versions:\n cat[k][v] = cat_cp[k][v]\n return cat",
"def list_interaction_model_catalog_versions_v1(self, catalog_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, ListCatalogEntityVersionsResponse_aa31060e, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"list_interaction_model_catalog_versions_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n if 'sort_field' in params:\n query_params.append(('sortField', params['sort_field']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.version.list_catalog_entity_versions_response.ListCatalogEntityVersionsResponse\", status_code=200, message=\"Returns list of catalogs for the vendor.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the catalog definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified catalog does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.version.list_catalog_entity_versions_response.ListCatalogEntityVersionsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_from_catalogue(self, vnf_id):\n try:\n resp = requests.get('{0}/vnfs'.format(self._tenor_url))\n except:\n raise IOError('{0} instance unreachable'.format(self._tenor_url))\n try:\n json.loads(resp.text)\n except:\n raise ValueError('Decoding last_vnf_id json resp failed')\n single = [x for x in json.loads(resp.text) if x['vnfd']['id'] == vnf_id]\n if len(single) > 0:\n self._vnfd = json.dumps(single[0])\n self._dummy_id = single[0]['vnfd']['id']\n cached = None\n if 'cached' in single[0]['vnfd']['vdu'][0]:\n cached = single[0]['vnfd']['vdu'][0]\n self._vdu = TenorVDU(single[0]['vnfd']['vdu'][0]['vm_image'],\n single[0]['vnfd']['vdu'][0]['vm_image_format'],\n single[0]['vnfd']['deployment_flavours'][0]['flavour_key'],\n cached)\n return single[0]\n else:\n return []",
"def getUserCatalogOnFilespace(fs_id):\n result = None\n session = Queries.createSession()\n try:\n result = session.execute(sqlalchemy.select([Catalog])\n .where(Catalog.fs_id == fs_id)\n .order_by(asc(Catalog.id))\n ).fetchone()\n except sqlalchemy.exc.ArgumentError:\n print 'SQLAlchemy ERROR: Invalid or conflicting function argument is supplied'\n except sqlalchemy.exc.CompileError:\n print 'SQLAlchemy ERROR: Error occurs during SQL compilation'\n finally:\n session.close()\n return result",
"def test_api_ucs_get_catalog(self):\n api_data = request(\"get\", \"/sys\")\n self.assertEqual(api_data['status'], 200,\n 'Incorrect HTTP return code, expected 200, got:' + str(api_data['status']))\n total_elements = 0\n for elementTypes in api_data[\"json\"]:\n for element in api_data[\"json\"][str(elementTypes)]:\n api_data_c = request(\"get\", \"/catalog\",\n query={\"identifier\": element[\"relative_path\"].strip(\"/\")})\n self.assertEqual(api_data_c['status'], 200,\n 'Incorrect HTTP return code, expected 200, got:' +\n str(api_data_c['status']))\n total_elements += 1\n self.assertGreater(total_elements, 0, \"Zero catalog elements found\")\n # TO DO: deeper check on the catalog data",
"def load_catalog(self):\n self.catalog = pd.read_csv(self.catalog_path, \n index_col=0, parse_dates=True)\n self.unique_years = self.catalog.index.year.unique()\n return",
"def create_interaction_model_catalog_version_v1(self, catalog_id, catalog, **kwargs):\n # type: (str, VersionData_af79e8d3, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_catalog_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'catalog' is set\n if ('catalog' not in params) or (params['catalog'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/catalogs/{catalogId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'catalog' in params:\n body_params = params['catalog']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Returns update status location link on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the catalog definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified catalog does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def make_catalog_comp_info_dict(self, catalog_sources):\n catalog_ret_dict = {}\n split_ret_dict = {}\n for key, value in catalog_sources.items():\n if value is None:\n continue\n if value['model_type'] != 'catalog':\n continue\n versions = value['versions']\n for version in versions:\n ver_key = \"%s_%s\" % (key, version)\n source_dict = self.read_catalog_info_yaml(ver_key)\n try:\n full_cat_info = catalog_ret_dict[key]\n except KeyError:\n full_cat_info = self.build_catalog_info(source_dict)\n catalog_ret_dict[key] = full_cat_info\n\n try:\n all_sources = [x.strip() for x in full_cat_info.catalog_table[\n 'Source_Name'].astype(str).tolist()]\n except KeyError:\n print(full_cat_info.catalog_table.colnames)\n used_sources = []\n rules_dict = source_dict['rules_dict']\n if rules_dict is None:\n rules_dict = {}\n split_dict = {}\n for rule_key, rule_val in rules_dict.items():\n # full_key =\\\n # self._name_factory.merged_sourcekey(catalog=ver_key,\n # rulekey=rule_key)\n sources = select_sources(\n full_cat_info.catalog_table, rule_val['cuts'])\n used_sources.extend(sources)\n split_dict[rule_key] = self.make_catalog_comp_info(\n full_cat_info, version, rule_key, rule_val, sources)\n\n # Now deal with the remainder\n for source in used_sources:\n try:\n all_sources.remove(source)\n except ValueError:\n continue\n rule_val = dict(cuts=[],\n merge=source_dict['remainder'].get('merge', False))\n split_dict['remain'] = self.make_catalog_comp_info(\n full_cat_info, version, 'remain', rule_val, all_sources)\n\n # Merge in the info for this version of splits\n split_ret_dict[ver_key] = split_dict\n\n self._catalog_comp_info_dicts.update(catalog_ret_dict)\n self._split_comp_info_dicts.update(split_ret_dict)\n return (catalog_ret_dict, split_ret_dict)",
"def loadData(catalog):\n return controller.loadData(catalog)",
"def loadData(catalog):\n return controller.loadData(catalog)",
"def final_catalogs(self, filename=None, catalog_cols=None):\n\n final_catalog = vstack([cluster_info['catalog'] for cluster_info in self._catalog_dictionary.values()])\n\n # If we request to keep only certain columns in our output\n if catalog_cols is not None:\n final_catalog.keep_columns(catalog_cols)\n\n if filename is None:\n return final_catalog\n else:\n if filename.endswith('.cat'):\n final_catalog.write(filename, format='ascii', overwrite=True)\n else:\n final_catalog.write(filename, overwrite=True)",
"def _query_catalog(self, version=None, level=None):\n print('WaPOR API: _query_catalog')\n\n if isinstance(version, int):\n if 0 < version < 3:\n self.version = version\n else:\n raise ValueError(\n 'WaPOR API ERROR: _query_catalog: Version \"{v}\"'\n ' is not correct!'.format(v=version))\n\n if isinstance(level, int):\n if 0 < level < 4:\n self.level = level\n else:\n raise ValueError(\n 'WaPOR API ERROR: _query_catalog: Level \"{lv}\"'\n ' is not correct!'.format(lv=level))\n elif level is None:\n self.version = version\n else:\n raise ValueError(\n 'WaPOR API ERROR: _query_catalog: Level \"{lv}\"'\n ' is not correct!'.format(lv=level))\n\n if self.level is None:\n base_url = '{0}{1}/cubes?overview=false&paged=false'\n request_url = base_url.format(\n self.path['catalog'],\n self.workspaces[self.version])\n else:\n base_url = '{0}{1}/cubes?overview=false&paged=false&tags=L{2}'\n request_url = base_url.format(\n self.path['catalog'],\n self.workspaces[self.version],\n self.level)\n\n if self.print_job:\n print(request_url)\n\n # requests\n try:\n resq = requests.get(\n request_url)\n resq.raise_for_status()\n except requests.exceptions.HTTPError as err:\n raise Exception(\"WaPOR API Http Error: {e}\".format(e=err))\n except requests.exceptions.ConnectionError as err:\n raise Exception(\"WaPOR API Error Connecting: {e}\".format(e=err))\n except requests.exceptions.Timeout as err:\n raise Exception(\"WaPOR API Timeout Error: {e}\".format(e=err))\n except requests.exceptions.RequestException as err:\n raise Exception(\"WaPOR API OOps: Something Else {e}\".format(e=err))\n else:\n resq_json = resq.json()\n\n try:\n resp = resq_json['response']\n # print(resp)\n\n if resq_json['message'] == 'OK':\n df = pd.DataFrame.from_dict(resp, orient='columns')\n return df\n # return df.sort_values(['code'], ascending=[True])\n else:\n print(resq_json['message'])\n except BaseException:\n print('WaPOR API ERROR: Cannot get {url}'.format(\n url=request_url))"
] | [
"0.6146063",
"0.6006047",
"0.59264326",
"0.58870983",
"0.567133",
"0.5622799",
"0.5576962",
"0.55423224",
"0.55372685",
"0.5530066",
"0.53972703",
"0.539612",
"0.53943086",
"0.53748065",
"0.53272104",
"0.5325469",
"0.52881753",
"0.52529997",
"0.523602",
"0.523346",
"0.52192205",
"0.52077293",
"0.5190316",
"0.51800215",
"0.5154777",
"0.5140498",
"0.50984883",
"0.50984883",
"0.50970936",
"0.50849384"
] | 0.6545546 | 0 |
Creates a new Job Definition from the Job Definition request provided. This can be either a CatalogAutoRefresh, which supports timebased configurations for catalogs, or a ReferencedResourceVersionUpdate, which is used for slotTypes and Interaction models to be automatically updated on the dynamic update of their referenced catalog. | def create_job_definition_for_interaction_model_v1(self, create_job_definition_request, **kwargs):
# type: (CreateJobDefinitionRequest_e3d4c41, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, CreateJobDefinitionResponse_efaa9a6f, ValidationErrors_d42055a1]
operation_name = "create_job_definition_for_interaction_model_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'create_job_definition_request' is set
if ('create_job_definition_request' not in params) or (params['create_job_definition_request'] is None):
raise ValueError(
"Missing the required parameter `create_job_definition_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/jobs'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_job_definition_request' in params:
body_params = params['create_job_definition_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.jobs.create_job_definition_response.CreateJobDefinitionResponse", status_code=201, message="Returns the generated jobId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.jobs.validation_errors.ValidationErrors", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.jobs.create_job_definition_response.CreateJobDefinitionResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def _build_create_job_definition_request(\n self,\n monitoring_schedule_name,\n job_definition_name,\n image_uri,\n latest_baselining_job_name=None,\n latest_baselining_job_config=None,\n existing_job_desc=None,\n endpoint_input=None,\n ground_truth_input=None,\n analysis_config=None,\n output_s3_uri=None,\n constraints=None,\n enable_cloudwatch_metrics=None,\n role=None,\n instance_count=None,\n instance_type=None,\n volume_size_in_gb=None,\n volume_kms_key=None,\n output_kms_key=None,\n max_runtime_in_seconds=None,\n env=None,\n tags=None,\n network_config=None,\n batch_transform_input=None,\n ):\n if existing_job_desc is not None:\n app_specification = existing_job_desc[\n \"{}AppSpecification\".format(self.monitoring_type())\n ]\n baseline_config = existing_job_desc.get(\n \"{}BaselineConfig\".format(self.monitoring_type()), {}\n )\n job_input = existing_job_desc[\"{}JobInput\".format(self.monitoring_type())]\n job_output = existing_job_desc[\"{}JobOutputConfig\".format(self.monitoring_type())]\n cluster_config = existing_job_desc[\"JobResources\"][\"ClusterConfig\"]\n if role is None:\n role = existing_job_desc[\"RoleArn\"]\n existing_network_config = existing_job_desc.get(\"NetworkConfig\")\n stop_condition = existing_job_desc.get(\"StoppingCondition\", {})\n else:\n app_specification = {}\n baseline_config = {}\n job_input = {}\n job_output = {}\n cluster_config = {}\n existing_network_config = None\n stop_condition = {}\n\n # job output\n if output_s3_uri is not None:\n normalized_monitoring_output = self._normalize_monitoring_output(\n monitoring_schedule_name, output_s3_uri\n )\n job_output[\"MonitoringOutputs\"] = [normalized_monitoring_output._to_request_dict()]\n if output_kms_key is not None:\n job_output[\"KmsKeyId\"] = output_kms_key\n\n # app specification\n if analysis_config is None:\n if latest_baselining_job_config is not None:\n analysis_config = latest_baselining_job_config.analysis_config\n elif app_specification:\n analysis_config = app_specification[\"ConfigUri\"]\n else:\n raise ValueError(\"analysis_config is mandatory.\")\n # backfill analysis_config\n if isinstance(analysis_config, str):\n analysis_config_uri = analysis_config\n else:\n analysis_config_uri = self._upload_analysis_config(\n analysis_config._to_dict(), output_s3_uri, job_definition_name, output_kms_key\n )\n app_specification[\"ConfigUri\"] = analysis_config_uri\n app_specification[\"ImageUri\"] = image_uri\n normalized_env = self._generate_env_map(\n env=env, enable_cloudwatch_metrics=enable_cloudwatch_metrics\n )\n if normalized_env:\n app_specification[\"Environment\"] = normalized_env\n\n # baseline config\n if constraints:\n # noinspection PyTypeChecker\n _, constraints_object = self._get_baseline_files(\n statistics=None, constraints=constraints, sagemaker_session=self.sagemaker_session\n )\n constraints_s3_uri = None\n if constraints_object is not None:\n constraints_s3_uri = constraints_object.file_s3_uri\n baseline_config[\"ConstraintsResource\"] = dict(S3Uri=constraints_s3_uri)\n elif latest_baselining_job_name:\n baseline_config[\"BaseliningJobName\"] = latest_baselining_job_name\n\n # job input\n if endpoint_input is not None:\n normalized_endpoint_input = self._normalize_endpoint_input(\n endpoint_input=endpoint_input\n )\n # backfill attributes to endpoint input\n if latest_baselining_job_config is not None:\n if normalized_endpoint_input.features_attribute is None:\n normalized_endpoint_input.features_attribute = (\n latest_baselining_job_config.features_attribute\n )\n if normalized_endpoint_input.inference_attribute is None:\n normalized_endpoint_input.inference_attribute = (\n latest_baselining_job_config.inference_attribute\n )\n if normalized_endpoint_input.probability_attribute is None:\n normalized_endpoint_input.probability_attribute = (\n latest_baselining_job_config.probability_attribute\n )\n if normalized_endpoint_input.probability_threshold_attribute is None:\n normalized_endpoint_input.probability_threshold_attribute = (\n latest_baselining_job_config.probability_threshold_attribute\n )\n job_input = normalized_endpoint_input._to_request_dict()\n elif batch_transform_input is not None:\n # backfill attributes to batch transform input\n if latest_baselining_job_config is not None:\n if batch_transform_input.features_attribute is None:\n batch_transform_input.features_attribute = (\n latest_baselining_job_config.features_attribute\n )\n if batch_transform_input.inference_attribute is None:\n batch_transform_input.inference_attribute = (\n latest_baselining_job_config.inference_attribute\n )\n if batch_transform_input.probability_attribute is None:\n batch_transform_input.probability_attribute = (\n latest_baselining_job_config.probability_attribute\n )\n if batch_transform_input.probability_threshold_attribute is None:\n batch_transform_input.probability_threshold_attribute = (\n latest_baselining_job_config.probability_threshold_attribute\n )\n job_input = batch_transform_input._to_request_dict()\n\n if ground_truth_input is not None:\n job_input[\"GroundTruthS3Input\"] = dict(S3Uri=ground_truth_input)\n\n # cluster config\n if instance_count is not None:\n cluster_config[\"InstanceCount\"] = instance_count\n if instance_type is not None:\n cluster_config[\"InstanceType\"] = instance_type\n if volume_size_in_gb is not None:\n cluster_config[\"VolumeSizeInGB\"] = volume_size_in_gb\n if volume_kms_key is not None:\n cluster_config[\"VolumeKmsKeyId\"] = volume_kms_key\n\n # stop condition\n if max_runtime_in_seconds is not None:\n stop_condition[\"MaxRuntimeInSeconds\"] = max_runtime_in_seconds\n\n request_dict = {\n \"JobDefinitionName\": job_definition_name,\n \"{}AppSpecification\".format(self.monitoring_type()): app_specification,\n \"{}JobInput\".format(self.monitoring_type()): job_input,\n \"{}JobOutputConfig\".format(self.monitoring_type()): job_output,\n \"JobResources\": dict(ClusterConfig=cluster_config),\n \"RoleArn\": self.sagemaker_session.expand_role(role),\n }\n\n if baseline_config:\n request_dict[\"{}BaselineConfig\".format(self.monitoring_type())] = baseline_config\n\n if network_config is not None:\n network_config_dict = network_config._to_request_dict()\n request_dict[\"NetworkConfig\"] = network_config_dict\n elif existing_network_config is not None:\n request_dict[\"NetworkConfig\"] = existing_network_config\n\n if stop_condition:\n request_dict[\"StoppingCondition\"] = stop_condition\n\n if tags is not None:\n request_dict[\"Tags\"] = tags\n\n return request_dict",
"def _create_job(self,\n name,\n environment_string,\n description='',\n platform='LINUX'):\n job = data_types.Job()\n job.name = name\n if environment_string.strip():\n job.environment_string = environment_string\n job.platform = platform\n job.descripton = description\n job.put()\n\n return job",
"def _create_job_spec(\n self,\n job_id: Text,\n training_input: Dict[Text, Any],\n job_labels: Optional[Dict[Text, Text]] = None) -> Dict[Text, Any]:\n\n job_spec = {\n 'display_name': job_id,\n 'job_spec': training_input,\n 'labels': job_labels,\n }\n return job_spec",
"def created_job(new_job, bulk_request):\n bulk_request.return_value = '''<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <jobInfo xmlns=\"http://www.force.com/2009/06/asyncapi/dataload\">\n <id>THEJOBID</id>\n <operation>update</operation>\n <object>Lead</object>\n </jobInfo>\n '''\n new_job.create()\n return new_job",
"def _create_job_spec(\n self,\n job_id: Text,\n training_input: Dict[Text, Any],\n job_labels: Optional[Dict[Text, Text]] = None) -> Dict[Text, Any]:\n\n job_spec = {\n 'jobId': job_id,\n 'trainingInput': training_input,\n 'labels': job_labels,\n }\n return job_spec",
"def create(self, **kwargs):\n url_str = self.base_url\n newheaders = self.get_headers()\n payload = kwargs['definition']\n resp, body = self.client.json_request('POST', url_str,\n data=payload,\n headers=newheaders)\n return resp",
"def get_job_definition_for_interaction_model_v1(self, job_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, JobDefinition_ee5db797, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_job_definition_for_interaction_model_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'job_id' is set\n if ('job_id' not in params) or (params['job_id'] is None):\n raise ValueError(\n \"Missing the required parameter `job_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/jobs/{jobId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'job_id' in params:\n path_params['jobId'] = params['job_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.jobs.job_definition.JobDefinition\", status_code=200, message=\"The job definition for a given jobId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.jobs.job_definition.JobDefinition\")\n\n if full_response:\n return api_response\n return api_response.body",
"def _create_job_spec(\n self,\n job_id: Text,\n training_input: Dict[Text, Any],\n job_labels: Optional[Dict[Text, Text]] = None) -> Dict[Text, Any]:\n pass",
"def set_up_job_definition(self, docker_image=None, job_role_arn=None):\n\n assert (\n docker_image is not None\n ), \"Please specify Docker image for Nextflow head node\"\n\n # Get the list of existing job definitions\n logging.info(\"Checking for a suitable existing job definition\")\n job_definitions = self.get_job_definitions()\n\n # Check to see if there is a job definition that is suitable\n for j in job_definitions:\n\n # Keep this set to true if all elements match\n keep_this_job_definition = True\n\n # Iterate over each fixed element\n for k, value in [\n (\"type\", \"container\"),\n (\"status\", \"ACTIVE\"),\n (\"jobRoleArn\", job_role_arn),\n (\"image\", docker_image),\n ]:\n if value is None:\n continue\n # Check the base namespace, as well as the 'containerProperties'\n # Both 'jobRoleArn' and 'image' are under 'containerProperties'\n if j.get(k, j[\"containerProperties\"].get(k)) != value:\n # If it doesn't match, set the marker to False\n keep_this_job_definition = False\n\n # If everything matches, use this one\n if keep_this_job_definition:\n logging.info(\"Using existing job definition\")\n return \"{}:{}\".format(j[\"jobDefinitionName\"], j[\"revision\"])\n # Otherwise, make a new job definition\n logging.info(\"Making new job definition\")\n \n containerProperties={\n \"image\": docker_image,\n \"vcpus\": int(max(int(self.memory / 4000), 1)),\n \"memory\": self.memory,\n }\n if job_role_arn is not None:\n containerProperties[\"jobRoleArn\"] = job_role_arn\n response = self.batch_client.register_job_definition(\n jobDefinitionName=\"nextflow_head_node\",\n type=\"container\",\n containerProperties=containerProperties,\n )\n\n return \"{}:{}\".format(response[\"jobDefinitionName\"], response[\"revision\"])",
"def sfdcCreateJob(**kwargs):\n api_ver = kwargs.get('api_ver', '')\n session_id = kwargs.get('session_id', '')\n instance = kwargs.get('instance', '')\n job_id = kwargs.get('job_id', '')\n sfdcXml = kwargs.get('sfdcXml', {})\n\n bodyXml = sfdcXml.get('job', {}).get('body')\n url = sfdcXml.get('job', {}).get('url')\n headers = sfdcXml.get('job', {}).get('headers')\n\n bodyXml = unicode(bodyXml, \"utf-8\")\n url = url.format(instance=instance, api_ver=api_ver)\n headers['X-SFDC-Session'] = self.session_id\n\n resp = requests.post(url=url, headers=headers, data=bodyXml)\n dictResp = xmltodict.parse(resp.text)\n job_id = str(dictResp['jobInfo']['id'])\n\n self.job_id = job_id\n return job_id",
"def create_job(api_instance, job):\n api_response = api_instance.create_namespaced_job(\n body=job, namespace=\"default\", pretty=True\n )\n logger.info(\"Job created with status='%s'\" % str(api_response.status))\n return api_response",
"def create(self, resource, **data):\n body = ''\n if resource == 'robot/job':\n body = data['body']\n else:\n body = urllib.urlencode(data)\n\n return self.request('/' + resource, 'POST', body=body)",
"def create(cls, job_id: str) -> \"JobManifest\":\n now = datetime.datetime.now(datetime.timezone.utc)\n return JobManifest(creation_time=now, job_id=job_id, orbit_ids=[], task_ids=[])",
"def createJob(self, joboptions, previousId=None):\n root = self.manifest.getRootResource()\n assert self.manifest.tosca\n job = Job(self, root, joboptions, previousId)\n\n if (\n self.manifest.localEnv\n and not joboptions.parentJob\n and not joboptions.startTime\n ):\n logPath = self.manifest.getJobLogPath(job.getStartTime(), \".log\")\n if not os.path.isdir(os.path.dirname(logPath)):\n os.makedirs(os.path.dirname(logPath))\n initLogging(logfile=logPath)\n path = self.manifest.path\n if joboptions.planOnly:\n logger.info(\"creating %s plan for %s\", joboptions.workflow, path)\n else:\n logger.info(\"starting %s job for %s\", joboptions.workflow, path)\n\n WorkflowPlan = Plan.getPlanClassForWorkflow(joboptions.workflow)\n if not WorkflowPlan:\n raise UnfurlError(\"unknown workflow: %s\" % joboptions.workflow)\n job.plan = WorkflowPlan(root, self.manifest.tosca, joboptions)\n return job",
"def make_instance(self, include_optional):\n # model = kloudio.models.new_job.NewJob() # noqa: E501\n if include_optional :\n return NewJob(\n destination = 'email', \n report_name = 'mysql-report', \n report_id = '57d3273aed8c3e1e1c0d3746', \n report_params = None, \n frequency = 'Hourly', \n am_pm = 'am', \n hour = '01', \n minute = '45', \n day = 'Monday', \n description = 'This is a sample query', \n spreadsheet_id = '1-sl-_DtdBUmbi-FyJOwc2dXGd6xX0xZstX7UzlsU_EA', \n sheet_id = '193832851', \n sheet_name = 'Sales-v2', \n timezone = 'PST', \n select_cols = users, \n tags = 'users', \n email_on_success = True, \n email_on_error = True, \n metadata = None, \n template_id = 'Y-z-jjFZ0H3u3maN', \n template_name = 'Template2404a', \n job_type = 'EMAIL'\n )\n else :\n return NewJob(\n destination = 'email',\n report_name = 'mysql-report',\n report_id = '57d3273aed8c3e1e1c0d3746',\n frequency = 'Hourly',\n am_pm = 'am',\n hour = '01',\n minute = '45',\n day = 'Monday',\n )",
"def create(self, validated_data):\n return Job.objects.create(**validated_data)",
"def create_recurring_run(\n self,\n experiment_id: str,\n job_name: str,\n description: Optional[str] = None,\n start_time: Optional[str] = None,\n end_time: Optional[str] = None,\n interval_second: Optional[int] = None,\n cron_expression: Optional[str] = None,\n max_concurrency: Optional[int] = 1,\n no_catchup: Optional[bool] = None,\n params: Optional[dict] = None,\n pipeline_package_path: Optional[str] = None,\n pipeline_id: Optional[str] = None,\n version_id: Optional[str] = None,\n enabled: bool = True,\n enable_caching: Optional[bool] = None,\n service_account: Optional[str] = None,\n ) -> kfp_server_api.V1Job:\n\n job_config = self._create_job_config(\n experiment_id=experiment_id,\n params=params,\n pipeline_package_path=pipeline_package_path,\n pipeline_id=pipeline_id,\n version_id=version_id,\n enable_caching=enable_caching,\n )\n\n if all([interval_second, cron_expression\n ]) or not any([interval_second, cron_expression]):\n raise ValueError(\n 'Either interval_second or cron_expression is required')\n if interval_second is not None:\n trigger = kfp_server_api.models.V1Trigger(\n periodic_schedule=kfp_server_api.models.V1PeriodicSchedule(\n start_time=start_time,\n end_time=end_time,\n interval_second=interval_second))\n if cron_expression is not None:\n trigger = kfp_server_api.models.V1Trigger(\n cron_schedule=kfp_server_api.models.V1CronSchedule(\n start_time=start_time,\n end_time=end_time,\n cron=cron_expression))\n\n job_body = kfp_server_api.models.V1Job(\n enabled=enabled,\n pipeline_spec=job_config.spec,\n resource_references=job_config.resource_references,\n name=job_name,\n description=description,\n no_catchup=no_catchup,\n trigger=trigger,\n max_concurrency=max_concurrency,\n service_account=service_account)\n return self._job_api.create_job(body=job_body)",
"def create_definition_from_data(self, course_key, new_def_data, category, user_id):\n new_def_data = self._serialize_fields(category, new_def_data)\n new_id = ObjectId()\n document = {\n '_id': new_id,\n \"block_type\": category,\n \"fields\": new_def_data,\n \"edit_info\": {\n \"edited_by\": user_id,\n \"edited_on\": datetime.datetime.now(UTC),\n \"previous_version\": None,\n \"original_version\": new_id,\n },\n 'schema_version': self.SCHEMA_VERSION,\n }\n self.update_definition(course_key, document)\n definition_locator = DefinitionLocator(category, new_id)\n return definition_locator",
"def create_definition_from_data(self, new_def_data, category, user_id):\r\n new_def_data = self._serialize_fields(category, new_def_data)\r\n new_id = ObjectId()\r\n document = {\r\n '_id': new_id,\r\n \"category\" : category,\r\n \"fields\": new_def_data,\r\n \"edit_info\": {\r\n \"edited_by\": user_id,\r\n \"edited_on\": datetime.datetime.now(UTC),\r\n \"previous_version\": None,\r\n \"original_version\": new_id,\r\n },\r\n 'schema_version': self.SCHEMA_VERSION,\r\n }\r\n self.db_connection.insert_definition(document)\r\n definition_locator = DefinitionLocator(category, new_id)\r\n return definition_locator",
"def create_job_object(job_type: int = 0,\n team_id: int = 0,\n destination_name: str = None,\n destination_lat: float = 0,\n destination_lng: float = 0,\n destination_text: str = None,\n destination_url: str = None,\n text_dispatcher: str = None,\n text_receiver: str = None,\n contact_name: str = None,\n contact_phone: str = None,\n contact_email: str = None,\n day: int = None,\n priority: int = None,\n number: int = None,\n on_site_seconds: int = None,\n window_start: int = None,\n window_end: int = None,\n order_id: int = None,\n dispatcher_uid: str = None,\n place_uid: str = None,\n worker: str = None,\n items_to_dropoff: int = None,\n items_to_pickup: int = None,\n custom_attributes: dict = None) -> dict:\n\n job = {\n \"type\": job_type,\n \"teamId\": team_id,\n \"destinationName\": destination_name,\n \"destinationLat\": destination_lat,\n \"destinationLng\": destination_lng,\n \"destinationText\": destination_text,\n \"destinationUrl\": destination_url,\n \"textDispatcher\": text_dispatcher,\n \"textReceiver\": text_receiver,\n \"contactName\": contact_name,\n \"contactPhone\": contact_phone,\n \"contactEmail\": contact_email,\n \"day\": day,\n \"priority\": priority,\n \"number\": number,\n \"onSiteSeconds\": on_site_seconds,\n \"windowStart\": window_start,\n \"windowEnd\": window_end,\n \"orderId\": order_id,\n \"dispatcherUid\": dispatcher_uid,\n \"placeUid\": place_uid,\n \"worker\": worker,\n \"itemsToDropoff\": items_to_dropoff,\n \"itemsToPickup\": items_to_pickup\n }\n job_without_none = {k: v for k, v in job.items() if v is not None}\n job.clear()\n job.update(job_without_none)\n\n if custom_attributes:\n job.update({f\"custom_{k}\": v for k, v in custom_attributes.items() if k})\n\n return job",
"def build(self, consumer, definition):\n\n try:\n definition = definition.build()\n except exceptions.InvalidRequestDefinition as error:\n # TODO: Find a Python 2.7 compatible way to reraise\n raise exceptions.UplinkBuilderError(\n consumer.__class__, definition.__name__, error)\n\n return CallFactory(\n consumer,\n RequestPreparer(self, definition),\n definition\n )",
"def create_job_object(message, environment_image):\n\n PYTHONUNBUFFERED_ENV = client.V1EnvVar(name=\"PYTHONUNBUFFERED\", value=\"1\")\n AUTH_TOKEN_ENV = client.V1EnvVar(name=\"AUTH_TOKEN\", value=AUTH_TOKEN)\n EVALAI_API_SERVER_ENV = client.V1EnvVar(\n name=\"EVALAI_API_SERVER\", value=EVALAI_API_SERVER\n )\n MESSAGE_BODY_ENV = client.V1EnvVar(name=\"BODY\", value=json.dumps(message))\n submission_pk = message[\"submission_pk\"]\n image = message[\"submitted_image_uri\"]\n # Configureate Pod agent container\n agent_container = client.V1Container(\n name=\"agent\", image=image, env=[PYTHONUNBUFFERED_ENV]\n )\n # Configureate Pod environment container\n environment_container = client.V1Container(\n name=\"environment\",\n image=environment_image,\n env=[\n PYTHONUNBUFFERED_ENV,\n AUTH_TOKEN_ENV,\n EVALAI_API_SERVER_ENV,\n MESSAGE_BODY_ENV,\n ],\n resources=client.V1ResourceRequirements(\n limits={\"nvidia.com/gpu\": \"1\"}\n ),\n )\n # Create and configurate a spec section\n template = client.V1PodTemplateSpec(\n metadata=client.V1ObjectMeta(labels={\"app\": \"evaluation\"}),\n spec=client.V1PodSpec(\n containers=[environment_container, agent_container],\n restart_policy=\"Never\",\n ),\n )\n # Create the specification of deployment\n spec = client.V1JobSpec(backoff_limit=1, template=template)\n # Instantiate the job object\n job = client.V1Job(\n api_version=\"batch/v1\",\n kind=\"Job\",\n metadata=client.V1ObjectMeta(\n name=\"submission-{0}\".format(submission_pk)\n ),\n spec=spec,\n )\n return job",
"def setup_and_get_job_details_for_sf(self):\n\n self.create_compute_environment()\n jq_response = self.create_job_queue()\n jd_response = self.register_job_definition()\n return dict(jobDefinition=jd_response[\"jobDefinitionName\"], jobQueue=jq_response)",
"def create(self, cr, uid, vals, context=None):\n vals.update({'ref': self.pool.get('ir.sequence').get(\n cr, uid, 'maintenance.job')})\n return super(maintenance_job, self).create(cr, uid, vals, context=context)",
"def create(\n cls,\n func: FunctionReferenceType,\n args: Union[List[Any], Optional[Tuple]] = None,\n kwargs: Optional[Dict[str, Any]] = None,\n connection: Optional['Redis'] = None,\n result_ttl: Optional[int] = None,\n ttl: Optional[int] = None,\n status: Optional[JobStatus] = None,\n description: Optional[str] = None,\n depends_on: Optional[JobDependencyType] = None,\n timeout: Optional[int] = None,\n id: Optional[str] = None,\n origin: str = '',\n meta: Optional[Dict[str, Any]] = None,\n failure_ttl: Optional[int] = None,\n serializer=None,\n *,\n on_success: Optional[Union['Callback', Callable[..., Any]]] = None, # Callable is deprecated\n on_failure: Optional[Union['Callback', Callable[..., Any]]] = None, # Callable is deprecated\n on_stopped: Optional[Union['Callback', Callable[..., Any]]] = None, # Callable is deprecated\n ) -> 'Job':\n if args is None:\n args = ()\n if kwargs is None:\n kwargs = {}\n\n if not isinstance(args, (tuple, list)):\n raise TypeError('{0!r} is not a valid args list'.format(args))\n if not isinstance(kwargs, dict):\n raise TypeError('{0!r} is not a valid kwargs dict'.format(kwargs))\n\n job = cls(connection=connection, serializer=serializer)\n if id is not None:\n job.set_id(id)\n\n if origin:\n job.origin = origin\n\n # Set the core job tuple properties\n job._instance = None\n if inspect.ismethod(func):\n job._instance = func.__self__\n job._func_name = func.__name__\n elif inspect.isfunction(func) or inspect.isbuiltin(func):\n job._func_name = '{0}.{1}'.format(func.__module__, func.__qualname__)\n elif isinstance(func, str):\n job._func_name = as_text(func)\n elif not inspect.isclass(func) and hasattr(func, '__call__'): # a callable class instance\n job._instance = func\n job._func_name = '__call__'\n else:\n raise TypeError('Expected a callable or a string, but got: {0}'.format(func))\n job._args = args\n job._kwargs = kwargs\n\n if on_success:\n if not isinstance(on_success, Callback):\n warnings.warn(\n 'Passing a string or function for `on_success` is deprecated, pass `Callback` instead',\n DeprecationWarning,\n )\n on_success = Callback(on_success) # backward compatibility\n job._success_callback_name = on_success.name\n job._success_callback_timeout = on_success.timeout\n\n if on_failure:\n if not isinstance(on_failure, Callback):\n warnings.warn(\n 'Passing a string or function for `on_failure` is deprecated, pass `Callback` instead',\n DeprecationWarning,\n )\n on_failure = Callback(on_failure) # backward compatibility\n job._failure_callback_name = on_failure.name\n job._failure_callback_timeout = on_failure.timeout\n\n if on_stopped:\n if not isinstance(on_stopped, Callback):\n warnings.warn(\n 'Passing a string or function for `on_stopped` is deprecated, pass `Callback` instead',\n DeprecationWarning,\n )\n on_stopped = Callback(on_stopped) # backward compatibility\n job._stopped_callback_name = on_stopped.name\n job._stopped_callback_timeout = on_stopped.timeout\n\n # Extra meta data\n job.description = description or job.get_call_string()\n job.result_ttl = parse_timeout(result_ttl)\n job.failure_ttl = parse_timeout(failure_ttl)\n job.ttl = parse_timeout(ttl)\n job.timeout = parse_timeout(timeout)\n job._status = status\n job.meta = meta or {}\n\n # dependency could be job instance or id, or iterable thereof\n if depends_on is not None:\n depends_on = ensure_list(depends_on)\n depends_on_list = []\n for depends_on_item in depends_on:\n if isinstance(depends_on_item, Dependency):\n # If a Dependency has enqueue_at_front or allow_failure set to True, these behaviors are used for\n # all dependencies.\n job.enqueue_at_front = job.enqueue_at_front or depends_on_item.enqueue_at_front\n job.allow_dependency_failures = job.allow_dependency_failures or depends_on_item.allow_failure\n depends_on_list.extend(depends_on_item.dependencies)\n else:\n depends_on_list.extend(ensure_list(depends_on_item))\n job._dependency_ids = [dep.id if isinstance(dep, Job) else dep for dep in depends_on_list]\n\n return job",
"def create_job_detail(company_name, job_title, application_deadline, job_listing_url, state, city, application_listed, salary):\n\n job_detail = JobDetail(company_name = company_name, job_title = job_title, application_deadline = application_deadline, job_listing_url = job_listing_url, state = state , city = city, application_listed = application_listed, salary = salary)\n db.session.add(job_detail)\n db.session.commit()\n\n return job_detail",
"def create_namespaced_build_request_instantiate(self, body, namespace, name, **kwargs):\n\n all_params = ['body', 'namespace', 'name', 'pretty']\n all_params.append('callback')\n\n params = locals()\n for key, val in iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method create_namespaced_build_request_instantiate\" % key\n )\n params[key] = val\n del params['kwargs']\n\n # verify the required parameter 'body' is set\n if ('body' not in params) or (params['body'] is None):\n raise ValueError(\"Missing the required parameter `body` when calling `create_namespaced_build_request_instantiate`\")\n # verify the required parameter 'namespace' is set\n if ('namespace' not in params) or (params['namespace'] is None):\n raise ValueError(\"Missing the required parameter `namespace` when calling `create_namespaced_build_request_instantiate`\")\n # verify the required parameter 'name' is set\n if ('name' not in params) or (params['name'] is None):\n raise ValueError(\"Missing the required parameter `name` when calling `create_namespaced_build_request_instantiate`\")\n\n resource_path = '/oapi/v1/namespaces/{namespace}/buildconfigs/{name}/instantiate'.replace('{format}', 'json')\n path_params = {}\n if 'namespace' in params:\n path_params['namespace'] = params['namespace']\n if 'name' in params:\n path_params['name'] = params['name']\n\n query_params = {}\n if 'pretty' in params:\n query_params['pretty'] = params['pretty']\n\n header_params = {}\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'body' in params:\n body_params = params['body']\n\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.\\\n select_header_accept(['application/json', 'application/yaml'])\n if not header_params['Accept']:\n del header_params['Accept']\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.\\\n select_header_content_type(['*/*'])\n\n # Authentication setting\n auth_settings = []\n\n response = self.api_client.call_api(resource_path, 'POST',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='V1BuildRequest',\n auth_settings=auth_settings,\n callback=params.get('callback'))\n return response",
"def override_definition(base_definition_name: str, image: str) -> str:\n # XXX TODO: We only create derived job definitions from an existing base\n # definition, which is minimally modified. This is a conservative choice\n # that avoids hardcoding a default definition. In the future, we might\n # consider relaxing this to auto-create a default base definition. The\n # advantage there is one less piece of initial AWS setup. The challenge is\n # choosing defaults that work for everyone's taste for resources/spending,\n # as well as using the right job roles and other details.\n # -trs, 22 May 2020\n batch = aws.client_with_default_region(\"batch\")\n\n base_definition = lookup_definition(base_definition_name)\n\n if not base_definition:\n raise UserError(\"AWS Batch job definition «%s» does not exist\" % base_definition_name)\n\n # The base definition might already use this image, in which case we avoid\n # creating anything. This lets admins not grant job definition creation to\n # users if they want; users will instead have to specify matching\n # --aws-batch-job and --image values.\n #\n # Split the image name in order to normalize the implicit :latest tag.\n base_image = base_definition[\"containerProperties\"][\"image\"]\n\n if split_image_name(base_image) == split_image_name(image):\n return base_definition_name\n\n # The revision of the base definition is included in the derived image name\n # so that changes to the base definition cause derived definitions to be\n # re-created. Unfortunately, we can't explicitly set the revision of new\n # definitions.\n derived_definition_name = sanitize_name(\n \"_\".join((\n base_definition_name,\n str(base_definition[\"revision\"]),\n *split_image_name(image))))\n\n derived_definition = lookup_definition(derived_definition_name)\n\n if not derived_definition:\n derived_definition = deepcopy(base_definition)\n derived_definition[\"jobDefinitionName\"] = derived_definition_name\n derived_definition[\"containerProperties\"][\"image\"] = image\n\n # Remove AWS-assigned keys returned by describe_job_definitions() which\n # aren't supported as keyword arguments by register_job_definition().\n register_inputs = batch.meta.service_model.operation_model(\"RegisterJobDefinition\").input_shape.members\n\n for key in set(derived_definition) - set(register_inputs):\n del derived_definition[key]\n\n batch.register_job_definition(**derived_definition)\n else:\n derived_image = derived_definition[\"containerProperties\"][\"image\"]\n\n assert split_image_name(derived_image) == split_image_name(image), (\n \"Expected job definition «%s», derived from «%s», to use image «%s», \"\n \"but it uses «%s» instead\"\n % (derived_definition_name, base_definition_name, image, derived_image))\n\n return derived_definition_name",
"def _GetMigrationJob(\n self,\n source_ref,\n destination_ref,\n conversion_workspace_ref,\n cmek_key_ref,\n args,\n ):\n migration_job_type = self.messages.MigrationJob\n labels = labels_util.ParseCreateArgs(\n args, self.messages.MigrationJob.LabelsValue\n )\n type_value = self._GetType(migration_job_type, args.type)\n source = source_ref.RelativeName()\n destination = destination_ref.RelativeName()\n params = {}\n if args.IsSpecified('peer_vpc'):\n params['vpcPeeringConnectivity'] = self._GetVpcPeeringConnectivity(args)\n elif args.IsSpecified('vm_ip'):\n params['reverseSshConnectivity'] = self._GetReverseSshConnectivity(args)\n elif args.IsSpecified('static_ip'):\n params['staticIpConnectivity'] = self._GetStaticIpConnectivity()\n\n migration_job_obj = migration_job_type(\n labels=labels,\n displayName=args.display_name,\n state=migration_job_type.StateValueValuesEnum.CREATING,\n type=type_value,\n dumpPath=args.dump_path,\n source=source,\n destination=destination,\n **params)\n if conversion_workspace_ref is not None:\n migration_job_obj.conversionWorkspace = self._GetConversionWorkspaceInfo(\n conversion_workspace_ref, args\n )\n if cmek_key_ref is not None:\n migration_job_obj.cmekKeyName = cmek_key_ref.RelativeName()\n\n if args.IsKnownAndSpecified('filter'):\n args.filter, server_filter = filter_rewrite.Rewriter().Rewrite(\n args.filter\n )\n migration_job_obj.filter = server_filter\n\n if args.IsKnownAndSpecified('dump_parallel_level'):\n migration_job_obj.performanceConfig = self._GetPerformanceConfig(args)\n\n return migration_job_obj",
"def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None,\n copy: Optional[pulumi.Input[pulumi.InputType['JobCopyArgs']]] = None,\n extract: Optional[pulumi.Input[pulumi.InputType['JobExtractArgs']]] = None,\n job_id: Optional[pulumi.Input[str]] = None,\n job_timeout_ms: Optional[pulumi.Input[str]] = None,\n job_type: Optional[pulumi.Input[str]] = None,\n labels: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,\n load: Optional[pulumi.Input[pulumi.InputType['JobLoadArgs']]] = None,\n location: Optional[pulumi.Input[str]] = None,\n project: Optional[pulumi.Input[str]] = None,\n query: Optional[pulumi.Input[pulumi.InputType['JobQueryArgs']]] = None,\n user_email: Optional[pulumi.Input[str]] = None) -> 'Job':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = dict()\n\n __props__[\"copy\"] = copy\n __props__[\"extract\"] = extract\n __props__[\"job_id\"] = job_id\n __props__[\"job_timeout_ms\"] = job_timeout_ms\n __props__[\"job_type\"] = job_type\n __props__[\"labels\"] = labels\n __props__[\"load\"] = load\n __props__[\"location\"] = location\n __props__[\"project\"] = project\n __props__[\"query\"] = query\n __props__[\"user_email\"] = user_email\n return Job(resource_name, opts=opts, __props__=__props__)"
] | [
"0.7011716",
"0.6262502",
"0.60106415",
"0.59811646",
"0.59107107",
"0.5779581",
"0.5768893",
"0.5693051",
"0.5675572",
"0.56623316",
"0.56285715",
"0.5569513",
"0.5486852",
"0.5481721",
"0.5459425",
"0.5407388",
"0.53674847",
"0.5330379",
"0.5303417",
"0.5297281",
"0.52739733",
"0.5267602",
"0.5253802",
"0.52483857",
"0.5232393",
"0.52295625",
"0.5188486",
"0.5175521",
"0.5171691",
"0.51694614"
] | 0.67803115 | 1 |
List all slot types for the vendor. | def list_interaction_model_slot_types_v1(self, vendor_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, ListSlotTypeResponse_b426c805, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "list_interaction_model_slot_types_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'vendor_id' is set
if ('vendor_id' not in params) or (params['vendor_id'] is None):
raise ValueError(
"Missing the required parameter `vendor_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
if 'vendor_id' in params:
query_params.append(('vendorId', params['vendor_id']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'sort_direction' in params:
query_params.append(('sortDirection', params['sort_direction']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.model_type.list_slot_type_response.ListSlotTypeResponse", status_code=200, message="Returns list of slot types for the vendor."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.model_type.list_slot_type_response.ListSlotTypeResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_potential_classes_for_slot(slot_number):\n return [\"econ\", \"biz\", \"wtf\"]",
"def GetAllSlots(cls):\n slots = []\n for parent in cls.__mro__:\n slots.extend(getattr(parent, \"__slots__\", []))\n return slots",
"def getTypesList():\n return Gw2Spidy._request('types')['results']",
"def get_volume_types(self):\n res = self.get('%s/types' % self.catalog['volume'])\n if res['status'] == 200:\n return json.loads(res['body'])['volume_types']\n else:\n LOG.error('Get volume types failed: %s %s %s' %\n (res['status'], res['reason'], res['body']))\n raise InvalidResponse(res)",
"def list(self, request):\n product_types = ProductType.objects.all()\n serializer = ProductTypeSerializer(product_types, many=True)\n\n return Response(serializer.data, status=status.HTTP_200_OK)",
"def required_slots(tracker: Tracker) -> List[Text]:\n print(\"required_slots(tracker: Tracker)\")\n return [\"name\",\"roomcount\",\"roomtype\"]",
"def list_lots(self):\n table = Table(\n 5,\n headers=['Short Name', 'Date', 'Cost', 'Gain', 'Gain%'],\n coltypes=['str', 'str', 'dollars', 'delta_dollars', 'percentage'])\n for account in self.accounts():\n for asset in account.assets():\n if hasattr(asset, 'list_lots'):\n lots = asset.list_lots()\n assert (\n lots.headers()\n == ['Date', 'Quantity', 'Cost', 'Gain', 'Gain%'])\n for lot in lots.list():\n table.add_row([asset.short_name()] + lot[:1] + lot[2:])\n return table",
"def listAssetTypes(self):\n return self.get_json('/assetType')",
"def vendor_list():\n return ['nxos', 'eos', 'cumulus']",
"def required_slots(tracker: Tracker) -> List[Text]:\n return [\n \"tipo_prenda\",\n \"tipo_compostura\"\n ]",
"def allItems(self):\n items = []\n for itemType in self.__inventory__:\n for item in self.__inventory__[itemType]:\n items.append(item)\n return items",
"def required_slots(tracker: Tracker) -> List[Text]:\n\n return [\"search_type\", \"time\"]",
"def get_all_typesystems(self):\n return list(self._type_systems.keys())",
"def list_bed_types():\n\n list = [\"ctrl\", \"cresis\", \"cresisp\", \"minus\", \"plus\", \"ba01_bed\", \"970mW_hs\", \"jak_1985\", \"no_bath\", \"wc\"]\n\n return list",
"def getStorageTypes(self, show_all=False):\n types = getStorageTypes()\n if not show_all:\n types = [x for x in types if x['interface'].providedBy(self)]\n return types",
"def list(self, request):\n gametypes = GameType.objects.all()\n\n # many=True kwarg is necessary if serializing a list of objects instead of single object\n serializer = GameTypeSerializer(gametypes, many=True, context={'request': request})\n return Response(serializer.data)",
"def required_slots(tracker: Tracker) -> List[Text]:\n\n return [\"product\", \"applicant_name\", \"applicant_dob\", \"applicant_phoneno\", \"applicant_address\"]",
"def _volume_types(cls):\n try:\n return cls.volumes.behaviors.get_volume_types()\n except:\n raise DatasetGeneratorError(\n \"Unable to retrieve list of volume types during \"\n \"data-driven-test setup.\")",
"def get_fuel_types(session: Session) -> CursorResult:\n return session.query(FuelType).order_by(FuelType.abbrev)",
"def allItemsByType(self, itemType):\n if itemType.value not in self.__inventory__:\n return []\n return self.__inventory__[itemType.value]",
"def required_slots(tracker: Tracker) -> List[Text]:\n return [\n \"tipo_prenda\",\n \"numero_prendas\",\n \"tipo_lavado\"\n ]",
"def list(self, request):\n\n game_type_objects = GameType.objects.all()\n\n # Note additonal 'many=True'\n # It's for serializing a list of objects instead of one.\n serialized_game_types = GameTypeSerializer(\n game_type_objects,\n many=True,\n context={'request': request}\n )\n\n return Response(serialized_game_types.data)",
"def handle_list(self, detail, *args, **kwargs):\n for product_type in models.ProductType.objects.all():\n print(product_type.name)\n if detail:\n for coverage_type in product_type.allowed_coverage_types.all():\n print(\"\\t%s\" % coverage_type.name)",
"def etypes(self): # -> list[str]:\n ...",
"def slot_mappings(self):\n # type: () -> Dict[Text: Union[Dict, List[Dict]]]\n\n return {\"name\": [self.from_entity(entity=\"name\"),\n self.from_text()],\n \"roomcount\": [self.from_entity(entity=\"roomcount\"),\n self.from_text()],\n \"roomtype\": [self.from_entity(entity=\"roomtype\"),\n self.from_text()]}",
"def product_types(self):\n return list(self._product_type_plugins.keys())",
"def slot_mappings(self) -> Dict[Text, Union[Dict, List[Dict]]]:\n\n return {\n \"search_type\": [\n self.from_trigger_intent(\n intent=\"search_transactions\", value=\"spend\"\n ),\n self.from_trigger_intent(\n intent=\"check_earnings\", value=\"deposit\"\n ),\n ],\n \"time\": [\n self.from_entity(entity=\"time\"),\n ]\n }",
"def slots(self):\n return self.__slots.values()",
"def list_inventory(self):\n\n print('Your inventory contains:')\n #i = 1\n #inv_dict = {}\n for item in self.bag_of_holding:\n if 'casted' not in item.name:\n try:\n print(item.name)\n except:\n pass\n\n #inv_dict[str(i)] = item\n #i += 1\n #return inv_dict",
"def get_slots(self, slot_names_filter=None):\n if slot_names_filter:\n # show only particular slots\n #TODO\n raise Exception(\"Not implemented!\")\n else:\n slot_names_filter = self.memory.keys()\n\n return self.memory"
] | [
"0.5957767",
"0.57510084",
"0.56942004",
"0.56164825",
"0.55939275",
"0.5561666",
"0.5548958",
"0.55201614",
"0.5444181",
"0.543892",
"0.5423173",
"0.54023176",
"0.5392513",
"0.5391163",
"0.5385374",
"0.53549826",
"0.53284764",
"0.53130853",
"0.52963626",
"0.5290598",
"0.5286499",
"0.52705383",
"0.5256339",
"0.5220683",
"0.51620406",
"0.51611596",
"0.5153498",
"0.5109461",
"0.5095078",
"0.50942814"
] | 0.65238047 | 0 |
Create a new version of slot type within the given slotTypeId. | def create_interaction_model_slot_type_v1(self, slot_type, **kwargs):
# type: (DefinitionData_dad4effb, **Any) -> Union[ApiResponse, object, SlotTypeResponse_1ca513dc, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "create_interaction_model_slot_type_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type' is set
if ('slot_type' not in params) or (params['slot_type'] is None):
raise ValueError(
"Missing the required parameter `slot_type` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'slot_type' in params:
body_params = params['slot_type']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_response.SlotTypeResponse", status_code=200, message="Returns the generated slotTypeId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error e.g. the slot type definition is invalid."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_response.SlotTypeResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_interaction_model_slot_type_version_v1(self, slot_type_id, slot_type, **kwargs):\n # type: (str, VersionData_faa770c8, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type' is set\n if ('slot_type' not in params) or (params['slot_type'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type' in params:\n body_params = params['slot_type']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Returns update status location link on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the slot type definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified slot type does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_interaction_model_slot_type_definition_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, SlotTypeDefinitionOutput_20e87f7, BadRequestError_f854b05]\n operation_name = \"get_interaction_model_slot_type_definition_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput\", status_code=200, message=\"The slot type definition.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"The slot type cannot be retrieved due to errors listed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput\")\n\n if full_response:\n return api_response\n return api_response.body",
"def update_interaction_model_slot_type_v1(self, slot_type_id, update_request, **kwargs):\n # type: (str, UpdateRequest_43de537, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_interaction_model_slot_type_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_request' is set\n if ('update_request' not in params) or (params['update_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/update'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'update_request' in params:\n body_params = params['update_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No content, indicates the fields were successfully updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def delete_interaction_model_slot_type_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No content; just confirm the slot type is deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"The slot type cannot be deleted from reasons due to in-use by other entities.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, SlotTypeVersionData_1f3ee474]\n operation_name = \"get_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\", status_code=200, message=\"Returns the slot type version metadata for the given slotTypeId and version.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_definition(self, block_type, slug=None):\n prefix = \"d\"\n if slug:\n prefix += \"_\" + slug\n def_id = self._next_id(prefix)\n self._definitions[def_id] = block_type\n return def_id",
"def setTypeId(self, x, y, z, type_):\n state = self.world.getBlockAt(x, y, z).getState()\n state.setTypeId(type_)\n self.list_.add(state)",
"def create_definition(self, block_type, slug=None):\n raise NotImplementedError()",
"def create_object_type(self, object_type=None):\n # Return Value\n # ------------\n # {object_type_id: ''}\n #\n if not is_basic_identifier(object_type.name):\n raise BadRequest(\"Invalid object_type name: %s\" % object_type.name)\n if not is_yaml_string_valid(object_type.definition):\n raise BadRequest(\"Invalid YAML definition\")\n object_type_id, version = self.clients.resource_registry.create(object_type)\n return object_type_id",
"def delete_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type version for this slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def create_parking_lot(self, allow_slots):\n allow_slots = int(allow_slots)\n\n if len(self.slots) > 0:\n print(\"Parking Lot is already created\")\n return\n\n if allow_slots < 1:\n print(\"Number of slot: %s provided is incorrect.\" % allow_slots)\n return\n\n for i in range(1, allow_slots + 1):\n self.slots[i] = Slot(slot_no=i, available=True)\n print(\"Created a parking lot with %s slots\" % allow_slots)",
"def add_slot(self, slot):\n slot.set_location(len(self.slots)+1)\n self.slots.append(slot)",
"def list_interaction_model_slot_type_versions_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, ListSlotTypeVersionResponse_7d552abf, BadRequestError_f854b05]\n operation_name = \"list_interaction_model_slot_type_versions_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\", status_code=200, message=\"Returns list of slot type version for the slot type id.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def new_parametertype(request, recipe, **_kwargs):\n return create_view(\n request,\n _(\"Parameter type for recipe %s\") % recipe.name,\n ParameterTypeForm,\n recipe=recipe,\n )",
"def create(self, item_type, uuid):\n return self.write.create(item_type, uuid)",
"def _insertNew(self, position):\n assert position >= 0 and position <= len(self._subSlots)\n slot = self._getInstance(self, level=self.level - 1)\n self._subSlots.insert(position, slot)\n slot.name = self.name\n if self._value is not None:\n slot.setValue(self._value)\n return slot",
"async def create_block_type(self, block_type: BlockTypeCreate) -> BlockType:\n try:\n response = await self._client.post(\n \"/block_types/\",\n json=block_type.dict(\n json_compatible=True, exclude_unset=True, exclude={\"id\"}\n ),\n )\n except httpx.HTTPStatusError as e:\n if e.response.status_code == status.HTTP_409_CONFLICT:\n raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e\n else:\n raise\n return BlockType.parse_obj(response.json())",
"def get_interaction_model_slot_type_build_status_v1(self, slot_type_id, update_request_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, SlotTypeStatus_a293ebfc, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_interaction_model_slot_type_build_status_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_request_id' is set\n if ('update_request_id' not in params) or (params['update_request_id'] is None):\n raise ValueError(\n \"Missing the required parameter `update_request_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/updateRequest/{updateRequestId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'update_request_id' in params:\n path_params['updateRequestId'] = params['update_request_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_status.SlotTypeStatus\", status_code=200, message=\"Returns the build status and error codes for the given slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_status.SlotTypeStatus\")\n\n if full_response:\n return api_response\n return api_response.body",
"def sNew(sdTypeStructId):\n outSDTypeStruct = ctypes.c_void_p()\n _res = sd.getContext().SDTypeStruct_sNew(ctypes.create_string_buffer(sdTypeStructId.encode('utf-8')), ctypes.byref(outSDTypeStruct))\n if _res != SDApiError.NoError.value:\n if _res == SDApiError.NoErrorOutputParamNotSet.value:\n return None\n raise APIException(SDApiError(_res))\n constructor = sd.getContext().mTypeMap[SDAPIObject(sd.getContext(), outSDTypeStruct, ownHandle=False).getClassName()]\n return constructor(sd.getContext(), outSDTypeStruct.value, ownHandle=True)",
"def create_parking_slots(number_of_slots):\n if (number_of_slots is None or number_of_slots == 0):\n print(f\"Cannot create parking slots. Please try again.\")\n return False\n number_of_slots = int(number_of_slots)\n if (isinstance(number_of_slots, int) and number_of_slots > 0):\n for i in range(number_of_slots):\n parking_slots[i + 1] = None\n print(f\"Created Parking of {number_of_slots} slots.\")\n return True\n else:\n print(\n f\"Cannot create slots with {number_of_slots} as input. Please try again. Maybe with a valid number?\"\n )\n return False",
"def generate_slot(slot_name, slot_description, slot_raw_filename):\n slot = {\n 'enumerationValues': [],\n \"name\": slot_name,\n \"description\": slot_description\n }\n slot_raw_vals = read_raw_vals(slot_raw_filename)\n for slot_val in slot_raw_vals:\n slot['enumerationValues'].append({'value': slot_val})\n\n return slot",
"def var(self, _type):\n return Slot()",
"def update_interaction_model_slot_type_version_v1(self, slot_type_id, version, slot_type_update, **kwargs):\n # type: (str, str, SlotTypeUpdate_ae01835f, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type_update' is set\n if ('slot_type_update' not in params) or (params['slot_type_update'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_update` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}/update'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type_update' in params:\n body_params = params['slot_type_update']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def place(slot_name, dttime):\n\tdttime = datetime.strptime(dttime, '%Y-%m-%d %H:%M:%S')\n\tdttime = dttime.replace(second=0, microsecond=0)\n\ttry:\n\t\tarea.context['timers'][dttime].add(slot_name)\n\texcept KeyError:\n\t\tarea.context['timers'][dttime] = {slot_name}\n\tarea.publish({'status': 'placed'}, slot=slot_name)",
"def create_for_object(self, parent_object, slot, role=\"m\", title=None):\n from .db import Placeholder\n\n parent_attrs = get_parent_lookup_kwargs(parent_object)\n obj = self.create(\n slot=slot,\n role=role or Placeholder.MAIN,\n title=title or slot.title().replace(\"_\", \" \"),\n **parent_attrs\n )\n obj.parent = parent_object # fill the reverse cache\n return obj",
"def create_wsdl_object_of_type(self, type_name):\r\n return self.client.factory.create(type_name)",
"def create_type(name):\n\n new_type = Type(name=name)\n db.session.add(new_type)\n db.session.commit()\n return new_type",
"def nfvi_create_instance_type(instance_type_uuid, instance_type_name,\n instance_type_attributes, callback):\n cmd_id = _compute_plugin.invoke_plugin('create_instance_type',\n instance_type_uuid,\n instance_type_name,\n instance_type_attributes,\n callback=callback)\n return cmd_id",
"def make_mutable_type(type_):\n _mutable_types.append(type_)",
"def __init__(__self__, *,\n type_name: Optional[pulumi.Input[str]] = None,\n type_version_arn: Optional[pulumi.Input[str]] = None,\n version_id: Optional[pulumi.Input[str]] = None):\n if type_name is not None:\n pulumi.set(__self__, \"type_name\", type_name)\n if type_version_arn is not None:\n pulumi.set(__self__, \"type_version_arn\", type_version_arn)\n if version_id is not None:\n pulumi.set(__self__, \"version_id\", version_id)"
] | [
"0.6634029",
"0.5734478",
"0.55027074",
"0.54875815",
"0.5442675",
"0.53843546",
"0.5305201",
"0.52553576",
"0.5187946",
"0.5171874",
"0.51383734",
"0.51134545",
"0.5109183",
"0.5080171",
"0.5068835",
"0.5044356",
"0.5031533",
"0.49719235",
"0.495085",
"0.49283054",
"0.49260128",
"0.4915639",
"0.4905667",
"0.4803809",
"0.47673833",
"0.475035",
"0.47492474",
"0.47216296",
"0.47029486",
"0.47027895"
] | 0.6622921 | 1 |
Delete the slot type. | def delete_interaction_model_slot_type_v1(self, slot_type_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "delete_interaction_model_slot_type_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type_id' is set
if ('slot_type_id' not in params) or (params['slot_type_id'] is None):
raise ValueError(
"Missing the required parameter `slot_type_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'slot_type_id' in params:
path_params['slotTypeId'] = params['slot_type_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="No content; just confirm the slot type is deleted."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="The slot type cannot be deleted from reasons due to in-use by other entities."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="There is no slot type defined for the slotTypeId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="DELETE",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def remove_type(self, name):\n del self.types[name]",
"def type(self):\n ida_bytes.del_items(self.ea)",
"def removeType(self, name):\n delattr(self, name)\n try:\n del self._type_names[name]\n except ValueError:\n pass",
"def delete(cls, type_obj):\n DB.session.delete(type_obj)\n DB.session.commit()",
"def delete(self, unit_type, unit_name, variation_name=None):\n if unit_type == pu.UnitType.alias:\n relevant_dict = self.alias_definitions\n stat_key = \"#aliases\"\n elif unit_type == pu.UnitType.slot:\n relevant_dict = self.slot_definitions\n stat_key = \"#slots\"\n elif unit_type == pu.UnitType.intent:\n relevant_dict = self.intent_definitions\n stat_key = \"#intents\"\n else:\n raise ValueError(\"Tried to delete a definition with wrong type \"+\n \"(expected alias, slot or intent)\")\n\n if unit_name not in relevant_dict:\n raise KeyError(\"Couldn't find a definition for \" + unit_type.name +\n \" '\" + unit_name + \"'.\")\n\n nb_rules = relevant_dict[unit_name].get_nb_rules(variation_name)\n if variation_name is None:\n del relevant_dict[unit_name]\n self.stats[stat_key] -= 1\n self.stats[\"#declarations\"] -= 1\n self.stats[\"#rules\"] -= nb_rules\n else:\n relevant_dict[unit_name].delete_variation(variation_name)\n self.stats[\"#rules\"] -= nb_rules",
"def slotDelete(self):\n item = self.groupListBox.item((self.groupListBox.currentItem()))\n group = item.text().ascii()\n Group.Sequencer().slotRemoveGlobalGroup(group)",
"def remove_card(self, slot):\n del self._starting_card[slot]",
"def delete_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type version for this slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def remove_type(self, qid, type, type_system):\n if type_system not in self._type_systems:\n raise ValueError(\n f\"The type system {type_system} is not one of {self._type_systems.keys()}\"\n )\n self._type_systems[type_system].remove_type(qid, type)",
"def delete(self, type, id):\n path = self._get_path('delete').format(itemType=type, itemId=id)\n \n return self._DELETE(path)",
"def delete(self):\n del self.shx.atoms[self.index]",
"def delete(self, accounttype):\n accounttype = Accounttype.query\\\n .filter(Accounttype.name == accounttype).one()\n db.session.delete(accounttype)\n db.session.commit()\n return jsonify(accounttype)",
"def delete_resourcetype(self, realm=None, uuid=None):\n if not uuid:\n raise ValueError(\"Please provide a uuid for a resourcetype.\")\n\n uri = self._uri_realm_creator(realm=realm, uri='resourcetypes/' + uuid)\n data = self._delete(uri=uri, headers=self.headers)\n return data.json()",
"def del_typecheck(self, name: str):\n try:\n del self.__custom_types[name]\n except KeyError:\n pass",
"def remove_slot(self, slot):\n if slot in self.slots:\n idx = self.slots.index(slot)\n # update location of rest slot\n for s in self.slots[idx:]:\n s.set_location(s.get_location()-1)\n self.slots.remove(slot)",
"def delete(self):\n type_model = request.json\n\n type_model = namedtuple(\"Type\", type_model.keys())(*type_model.values())\n repository = TypeRepository(\n FLASK_APP.config[\"DBUSER\"],\n FLASK_APP.config[\"DBPASS\"],\n FLASK_APP.config[\"DBHOST\"],\n FLASK_APP.config[\"DBPORT\"],\n FLASK_APP.config[\"DBNAME\"])\n\n try:\n status = repository.delete(type_model)\n if status:\n Logger.Logger.create(FLASK_APP.config[\"ELASTICURL\"],\n 'Informative',\n 'Type deleted sucessfuly',\n 'delete()',\n str(status),\n FLASK_APP.config[\"TYPE\"])\n return self.okResponse(\n response=models.Type.Type(),\n message=\"Type deleted sucessfuly.\",\n status=204), 200\n except Exception as err:\n Logger.Logger.create(FLASK_APP.config[\"ELASTICURL\"],\n 'Error',\n 'Internal server error',\n 'delete()',\n str(err),\n FLASK_APP.config[\"TYPE\"])\n return self.okResponse(\n response=err,\n message=\"Internal server error: \"+str(err),\n status=500)",
"def delete_parametertype(request, parametertype, **_kwargs):\n pass",
"def delete_UI_transaction_type(account):\n\t_type = read_type()\n\tdeleted = delete_transaction_type(account, _type)\n\tif (not deleted):\n\t\tprint('Nu s-a efectuat nici o stergere.')\n\telse:\n\t\tprint('Stergere finalizata.')",
"def delete_item(self, key):\n deleted_slot = self.count_hash(key, len(self.slots))\n\n if self.slots[deleted_slot] == key:\n self.slots[deleted_slot] = None\n self.data[deleted_slot] = None\n elif isinstance(self.slots[deleted_slot], tuple):\n index_tuple = (self.slots[deleted_slot].index(key))\n list_slot = list(self.slots[deleted_slot])\n list_data = list(self.data[deleted_slot])\n list_slot.pop(index_tuple)\n list_data.pop(index_tuple)\n self.slots[deleted_slot] = tuple(list_slot)\n self.data[deleted_slot] = tuple(list_data)",
"def delete(self, key, key_type=None):\n pass",
"def Delete(self):\n\t\treturn self._oleobj_.InvokeTypes(50371075, LCID, 1, (24, 0), (),)",
"def delete_type(self, name):\n results = None\n\n atlas_endpoint = self.endpoint_url + \\\n f\"/types/typedef/name/{name}\"\n deleteType = requests.delete(\n atlas_endpoint,\n headers=self.authentication.get_authentication_headers())\n\n try:\n deleteType.raise_for_status()\n except requests.RequestException:\n raise Exception(deleteType.text)\n \n results = {\"message\":f\"successfully delete {name}\"}\n return results",
"def reset_type(self, name):\r\n del self._retype_dictionary[name]",
"def delete(self):\n self._instance.delete()\n self._instance = None\n self._data_defs = []",
"def delete(context, namespace_name, resource_type_name, session):\n\n namespace = namespace_api.get(\n context, namespace_name, session)\n\n resource_type = resource_type_api.get(\n context, resource_type_name, session)\n\n deleted = _delete(context, namespace_name, resource_type_name,\n namespace['id'], resource_type['id'], session)\n\n return _to_model_dict(resource_type_name, deleted)",
"def remove_type(self, ):\n if self.AttributeNames.TYPE in self.attrs:\n del self.attrs[self.AttributeNames.TYPE]\n return self",
"async def delete_block_type(self, block_type_id: UUID):\n try:\n await self._client.delete(f\"/block_types/{block_type_id}\")\n except httpx.HTTPStatusError as e:\n if e.response.status_code == 404:\n raise prefect.exceptions.ObjectNotFound(http_exc=e) from e\n elif (\n e.response.status_code == status.HTTP_403_FORBIDDEN\n and e.response.json()[\"detail\"]\n == \"protected block types cannot be deleted.\"\n ):\n raise prefect.exceptions.ProtectedBlockError(\n \"Protected block types cannot be deleted.\"\n ) from e\n else:\n raise",
"def clear_entity_type_vocabulary(self, type_name):\n\n symtab = self._symtab[type_name]\n symtab.reset()",
"def delete_volume_type(self, volume_type):\n return self._impl.delete_volume_type(volume_type)",
"def destroy(self, request, pk=None):\n try:\n vehicletype = VehicleType.objects.get(pk=pk)\n vehicletype.delete()\n\n return Response({}, status=status.HTTP_204_NO_CONTENT)\n\n except vehicletype.DoesNotExist as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_404_NOT_FOUND)\n\n except Exception as ex:\n return Response({'message': ex.args[0]}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)"
] | [
"0.638149",
"0.6239823",
"0.6080558",
"0.6049676",
"0.60330087",
"0.6005915",
"0.5982221",
"0.59309065",
"0.59063286",
"0.5892682",
"0.5870901",
"0.58697253",
"0.5854464",
"0.58537173",
"0.585165",
"0.5848346",
"0.579543",
"0.5775421",
"0.5773731",
"0.5757727",
"0.57050896",
"0.5682423",
"0.56662667",
"0.56367815",
"0.56240463",
"0.5622639",
"0.562107",
"0.5612045",
"0.55816716",
"0.5565348"
] | 0.69324857 | 0 |
Get the slot type definition. | def get_interaction_model_slot_type_definition_v1(self, slot_type_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, SlotTypeDefinitionOutput_20e87f7, BadRequestError_f854b05]
operation_name = "get_interaction_model_slot_type_definition_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type_id' is set
if ('slot_type_id' not in params) or (params['slot_type_id'] is None):
raise ValueError(
"Missing the required parameter `slot_type_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'slot_type_id' in params:
path_params['slotTypeId'] = params['slot_type_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput", status_code=200, message="The slot type definition."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="The slot type cannot be retrieved due to errors listed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="There is no slot type defined for the slotTypeId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def getDefinition(self, type=None):\n\n if type is None:\n return self.definitions['None']\n try:\n return self.definitions[type]\n except KeyError:\n return self.definitions['None']",
"def get_slot_definition(self, slot: DeckSlotName) -> SlotDefV3:\n deck_def = self.get_deck_definition()\n\n for slot_def in deck_def[\"locations\"][\"orderedSlots\"]:\n if slot_def[\"id\"] == slot.id:\n return slot_def\n\n raise errors.SlotDoesNotExistError(\n f\"Slot ID {slot.id} does not exist in deck {deck_def['otId']}\"\n )",
"def getAliasType(self):\n if self.sym != None:\n return self.sym.getType()\n return self.define.getType()",
"def get_block_type(self, def_id):\n try:\n return self._definitions[def_id]\n except KeyError:\n try:\n return def_id.aside_type\n except AttributeError:\n raise NoSuchDefinition(repr(def_id)) # pylint: disable= raise-missing-from",
"def type(self):\n return self._getValue('type')",
"def get_type(self) -> str:\n # Note: this name conflicts with existing python builtins\n return self[\"Type\"]",
"def get_declaration(self):\r\n return conf.lib.clang_getTypeDeclaration(self)",
"def reg_def_type(self) -> str:\n return self._reg_def_type",
"def get_type(self):\n return self._sType",
"def get_type (self):\n return self._stype",
"def _type(self):\n return self._id[1]",
"def get_spec_type(self):\r\n return self._spec_type",
"def get_type_definition(self, type_definition):\n if isinstance(type_definition, types.Enum):\n return self.define_enum_field(type_definition)\n if isinstance(type_definition, types.NumberTypeMarker):\n return self.define_basic_field(type_definition)\n if isinstance(type_definition, types.StringTypeMarker):\n return self.define_basic_field(type_definition)\n if isinstance(type_definition, types.Bool):\n return self.define_basic_field(type_definition)\n if isinstance(type_definition, types.Struct):\n # Since all the structs were already collected, and are\n # defined in the definitions section, it's enough to refer\n # to the struct here.\n return self.reference_type(type_definition)\n if isinstance(type_definition, types.Map):\n return self.define_map_field(type_definition)\n if isinstance(type_definition, types.List):\n return self.define_array(type_definition)\n if isinstance(type_definition, types.JSONData):\n return copy.deepcopy(JSONDATA_TEMPLATE)\n if isinstance(type_definition, types.Tuple):\n return self.define_array(type_definition)\n raise Exception(\n \"Cannot create schema for type %s\" %\n str(type_definition))",
"def type(self) -> global___Type:",
"def var(self, _type):\n return Slot()",
"def type_name(self):\n return self.TYPE_NAMES[self.type]",
"def get_type(self):\n return self.type",
"def get_type(self):\n return self.type",
"def get_type(self):\n return self._TYPE",
"def get_type(self):\n return self._type_obj",
"def get_type(self) -> str:\n return Tables.ESL.name",
"def get_type(self) -> str:\n return self.type",
"def get_type(self) -> str:\n # Note: this name conflicts with existing python builtins\n return self[\"Sns\"][\"Type\"]",
"def getPrettyType(self):\n s = self.sym\n if self.sym == None:\n s = self.define\n return \"Typedef (alias type: %s)\" % s.getType()",
"def slot(self):\n if self.__slot in ApexAP1000.SLOTS:\n return self.__slot\n else:\n raise ValueError('Bad slot number !')",
"def getType(self):\n return self.type",
"def getType(self):\n return self._type",
"def get_type(self):\n return self._type",
"def get_type(self):\n return self._type",
"def type_name(self):\n return self._type_name"
] | [
"0.6754375",
"0.61281437",
"0.6105955",
"0.60216135",
"0.6002419",
"0.59822404",
"0.5979925",
"0.59779984",
"0.5976322",
"0.59741217",
"0.59307176",
"0.59267306",
"0.5876768",
"0.58651626",
"0.58583635",
"0.5856294",
"0.5843073",
"0.5843073",
"0.58384514",
"0.58371776",
"0.58360153",
"0.58313835",
"0.5822613",
"0.5814443",
"0.58082825",
"0.57950485",
"0.5788796",
"0.5782611",
"0.5782611",
"0.57816756"
] | 0.659528 | 1 |
Get the status of slot type resource and its subresources for a given slotTypeId. | def get_interaction_model_slot_type_build_status_v1(self, slot_type_id, update_request_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, SlotTypeStatus_a293ebfc, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "get_interaction_model_slot_type_build_status_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type_id' is set
if ('slot_type_id' not in params) or (params['slot_type_id'] is None):
raise ValueError(
"Missing the required parameter `slot_type_id` when calling `" + operation_name + "`")
# verify the required parameter 'update_request_id' is set
if ('update_request_id' not in params) or (params['update_request_id'] is None):
raise ValueError(
"Missing the required parameter `update_request_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/updateRequest/{updateRequestId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'slot_type_id' in params:
path_params['slotTypeId'] = params['slot_type_id']
if 'update_request_id' in params:
path_params['updateRequestId'] = params['update_request_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_status.SlotTypeStatus", status_code=200, message="Returns the build status and error codes for the given slotTypeId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="There is no slot type defined for the slotTypeId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_status.SlotTypeStatus")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def SlotStatus(rangeInfo):\n if rangeInfo >= 3 and rangeInfo <= 10:\n \"\"\" Full Slot \"\"\"\n status = 1\n return status\n else:\n \"\"\" Empty Slot \"\"\"\n status = 0\n return status",
"def list_interaction_model_slot_type_versions_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, ListSlotTypeVersionResponse_7d552abf, BadRequestError_f854b05]\n operation_name = \"list_interaction_model_slot_type_versions_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\", status_code=200, message=\"Returns list of slot type version for the slot type id.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_resource_status(type, full_name=\"\", label=\"\", must_exist=True):\n cmd = \"kubectl get {} --no-headers --all-namespaces \" \\\n \"-o wide --selector \\\"{}\\\" \" \\\n \"| grep \\\"{}\\\" | awk '{{print $1 \\\" \\\" $2}}'\"\n cmd = cmd.format(type, label, full_name)\n try:\n encoded_output = subprocess.check_output(\n cmd, shell=True, stderr=subprocess.STDOUT,\n )\n except subprocess.CalledProcessError as exc:\n log.warning(\"command to get status of {} has \"\n \"failed. error code: \"\n \"{} {}\".format(full_name,\n exc.returncode, exc.output))\n raise RuntimeError(\n \"command to get status of {} has \"\n \"failed. error code: \"\n \"{} {}\".format(full_name,\n exc.returncode, exc.output))\n output = encoded_output.decode()\n if output == \"\":\n if not must_exist:\n return None\n log.warning(\n \"{} \\\"{}\\\" with label \\\"{}\\\" can't be found in \"\n \"the cluster\".format(type, full_name, label))\n raise RuntimeError(\n \"{} {} with label {} can't be found in the cluster\".format(\n type, full_name, label))\n # Example line:\n # kube-system cilium\n split_line = output.split(' ')\n return ResourceStatus(namespace=split_line[0],\n name=split_line[1])",
"def resource_status(self) -> 'outputs.InstantSnapshotResourceStatusResponse':\n return pulumi.get(self, \"resource_status\")",
"def get_status(self):\n data = self.client._perform_json(\n \"GET\", \"/projects/%s/recipes/%s/status\" % (self.project_key, self.recipe_name))\n return DSSRecipeStatus(self.client, data)",
"def get_interaction_model_slot_type_definition_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, SlotTypeDefinitionOutput_20e87f7, BadRequestError_f854b05]\n operation_name = \"get_interaction_model_slot_type_definition_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput\", status_code=200, message=\"The slot type definition.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"The slot type cannot be retrieved due to errors listed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_resource_status(self, namespace: \"str\" = None):\n pass",
"def get_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, SlotTypeVersionData_1f3ee474]\n operation_name = \"get_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\", status_code=200, message=\"Returns the slot type version metadata for the given slotTypeId and version.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_available_polls(game_type_id):\n\n poll_response = requests.get(\n url=f'{settings.GAME_SETUP_URL}/all-polls/{game_type_id}/',\n timeout=5 # in sec\n )\n if poll_response.status_code == 200:\n return poll_response.json()\n return {}",
"def _get_status(self):\n status_results = self.db_handler.query_items({\n 'api_version': {\n 'condition': 'is_in',\n 'value': ['3', TsV2CatalogHandler.api_version]\n }\n })\n source_status = None\n status = None\n for s in status_results:\n if s['api_version'] == '3':\n source_status = s\n elif s['api_version'] == TsV2CatalogHandler.api_version:\n status = s\n if not source_status:\n self.logger.warning('Source catalog status not found')\n return False\n if source_status['state'] != 'complete':\n self.logger.debug('Source catalog is not ready for use')\n return False\n if not status or ((status['source_timestamp'] != source_status['timestamp']) and status['state'] != 'in-progress'):\n # begin or restart process.\n # If the catalog is already being generated it will be allowed to finish before re-starting.\n status = {\n 'api_version': TsV2CatalogHandler.api_version,\n 'catalog_url': '{}/ts/txt/2/catalog.json'.format(self.cdn_url),\n 'source_api': source_status['api_version'],\n 'source_timestamp': source_status['timestamp'],\n 'state': 'in-progress',\n 'processed': {}\n }\n\n return (status, source_status)",
"def get_status_by_id(cls, request, id):\n return request.dbsession.query(cls).get(id).status",
"def create_interaction_model_slot_type_version_v1(self, slot_type_id, slot_type, **kwargs):\n # type: (str, VersionData_faa770c8, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type' is set\n if ('slot_type' not in params) or (params['slot_type'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type' in params:\n body_params = params['slot_type']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Returns update status location link on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the slot type definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified slot type does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def available_statuses(self):\n return self.pipeline.get(self.status, ())",
"def available_statuses(self):\n return self.pipeline.get(self.status, ())",
"def _getCurrentComponentStatus(self):\n resOverall = self.sysAdminClient.getOverallStatus()\n if not resOverall['OK']:\n return resOverall\n currentStatus = {'Down': set(), 'Run': set(), 'All': set()}\n informationDict = resOverall['Value']\n for systemsDict in informationDict.values():\n for system, instancesDict in systemsDict.items():\n for instanceName, instanceInfoDict in instancesDict.items():\n identifier = '%s__%s' % (system, instanceName)\n runitStatus = instanceInfoDict.get('RunitStatus')\n if runitStatus in ('Run', 'Down'):\n currentStatus[runitStatus].add(identifier)\n\n currentStatus['All'] = currentStatus['Run'] | currentStatus['Down']\n return S_OK(currentStatus)",
"def get_resources_using_table(self, *, id: str, resource_type: ResourceType) -> Dict[str, List[DashboardSummary]]:\n if resource_type != ResourceType.Dashboard:\n raise NotImplementedError(f'{resource_type.name} is not supported')\n\n with self.client.create_session() as session:\n dashboard_subquery = session.query(RDSDashboardTable.dashboard_rk).filter(\n RDSDashboardTable.table_rk == id\n ).subquery()\n\n usage_subquery = session.query(\n RDSDashboardUsage.dashboard_rk,\n func.sum(RDSDashboardUsage.read_count).label('recent_view_count')\n ).group_by(RDSDashboardUsage.dashboard_rk).filter(\n RDSDashboardUsage.dashboard_rk.in_(dashboard_subquery)\n ).subquery()\n\n query = session.query(RDSDashboard).join(usage_subquery).filter(\n RDSDashboard.rk == usage_subquery.c.dashboard_rk\n ).order_by(usage_subquery.c.recent_view_count.desc())\n\n query = query.options(\n subqueryload(RDSDashboard.group).options(\n subqueryload(RDSDashboardGroup.cluster).options(\n load_only(RDSDashboardCluster.name)\n )\n ),\n subqueryload(RDSDashboard.description).options(\n load_only(RDSDashboardDescription.description)\n ),\n subqueryload(RDSDashboard.execution).options(\n load_only(RDSDashboardExecution.rk, RDSDashboardExecution.timestamp)\n )\n )\n\n dashboards = query.all()\n\n results = []\n for dashboard in dashboards:\n product = dashboard.rk.split('_')[0]\n description = dashboard.description\n group = dashboard.group\n last_exec = next((execution for execution in dashboard.execution\n if execution.rk.endswith('_last_successful_execution')), None)\n results.append(DashboardSummary(uri=dashboard.rk,\n cluster=group.cluster.name,\n group_name=group.name,\n group_url=group.dashboard_group_url,\n product=product,\n name=dashboard.name,\n url=dashboard.dashboard_url,\n description=description.description if description else None,\n last_successful_run_timestamp=int(last_exec.timestamp)\n if last_exec else None))\n return {'dashboards': results}",
"def create_interaction_model_slot_type_v1(self, slot_type, **kwargs):\n # type: (DefinitionData_dad4effb, **Any) -> Union[ApiResponse, object, SlotTypeResponse_1ca513dc, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_slot_type_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type' is set\n if ('slot_type' not in params) or (params['slot_type'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type' in params:\n body_params = params['slot_type']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_response.SlotTypeResponse\", status_code=200, message=\"Returns the generated slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the slot type definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_response.SlotTypeResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def getResourcesByBlocktype(entitytype, blocktype):\n cursor.execute(\n '''SELECT value FROM resource\n JOIN content ON content_id = content.id \n JOIN blocktype ON blocktype_id = blocktype.id\n JOIN entitytype ON entitytype_id = entitytype.id\n WHERE in_dump = True AND entitytype.name = %s\n AND blocktype.name = %s\n ''',\n (entitytype, blocktype,)\n )\n return {c['value'] for c in cursor}",
"def getControlTowerResource(self, typeID):\n\n invTypes = self.metadata.tables['invTypes']\n invCTRes = self.metadata.tables['invControlTowerResources']\n\n stmt = select(\n [invTypes.c.typeName, invTypes.c.volume, invCTRes],\n invCTRes.c.controlTowerTypeID == typeID,\n invCTRes.join(invTypes, \n invTypes.c.typeID == invCTRes.c.resourceTypeID)\n )\n\n results = self.select(stmt)\n if not results:\n raise ValueError('typeid is not a control tower')\n\n return results",
"def local_resource_status(self):\n if not self._local_resource_status:\n self._local_resource_status = self._unpickle_from_file(self.resource_status_cache_filename)\n if not self._local_resource_status:\n self._local_resource_status = dict()\n return self._local_resource_status",
"def get_status(self, run_id):\n return self.client._perform_json(\n \"GET\", \"/projects/%s/runnables/%s/state/%s\" % (self.project_key, self.runnable_type, run_id))",
"def get_status(self):\n if self.__db.channel_exists('{}.today.1_0'.format(self.__dest_code)):\n self.__db.sync_today_channel()\n # maybe just sync this channel? and do same for previous methods\n else:\n self.__db.create_today_channel('{}.today.1_0'.format(self.__dest_code))\n\n conn = sqlite3.connect(self.__db.db_path)\n c = conn.cursor()\n\n today_data = c.execute(\"\"\"SELECT body FROM sync WHERE id = '{}.today.1_0.{}'\"\"\".format(self.__dest_code, self.__entityType)).fetchone()\n\n if today_data is None:\n return None\n else:\n body = json.loads(today_data[0])\n try:\n return body['facilities'][str(self.__id) + ';entityType=' + self.__entityType][0]['scheduleType']\n except:\n return None",
"def task_status_stat_by_request(request, rid):\n qs = ProductionTask.objects.filter(request__reqid=rid)\n stat = get_status_stat(qs)\n return TemplateResponse(request, 'prodtask/_task_status_stat.html', { 'stat': stat, 'reqid': rid})",
"def get_status(self, get_all=False):\n\n status = []\n message = 'does not include components in optimal state'\n if get_all:\n message = 'includes all components'\n\n status.append('=== RaidStatus ({})'.format(message))\n\n for adapter in self.adapters:\n if not get_all and adapter['optimal']:\n continue\n\n status += self._get_block_status(adapter, get_all=get_all)\n\n status.append('=== RaidStatus completed')\n\n return '\\n'.join(status)",
"def get_resource_versions(self, resource_type):\n if self._needs_recalculation:\n self._recalculate_versions()\n self._needs_recalculation = False\n\n return copy.copy(self._versions[resource_type])",
"def related_resources(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['KlusterletStatusRelatedResourcesArgs']]]]:\n return pulumi.get(self, \"related_resources\")",
"def getstatus(self):\n with self.lock:\n return (self.status, self.time_start)",
"def status(self):\n return {\n 'hawkular_services': self._hawkular.status(),\n 'alerts': self.alert.status(),\n 'inventory': self.inventory.status(),\n 'metrics': self.metric.status()\n }",
"def list_interaction_model_slot_types_v1(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, ListSlotTypeResponse_b426c805, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"list_interaction_model_slot_types_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.list_slot_type_response.ListSlotTypeResponse\", status_code=200, message=\"Returns list of slot types for the vendor.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.list_slot_type_response.ListSlotTypeResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_available_time_slot():\n try:\n time_slot_set_list = list()\n # Read all time slot from database\n with open(InterviewCalendarApi.DB_FILE, \"r\") as fd:\n for line in fd:\n time_slot_list = list()\n (_,_,_, time_slots) = line.strip().split(\"|\")\n for time_slot in time_slots.split(\",\"):\n (from_time_slot, to_time_slot) = list(map(int, time_slot.split(\"-\")))\n time_slot_list.extend(range(from_time_slot, (to_time_slot + 1)))\n # Get all available time slot for every user\n time_slot_set_list.append(set(time_slot_list))\n \n # Find common time slot between multiple parties\n available_slots = list(set.intersection(*time_slot_set_list))\n\n msg = json.dumps({\"Status\": \"Success\", \"available_slots\": available_slots})\n return make_response(msg, 200, InterviewCalendarApi.HEADERS)\n except:\n err_msg = sys.exc_info()\n error = json.dumps({'error': 'Unable to find time slot due to error: %s' %str(err_msg)})\n return make_response(error, 401, InterviewCalendarApi.HEADERS)"
] | [
"0.5389657",
"0.52319205",
"0.52153623",
"0.5146299",
"0.503496",
"0.49674195",
"0.49453658",
"0.4932707",
"0.48663652",
"0.48232716",
"0.48213974",
"0.47881374",
"0.47817594",
"0.47817594",
"0.47557944",
"0.47314698",
"0.471271",
"0.4682415",
"0.46182647",
"0.46158686",
"0.4560954",
"0.4557564",
"0.45497432",
"0.45482206",
"0.4524249",
"0.45169336",
"0.4515555",
"0.4510597",
"0.45037788",
"0.45015422"
] | 0.6065341 | 0 |
List all slot type versions for the slot type id. | def list_interaction_model_slot_type_versions_v1(self, slot_type_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, ListSlotTypeVersionResponse_7d552abf, BadRequestError_f854b05]
operation_name = "list_interaction_model_slot_type_versions_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type_id' is set
if ('slot_type_id' not in params) or (params['slot_type_id'] is None):
raise ValueError(
"Missing the required parameter `slot_type_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'slot_type_id' in params:
path_params['slotTypeId'] = params['slot_type_id']
query_params = [] # type: List
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'sort_direction' in params:
query_params.append(('sortDirection', params['sort_direction']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse", status_code=200, message="Returns list of slot type version for the slot type id."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, SlotTypeVersionData_1f3ee474]\n operation_name = \"get_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\", status_code=200, message=\"Returns the slot type version metadata for the given slotTypeId and version.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_interaction_model_slot_type_version_v1(self, slot_type_id, slot_type, **kwargs):\n # type: (str, VersionData_faa770c8, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type' is set\n if ('slot_type' not in params) or (params['slot_type'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type' in params:\n body_params = params['slot_type']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Returns update status location link on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the slot type definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified slot type does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def list_interaction_model_slot_types_v1(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, ListSlotTypeResponse_b426c805, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"list_interaction_model_slot_types_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.list_slot_type_response.ListSlotTypeResponse\", status_code=200, message=\"Returns list of slot types for the vendor.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.list_slot_type_response.ListSlotTypeResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def list_versions(self, service_id):\n return [self.fastly_cache[service_id]['service_details']]",
"def ListVersions(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def list_versions(self):\n version_url = self._get_base_version_url()\n\n resp, body = self.raw_request(version_url, 'GET')\n # NOTE: We need a raw_request() here instead of request() call because\n # \"list API versions\" API doesn't require an authentication and we can\n # skip it with raw_request() call.\n self._error_checker(resp, body)\n\n body = json.loads(body)\n self.validate_response(schema.list_versions, resp, body)\n return rest_client.ResponseBody(resp, body)",
"def delete_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type version for this slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_resource_versions(resource_type):\n return _get_cached_tracker().get_resource_versions(resource_type)",
"def ListVersions(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def list_versions(self, project_id, model_id):\n endpoint = \"/project/{}/model/{}/version\".format(project_id, model_id)\n return self._get(endpoint, _ModelVersionSchema(many=True))",
"def select_versions(self):\n return []",
"def list_versions(self):\n if not USE_GCLOUD:\n return self.run_appcfg(['list_versions'])\n data = self.run_gcloud(['app', 'versions', 'list'])\n per_module = collections.defaultdict(list)\n for deployment in data:\n service = deployment['service'].encode('utf-8')\n version_id = deployment['id'].encode('utf-8')\n per_module[service].append(version_id)\n return dict(per_module)",
"def list_versions(quartus_versions):\n for key in quartus_versions.keys():\n print(key)",
"def get_resource_versions(self, resource_type):\n if self._needs_recalculation:\n self._recalculate_versions()\n self._needs_recalculation = False\n\n return copy.copy(self._versions[resource_type])",
"def all(self):\r\n if self._versions is None or \\\r\n len(self._versions) == 0:\r\n url = \"%s/versions\" % self._url\r\n params = {'f':'json'}\r\n res = self._con.get(url, params)\r\n self._versions = []\r\n if 'versions' in res:\r\n for v in res['versions']:\r\n guid = v['versionGuid'][1:-1]\r\n vurl = \"%s/versions/%s\" % (self._url, guid)\r\n self._versions.append(Version(url=vurl,\r\n flc=self._flc,\r\n gis=self._gis))\r\n return self._versions\r\n return self._versions",
"def index(self, request):\n versions = []\n for key, data in VERSIONS.items():\n v = BaseVersion(\n data[\"id\"],\n data[\"status\"],\n request.application_url,\n data[\"updated\"])\n versions.append(v)\n return wsgi.Result(VersionsDataView(versions))",
"def list_versions(self,\n uid: UUID,\n page: Optional[int] = None,\n per_page: int = 100) -> Iterable[GemTable]:\n def fetch_versions(page: Optional[int],\n per_page: int) -> Tuple[Iterable[dict], str]:\n data = self.session.get_resource(self._get_path() + '/' + str(uid),\n params=self._page_params(page, per_page))\n return (data[self._collection_key], data.get('next', \"\"))\n\n def build_versions(collection: Iterable[dict]) -> Iterable[GemTable]:\n for item in collection:\n yield self.build(item)\n\n return self._paginator.paginate(\n # Don't deduplicate on uid since uids are shared between versions\n fetch_versions, build_versions, page, per_page, deduplicate=False)",
"def list_data_version_and_types(self):\n\n return self.dataset_registry.list_data_version_and_types()",
"def get_versions(self):\n raise NotImplementedError",
"def list_dataset_version(self, version_id):\n assert self.dataset_id, 'dataset_id required!'\n return self._datasets_request('GET', dataset_id=self.dataset_id, versions_request=True,\n version_id=version_id)",
"def get_versions():\n ret_obj = {'versions': picard_versions(current_app)}\n return make_response(jsonify(ret_obj), 200)",
"def get_slots_for_date(url: str, session: requests.Session) -> List[Dict]:\n response = session.get(\n url,\n headers={\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"Adrum\": \"isAjax:true\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n },\n )\n\n slots = list(\n filter(lambda item: item[\"status\"] != \"UnAvailable\", response.json()[\"slots\"])\n )\n\n return slots",
"def update_interaction_model_slot_type_version_v1(self, slot_type_id, version, slot_type_update, **kwargs):\n # type: (str, str, SlotTypeUpdate_ae01835f, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type_update' is set\n if ('slot_type_update' not in params) or (params['slot_type_update'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_update` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}/update'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type_update' in params:\n body_params = params['slot_type_update']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_list_versions(self):\n self.metadata.create_or_update(data=self.create)\n\n # Find by name\n res_name = self.metadata.get_by_name(\n entity=Dashboard, fqn=self.entity.fullyQualifiedName\n )\n\n res = self.metadata.get_list_entity_versions(\n entity=Dashboard, entity_id=res_name.id.__root__\n )\n assert res",
"def versions(self) -> Dict[str, str]:\n self.__logger.debug('Eva.versions called')\n return self.__http_client.api_versions()",
"def cluster_setslot_stable(self, slot_id: int) -> ResponseT:\n return self.execute_command(\"CLUSTER SETSLOT\", slot_id, \"STABLE\")",
"def ListVersions(self, request, timeout, metadata=None, with_call=False, protocol_options=None):\n raise NotImplementedError()",
"def versions(self, stored=False) -> List['RadsSolutionVersion']:\n\n if stored:\n fspath = self.storage.fspath(self.path)\n if not os.path.isdir(fspath):\n return [] # solution not in storage\n listing = []\n for path in os.listdir(fspath):\n if not os.path.isdir(os.path.join(fspath, path)):\n continue\n listing.append(path)\n else:\n logger.debug(f\"retrieve versions of {self}\")\n listing = self.storage.request_text(f\"{self.path}/releaselisting\").splitlines()\n return sorted(RadsSolutionVersion(self, RadsVersion(l)) for l in listing)",
"def get_all_voltages(self):\n self.check_validity()\n\n return self.ipcon.send_request(self, BrickletIndustrialDualAnalogInV2.FUNCTION_GET_ALL_VOLTAGES, (), '', 16, '2i')",
"def GetAllSlots(cls):\n slots = []\n for parent in cls.__mro__:\n slots.extend(getattr(parent, \"__slots__\", []))\n return slots"
] | [
"0.6106796",
"0.6043508",
"0.59520197",
"0.58241546",
"0.5630513",
"0.5481223",
"0.54357177",
"0.53851986",
"0.53153414",
"0.52639025",
"0.5244154",
"0.5198423",
"0.5193687",
"0.51933515",
"0.51930255",
"0.51110554",
"0.5060837",
"0.5051601",
"0.50498486",
"0.5047052",
"0.5046055",
"0.49836776",
"0.4982919",
"0.49710992",
"0.495922",
"0.4943203",
"0.49334934",
"0.49182692",
"0.4917806",
"0.49056503"
] | 0.752099 | 0 |
Create a new version of slot type entity for the given slotTypeId. | def create_interaction_model_slot_type_version_v1(self, slot_type_id, slot_type, **kwargs):
# type: (str, VersionData_faa770c8, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "create_interaction_model_slot_type_version_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type_id' is set
if ('slot_type_id' not in params) or (params['slot_type_id'] is None):
raise ValueError(
"Missing the required parameter `slot_type_id` when calling `" + operation_name + "`")
# verify the required parameter 'slot_type' is set
if ('slot_type' not in params) or (params['slot_type'] is None):
raise ValueError(
"Missing the required parameter `slot_type` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'slot_type_id' in params:
path_params['slotTypeId'] = params['slot_type_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'slot_type' in params:
body_params = params['slot_type']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message="Returns update status location link on success."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error e.g. the slot type definition is invalid."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The specified slot type does not exist."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_interaction_model_slot_type_v1(self, slot_type, **kwargs):\n # type: (DefinitionData_dad4effb, **Any) -> Union[ApiResponse, object, SlotTypeResponse_1ca513dc, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_slot_type_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type' is set\n if ('slot_type' not in params) or (params['slot_type'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type' in params:\n body_params = params['slot_type']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_response.SlotTypeResponse\", status_code=200, message=\"Returns the generated slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the slot type definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_response.SlotTypeResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_interaction_model_slot_type_definition_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, SlotTypeDefinitionOutput_20e87f7, BadRequestError_f854b05]\n operation_name = \"get_interaction_model_slot_type_definition_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput\", status_code=200, message=\"The slot type definition.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"The slot type cannot be retrieved due to errors listed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_definition_output.SlotTypeDefinitionOutput\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_definition(self, block_type, slug=None):\n raise NotImplementedError()",
"def get_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, SlotTypeVersionData_1f3ee474]\n operation_name = \"get_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\", status_code=200, message=\"Returns the slot type version metadata for the given slotTypeId and version.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_definition(self, block_type, slug=None):\n prefix = \"d\"\n if slug:\n prefix += \"_\" + slug\n def_id = self._next_id(prefix)\n self._definitions[def_id] = block_type\n return def_id",
"def delete_interaction_model_slot_type_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No content; just confirm the slot type is deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"The slot type cannot be deleted from reasons due to in-use by other entities.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def update_interaction_model_slot_type_v1(self, slot_type_id, update_request, **kwargs):\n # type: (str, UpdateRequest_43de537, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_interaction_model_slot_type_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_request' is set\n if ('update_request' not in params) or (params['update_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/update'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'update_request' in params:\n body_params = params['update_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No content, indicates the fields were successfully updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def new_entity_type(name, client=default):\n data = {\"name\": name}\n return raw.create(\"entity-types\", data, client=client)",
"def delete_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type version for this slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def list_interaction_model_slot_type_versions_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, ListSlotTypeVersionResponse_7d552abf, BadRequestError_f854b05]\n operation_name = \"list_interaction_model_slot_type_versions_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\", status_code=200, message=\"Returns list of slot type version for the slot type id.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_object_type(self, object_type=None):\n # Return Value\n # ------------\n # {object_type_id: ''}\n #\n if not is_basic_identifier(object_type.name):\n raise BadRequest(\"Invalid object_type name: %s\" % object_type.name)\n if not is_yaml_string_valid(object_type.definition):\n raise BadRequest(\"Invalid YAML definition\")\n object_type_id, version = self.clients.resource_registry.create(object_type)\n return object_type_id",
"def create_for_object(self, parent_object, slot, role=\"m\", title=None):\n from .db import Placeholder\n\n parent_attrs = get_parent_lookup_kwargs(parent_object)\n obj = self.create(\n slot=slot,\n role=role or Placeholder.MAIN,\n title=title or slot.title().replace(\"_\", \" \"),\n **parent_attrs\n )\n obj.parent = parent_object # fill the reverse cache\n return obj",
"def create(self, item_type, uuid):\n return self.write.create(item_type, uuid)",
"def update_interaction_model_slot_type_version_v1(self, slot_type_id, version, slot_type_update, **kwargs):\n # type: (str, str, SlotTypeUpdate_ae01835f, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type_update' is set\n if ('slot_type_update' not in params) or (params['slot_type_update'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_update` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}/update'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type_update' in params:\n body_params = params['slot_type_update']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def setTypeId(self, x, y, z, type_):\n state = self.world.getBlockAt(x, y, z).getState()\n state.setTypeId(type_)\n self.list_.add(state)",
"def _insertNew(self, position):\n assert position >= 0 and position <= len(self._subSlots)\n slot = self._getInstance(self, level=self.level - 1)\n self._subSlots.insert(position, slot)\n slot.name = self.name\n if self._value is not None:\n slot.setValue(self._value)\n return slot",
"def new_parametertype(request, recipe, **_kwargs):\n return create_view(\n request,\n _(\"Parameter type for recipe %s\") % recipe.name,\n ParameterTypeForm,\n recipe=recipe,\n )",
"def create_parking_lot(self, allow_slots):\n allow_slots = int(allow_slots)\n\n if len(self.slots) > 0:\n print(\"Parking Lot is already created\")\n return\n\n if allow_slots < 1:\n print(\"Number of slot: %s provided is incorrect.\" % allow_slots)\n return\n\n for i in range(1, allow_slots + 1):\n self.slots[i] = Slot(slot_no=i, available=True)\n print(\"Created a parking lot with %s slots\" % allow_slots)",
"async def create_block_type(self, block_type: BlockTypeCreate) -> BlockType:\n try:\n response = await self._client.post(\n \"/block_types/\",\n json=block_type.dict(\n json_compatible=True, exclude_unset=True, exclude={\"id\"}\n ),\n )\n except httpx.HTTPStatusError as e:\n if e.response.status_code == status.HTTP_409_CONFLICT:\n raise prefect.exceptions.ObjectAlreadyExists(http_exc=e) from e\n else:\n raise\n return BlockType.parse_obj(response.json())",
"def get_interaction_model_slot_type_build_status_v1(self, slot_type_id, update_request_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, SlotTypeStatus_a293ebfc, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_interaction_model_slot_type_build_status_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_request_id' is set\n if ('update_request_id' not in params) or (params['update_request_id'] is None):\n raise ValueError(\n \"Missing the required parameter `update_request_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/updateRequest/{updateRequestId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'update_request_id' in params:\n path_params['updateRequestId'] = params['update_request_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_status.SlotTypeStatus\", status_code=200, message=\"Returns the build status and error codes for the given slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.model_type.slot_type_status.SlotTypeStatus\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_xblock(\n self, runtime, course_key, block_type, block_id=None, fields=None,\n definition_id=None, parent_xblock=None, **kwargs\n ):\n assert runtime is not None\n\n xblock_class = runtime.load_block_type(block_type)\n json_data = {\n 'block_type': block_type,\n 'fields': {},\n }\n if definition_id is not None:\n json_data['definition'] = definition_id\n if parent_xblock is None:\n # If no parent, then nothing to inherit.\n inherited_settings = {}\n else:\n inherited_settings = parent_xblock.xblock_kvs.inherited_settings.copy()\n if fields is not None:\n for field_name in inheritance.InheritanceMixin.fields: # lint-amnesty, pylint: disable=not-an-iterable\n if field_name in fields:\n inherited_settings[field_name] = fields[field_name]\n\n new_block = runtime.xblock_from_json(\n xblock_class,\n course_key,\n BlockKey(block_type, block_id) if block_id else None,\n BlockData(**json_data),\n **kwargs\n )\n for field_name, value in (fields or {}).items():\n setattr(new_block, field_name, value)\n\n if parent_xblock is not None:\n parent_xblock.children.append(new_block.scope_ids.usage_id)\n # decache pending children field settings\n parent_xblock.save()\n return new_block",
"def generate_slot(slot_name, slot_description, slot_raw_filename):\n slot = {\n 'enumerationValues': [],\n \"name\": slot_name,\n \"description\": slot_description\n }\n slot_raw_vals = read_raw_vals(slot_raw_filename)\n for slot_val in slot_raw_vals:\n slot['enumerationValues'].append({'value': slot_val})\n\n return slot",
"def create(server,idx):\n \n uaModel.__create_type(server,idx)\n uaModel.__create_objects(server,idx)",
"def test_save_slot(self):\n business = BUSINESS_FACTORY.create_business()\n slot = Slot.objects.create(site_id=2, business_id=business.id,\n start_date = datetime.date.today(),\n end_date = datetime.date.today() + datetime.timedelta(1))\n LOG.debug(slot)\n self.assertTrue(slot.id)\n self.assertEqual(slot.renewal_rate, 10)\n self.assertEqual(slot.is_autorenew, False)",
"def _new_entity(client, entity_type):\n\n return datastore.Entity(_load_key(client, entity_type))",
"def add_vehicle_cfg_part_type(self, parttype):\n pt_cond = SQLBinaryExpr(SQLFuncExpr(self.db_func_map[DB_FUNC_NAME_LOWER],\n COL_NAME_PARTTYPES_NAME),\n OP_EQ, SQLLiteral(parttype[COL_NAME_PARTTYPES_NAME].lower()))\n entries = self.select_generic_data(table_list=[TABLE_NAME_PARTTYPES], where=pt_cond)\n if len(entries) <= 0:\n ptid = self._get_next_id(TABLE_NAME_PARTTYPES, COL_NAME_PARTTYPES_PARTTYPEID)\n parttype[COL_NAME_PARTTYPES_PARTTYPEID] = ptid\n self.add_generic_data(parttype, TABLE_NAME_PARTTYPES)\n return ptid\n else:\n if self.error_tolerance < ERROR_TOLERANCE_LOW:\n raise AdasDBError(\"Part type '%s' exists already in the catalog.\" % parttype[COL_NAME_PARTTYPES_NAME])\n else:\n warn(\"Part type '\" + parttype[COL_NAME_PARTTYPES_NAME] + \"' already exists in the catalog.\")\n if len(entries) == 1:\n return entries[0][COL_NAME_PARTTYPES_PARTTYPEID]\n elif len(entries) > 1:\n tmp = \"Part type '%s' \" % (parttype[COL_NAME_PARTTYPES_NAME])\n tmp += \"cannot be resolved because it is ambiguous. (%s)\" % entries\n raise AdasDBError(tmp)",
"def create_type(name):\n\n new_type = Type(name=name)\n db.session.add(new_type)\n db.session.commit()\n return new_type",
"def __create_type(server,idx):\n\n types = Factory.get_list_types()\n\n # node de tipos no opcua\n uatypes = server.get_base_objectType_node()\n \n try:\n \n for t in types:\n\n # cria os tipos de objeto/variaveis no servidor opcua\n ua_type = Factory.create_type(uatypes,idx,t) \n\n logger.info(\"Criado o tipo: {} {}\".format(t,ua_type))\n\n except :\n logger.error(\"Problema ao cria os tipos {}\".format(types))",
"def add_object(self, object_type, data=None, read_from_netbox=False, source=None):\n\n # create new object\n new_object = object_type(data, read_from_netbox=read_from_netbox, inventory=self, source=source)\n\n # add to inventory\n self.base_structure[object_type.name].append(new_object)\n\n if read_from_netbox is False:\n log.info(f\"Created new {new_object.name} object: {new_object.get_display_name()}\")\n\n return new_object",
"def servicemanage_type_create(context, values):\n if not values.get('id'):\n values['id'] = str(uuid.uuid4())\n\n session = get_session()\n with session.begin():\n try:\n servicemanage_type_get_by_name(context, values['name'], session)\n raise exception.ServiceManageTypeExists(id=values['name'])\n except exception.ServiceManageTypeNotFoundByName:\n pass\n try:\n servicemanage_type_get(context, values['id'], session)\n raise exception.ServiceManageTypeExists(id=values['id'])\n except exception.ServiceManageTypeNotFound:\n pass\n try:\n values['extra_specs'] = _metadata_refs(values.get('extra_specs'),\n models.ServiceManageTypeExtraSpecs)\n servicemanage_type_ref = models.ServiceManageTypes()\n servicemanage_type_ref.update(values)\n servicemanage_type_ref.save()\n except Exception, e:\n raise exception.DBError(e)\n return servicemanage_type_ref"
] | [
"0.6595384",
"0.5778384",
"0.56464463",
"0.54920423",
"0.5468983",
"0.5460118",
"0.5449998",
"0.52916855",
"0.52558595",
"0.5233566",
"0.50949",
"0.5021223",
"0.49814785",
"0.49695474",
"0.496029",
"0.4954763",
"0.48741883",
"0.4864564",
"0.48532182",
"0.48508102",
"0.48163706",
"0.48102143",
"0.4808406",
"0.4791915",
"0.4791299",
"0.4751082",
"0.47461826",
"0.47309723",
"0.4677087",
"0.46765435"
] | 0.6711128 | 0 |
Delete slot type version. | def delete_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "delete_interaction_model_slot_type_version_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type_id' is set
if ('slot_type_id' not in params) or (params['slot_type_id'] is None):
raise ValueError(
"Missing the required parameter `slot_type_id` when calling `" + operation_name + "`")
# verify the required parameter 'version' is set
if ('version' not in params) or (params['version'] is None):
raise ValueError(
"Missing the required parameter `version` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'slot_type_id' in params:
path_params['slotTypeId'] = params['slot_type_id']
if 'version' in params:
path_params['version'] = params['version']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="No Content; Confirms that version is successfully deleted."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="There is no slot type version for this slotTypeId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="DELETE",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def delete_version(self):\n pass",
"def delete_interaction_model_slot_type_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No content; just confirm the slot type is deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"The slot type cannot be deleted from reasons due to in-use by other entities.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def DeleteVersion(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def remove_card(self, slot):\n del self._starting_card[slot]",
"def delete_version(self, package, version):\n with self._conn.begin():\n self._conn.execute(\n \"VALUES (delete_version(%s, %s))\", (package, version))",
"def delete_kind(self, kind, version=None):\n bindings = self.bindings\n name = self.TEST_APP + \"-\" + kind\n payload = self.agent.make_json_payload_from_kwargs(\n job=[\n {\n \"cloudProvider\": \"kubernetes\",\n \"type\": \"deleteManifest\",\n \"account\": bindings[\"SPINNAKER_KUBERNETES_V2_ACCOUNT\"],\n \"user\": \"[anonymous]\",\n \"kinds\": [kind],\n \"location\": self.TEST_NAMESPACE,\n \"options\": {},\n \"labelSelectors\": {\n \"selectors\": [\n {\"kind\": \"EQUALS\", \"key\": \"app\", \"values\": [self.TEST_APP]}\n ]\n },\n }\n ],\n application=self.TEST_APP,\n description=\"Destroy Manifest\",\n )\n\n if version is not None:\n name = name + \"-\" + version\n\n builder = kube.KubeContractBuilder(self.kube_v2_observer)\n (\n builder.new_clause_builder(\"Manifest Removed\")\n .get_resources(kind, extra_args=[name, \"--namespace\", self.TEST_NAMESPACE])\n .EXPECT(self.mp.not_found_observation_predicate())\n )\n\n return st.OperationContract(\n self.new_post_operation(title=\"delete_kind\", data=payload, path=\"tasks\"),\n contract=builder.build(),\n )",
"def versionable_delete(self, instance, timestamp):\n instance._delete_at(timestamp, using=self.using)",
"def test_delete_hyperflex_hxdp_version(self):\n pass",
"def DeleteVersion(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def remove_slot(self, slot):\n if slot in self.slots:\n idx = self.slots.index(slot)\n # update location of rest slot\n for s in self.slots[idx:]:\n s.set_location(s.get_location()-1)\n self.slots.remove(slot)",
"def delete_parametertype(request, parametertype, **_kwargs):\n pass",
"def delete(self):\n self.connection.deprecate_activity_type(self.domain.name, self.name, self.version)",
"def delete_item(self, key):\n deleted_slot = self.count_hash(key, len(self.slots))\n\n if self.slots[deleted_slot] == key:\n self.slots[deleted_slot] = None\n self.data[deleted_slot] = None\n elif isinstance(self.slots[deleted_slot], tuple):\n index_tuple = (self.slots[deleted_slot].index(key))\n list_slot = list(self.slots[deleted_slot])\n list_data = list(self.data[deleted_slot])\n list_slot.pop(index_tuple)\n list_data.pop(index_tuple)\n self.slots[deleted_slot] = tuple(list_slot)\n self.data[deleted_slot] = tuple(list_data)",
"def delete(self):\n del self.shx.atoms[self.index]",
"def test_delete_pokemon_slot_4(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 4\n\n pokemon_name = \"Gastrodon\"\n\n response = self.client.post(\"/teams/add/\", {\n \"id\":str(team_pk),\n \"slot\": str(slot),\n \"pokemon_name\": pokemon_name,\n })\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)\n poke = Team.objects.get(pk=team_pk)\n self.assertFalse(poke.slot_4_pokemon)",
"def test_delete_pokemon_slot_4_not_exists(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 4\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)",
"def version_delete(self, version_id):\n try:\n castle_delete_version(self.conn, version_id)\n pycastle_log.info(\"Deleted version {0}\".format(version_id))\n except Exception, e:\n pycastle_log.error(str(self)+\" got exception {0}:{1}\".format(type(e), e))\n raise",
"def type(self):\n ida_bytes.del_items(self.ea)",
"def test_delete_pokemon_slot_2_not_exists(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 2\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)",
"def test_delete_hyperflex_software_version_policy(self):\n pass",
"def nfvi_delete_instance_type(instance_type_uuid, callback):\n cmd_id = _compute_plugin.invoke_plugin('delete_instance_type',\n instance_type_uuid,\n callback=callback)\n return cmd_id",
"def slotDelete(self):\n item = self.groupListBox.item((self.groupListBox.currentItem()))\n group = item.text().ascii()\n Group.Sequencer().slotRemoveGlobalGroup(group)",
"def test_delete_pokemon_slot_1_not_exists(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 1\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)",
"def test_delete_pokemon_slot_2(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 2\n\n pokemon_name = \"Gastrodon\"\n\n response = self.client.post(\"/teams/add/\", {\n \"id\":str(team_pk),\n \"slot\": str(slot),\n \"pokemon_name\": pokemon_name,\n })\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)\n poke = Team.objects.get(pk=team_pk)\n self.assertFalse(poke.slot_2_pokemon)",
"def test_delete_pokemon_slot_6(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 6\n\n pokemon_name = \"Gastrodon\"\n\n response = self.client.post(\"/teams/add/\", {\n \"id\":str(team_pk),\n \"slot\": str(slot),\n \"pokemon_name\": pokemon_name,\n })\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)\n poke = Team.objects.get(pk=team_pk)\n self.assertFalse(poke.slot_6_pokemon)",
"def test_delete_pokemon_slot_1(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 1\n\n pokemon_name = \"Gastrodon\"\n\n response = self.client.post(\"/teams/add/\", {\n \"id\":str(team_pk),\n \"slot\": str(slot),\n \"pokemon_name\": pokemon_name,\n })\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)\n poke = Team.objects.get(pk=team_pk)\n self.assertFalse(poke.slot_1_pokemon)",
"def test_delete_pokemon_slot_6_not_exists(self):\n response = self.client.post(\"/teams/create/\",\n {\n \"trainer\": str(self.trainer_id),\n })\n team_pk = response.json()[\"id\"]\n slot = 6\n\n response = self.client.delete(\"/teams/deletepokemon/{}/{}/\".format(team_pk, str(slot)))\n self.assertEqual(response.status_code, 204)",
"def delete_encryption_type(self, volume_type):\n aname = \"cinder_v%s.delete_encryption_type\" % self.version\n with atomic.ActionTimer(self, aname):\n resp = self._get_client().volume_encryption_types.delete(\n volume_type)\n if (resp[0].status_code != 202):\n raise exceptions.RallyException(\n \"EncryptionType Deletion Failed\")",
"def test_delete_hyperflex_server_firmware_version(self):\n pass",
"def test_vault_delete_vault_item(self):\n pass"
] | [
"0.69133455",
"0.65906924",
"0.58580124",
"0.5852691",
"0.58427644",
"0.5832888",
"0.5797444",
"0.5750808",
"0.56815904",
"0.56198233",
"0.55722696",
"0.55600405",
"0.5533061",
"0.5531285",
"0.54934555",
"0.54884666",
"0.547365",
"0.54593927",
"0.54386854",
"0.5433934",
"0.54321504",
"0.5432048",
"0.54196316",
"0.54116863",
"0.5401502",
"0.53965384",
"0.53816354",
"0.5367596",
"0.5364674",
"0.53622556"
] | 0.7003186 | 0 |
Get slot type version data of given slot type version. | def get_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, SlotTypeVersionData_1f3ee474]
operation_name = "get_interaction_model_slot_type_version_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'slot_type_id' is set
if ('slot_type_id' not in params) or (params['slot_type_id'] is None):
raise ValueError(
"Missing the required parameter `slot_type_id` when calling `" + operation_name + "`")
# verify the required parameter 'version' is set
if ('version' not in params) or (params['version'] is None):
raise ValueError(
"Missing the required parameter `version` when calling `" + operation_name + "`")
resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'slot_type_id' in params:
path_params['slotTypeId'] = params['slot_type_id']
if 'version' in params:
path_params['version'] = params['version']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData", status_code=200, message="Returns the slot type version metadata for the given slotTypeId and version."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="There is no slot type defined for the slotTypeId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.interaction_model.type_version.slot_type_version_data.SlotTypeVersionData")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def v(self, n):\n\n if n == 0:\n return None\n if n < self.maxSlot + 1:\n return self.slotType\n m = n - self.maxSlot\n if m <= len(self.data):\n return self.data[m - 1]\n return None",
"def create_interaction_model_slot_type_version_v1(self, slot_type_id, slot_type, **kwargs):\n # type: (str, VersionData_faa770c8, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type' is set\n if ('slot_type' not in params) or (params['slot_type'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type' in params:\n body_params = params['slot_type']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Returns update status location link on success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. the slot type definition is invalid.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified slot type does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def delete_interaction_model_slot_type_version_v1(self, slot_type_id, version, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully deleted.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type version for this slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_dialogflow_slot_value(data, slot=None) -> Union[Any, None]:\n if \"result\" in data:\n # using V1 API\n contexts = data[\"result\"][\"contexts\"][0]\n if contexts:\n parameters = contexts.get(\"parameters\")\n else:\n parameters = data[\"result\"][\"parameters\"]\n if slot is None:\n return parameters\n elif slot in parameters:\n return parameters[slot]\n else:\n return None\n elif \"queryResult\" in data:\n # using V2 API\n contexts = data[\"queryResult\"][\"outputContexts\"][0]\n if contexts:\n parameters = contexts.get(\"parameters\")\n else:\n parameters = data[\"queryResult\"][\"parameters\"]\n if slot is None:\n return parameters\n elif slot in parameters:\n return parameters[slot]\n else:\n return None\n else:\n return None",
"def getVersion(self,type='BASIS'):\r\n\r\n logStr = \"{0:s}.{1:s}: \".format(self.__class__.__name__, sys._getframe().f_code.co_name)\r\n logger.debug(\"{0:s}{1:s}\".format(logStr,'Start.')) \r\n \r\n try: \r\n vStr=None\r\n t=self.dataFrames['DATENEBENE']\r\n if 'VERSION' not in t.columns.tolist():\r\n logger.debug(\"{0:s}Spalte VERSION not in Tabelle DATENEBENE - vStr set to Sir3S-90-09\".format(logStr)) \r\n vStr='Sir3S-90-09'\r\n else: \r\n tType=t[t['TYP'].str.contains(type)]\r\n vStr=tType['VERSION'].iloc[0] \r\n if vStr == None or str(vStr) == 'nan' or str(vStr) == 'NaN':\r\n logger.debug(\"{0:s}vStr is None (type={1:s}) - vStr set to Sir3S-90-09\".format(logStr,type)) \r\n vStr='Sir3S-90-09' \r\n logger.debug(\"{0:s}vStr: {1:s} (type={2:s})\".format(logStr,str(vStr),type)) \r\n \r\n except Exception as e:\r\n logStrFinal=\"{:s}Exception: Line: {:d}: {!s:s}: {:s}\".format(logStr,sys.exc_info()[-1].tb_lineno,type(e),str(e)) \r\n logger.error(logStrFinal) \r\n raise XmError(logStrFinal) \r\n finally:\r\n logger.debug(\"{0:s}{1:s}\".format(logStr,'_Done.')) \r\n return vStr",
"def get_slot(self, c):\n if 'slot_number' in c.keys():\n slot_number = c['slot_number']\n return slot_number\n else:\n raise ValueError(self.no_selection_msg())\n \n # returnValue(voltage * units.V)",
"def get_version(self, key, version=None):\n if version is None:\n if key not in self._data:\n raise KeyError(\"No value associated with any version of %s\"\n % key)\n vs = self._data[key]\n return vs[max(vs)]\n\n try:\n return self._data[key][version]\n except KeyError:\n raise KeyError(\"No value associated with version %s of %s\" %\n (version, key))",
"def list_interaction_model_slot_type_versions_v1(self, slot_type_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, ListSlotTypeVersionResponse_7d552abf, BadRequestError_f854b05]\n operation_name = \"list_interaction_model_slot_type_versions_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'sort_direction' in params:\n query_params.append(('sortDirection', params['sort_direction']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\", status_code=200, message=\"Returns list of slot type version for the slot type id.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.interaction_model.type_version.list_slot_type_version_response.ListSlotTypeVersionResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_alexa_slot_value(data, slot=None) -> Union[str, None]:\n if \"request\" in data and \"intent\" in data[\"request\"] and \"slots\" in data[\"request\"][\"intent\"]:\n if slot is None:\n return data[\"request\"][\"intent\"][\"slots\"]\n else:\n if slot in data[\"request\"][\"intent\"][\"slots\"] and \"value\" in data[\"request\"][\"intent\"][\"slots\"][slot]:\n return data[\"request\"][\"intent\"][\"slots\"][slot][\"value\"]\n else:\n return None\n else:\n return None",
"def loads_value(type_key, binary_data, version, vectors):\n # pylint: disable=too-many-return-statements\n\n if isinstance(type_key, bytes):\n type_key = type_keys.Value(type_key)\n\n if type_key == type_keys.Value.INTEGER:\n return struct.unpack(\"!q\", binary_data)[0]\n if type_key == type_keys.Value.FLOAT:\n return struct.unpack(\"!d\", binary_data)[0]\n if type_key == type_keys.Value.COMPLEX:\n return complex(*struct.unpack(formats.COMPLEX_PACK, binary_data))\n if type_key == type_keys.Value.NUMPY_OBJ:\n return common.data_from_binary(binary_data, np.load)\n if type_key == type_keys.Value.STRING:\n return binary_data.decode(common.ENCODE)\n if type_key == type_keys.Value.NULL:\n return None\n if type_key == type_keys.Value.CASE_DEFAULT:\n return CASE_DEFAULT\n if type_key == type_keys.Value.PARAMETER_VECTOR:\n return common.data_from_binary(binary_data, _read_parameter_vec, vectors=vectors)\n if type_key == type_keys.Value.PARAMETER:\n return common.data_from_binary(binary_data, _read_parameter)\n if type_key == type_keys.Value.PARAMETER_EXPRESSION:\n if version < 3:\n return common.data_from_binary(binary_data, _read_parameter_expression)\n else:\n return common.data_from_binary(\n binary_data, _read_parameter_expression_v3, vectors=vectors\n )\n\n raise exceptions.QpyError(f\"Serialization for {type_key} is not implemented in value I/O.\")",
"def _get_slot_variable(self, layer_name, slot_name):\n return self._tls._slot_variables.get(layer_name, {}).get(\n slot_name, None\n )",
"def read_vsys_data(command, version):\n # Send request through vsys (for slice context).\n data = read_vsys_data_direct(command)\n\n if 'data' not in data:\n collectd.error('%s: returned value has no \"data\" field.' % command)\n return {}\n\n if 'version' not in data:\n collectd.error('%s: returned value has no \"version\" field.' % command)\n return {}\n\n if 'message_type' in data and data['message_type'] != command:\n collectd.error('Returned message_type does not match request.')\n collectd.error('Requested: %s' % command)\n collectd.error('Received : %s' % data['message_type'])\n return {}\n\n if data['version'] != version:\n msg = '%s: version mismatch: found (%d), expected (%d)' % (\n command, data['version'], version)\n collectd.warning(msg)\n\n return data['data']",
"def valid_values(cls, release_type):\n return versions.get(release_type)",
"def handle_slot_select(data: bytes) -> Tuple[bytes, str]:\n new_slot = struct.unpack('B', data[:1])[0]\n return data[1:], f'New slot: {new_slot}'",
"def version (self, type='other'):\n return self._response.version (type)",
"def unpack(self, data_type):\n\t\tif data_type in data_types:\n\t\t\tformat = data_types[data_type]\n\t\t\treturn self.unpack_real(format[0], format[1])\n\t\t\n\t\tif data_type == \"string8\":\n\t\t\tlength = self.unpack('short')\n\t\t\tif length < 0:\n\t\t\t\traise Exception(\"Negative length for string\")\n\t\t\tif len(self.buff) < length:\n\t\t\t\traise IncompleteData()\n\t\t\tstring = self.buff[:length]\n\t\t\tself.buff = self.buff[length:]\n\t\t\treturn string\n\t\tif data_type == \"string16\":\n\t\t\tlength = self.unpack('short')\n\t\t\tif length < 0:\n\t\t\t\traise Exception(\"Negative length for string\")\n\t\t\tif len(self.buff) < 2*length:\n\t\t\t\traise IncompleteData()\n\t\t\tstring = self.buff[:2*length].decode('utf-16be')\n\t\t\tself.buff = self.buff[2*length:]\n\t\t\treturn string\n\t\tif data_type == \"slot\":\n\t\t\to = {}\n\t\t\to[\"id\"] = self.unpack('short')\n\t\t\tif o[\"id\"] > 0:\n\t\t\t\to[\"amount\"] = self.unpack('byte')\n\t\t\t\to[\"damage\"] = self.unpack('short')\n\t\t\tif o[\"id\"] in SLOT_EXTRA_DATA_IDS:\n\t\t\t\textra_len = self.unpack('short')\n\t\t\t\tif extra_len <= 0:\n\t\t\t\t\to[\"extra\"] = None\n\t\t\t\telse:\n\t\t\t\t\tif len(self.buff) < extra_len:\n\t\t\t\t\t\traise IncompleteData()\n\t\t\t\t\textra_buff = self.buff[:extra_len]\n\t\t\t\t\tself.buff = self.buff[extra_len:]\n\t\t\t\t\to[\"extra\"] = extra_buff\n\t\t\treturn o\n\t\tif data_type == \"metadata\":\n\t\t\t#[(17, 0), (0, 0), (16, -1)]\n\t\t\to = []\n\t\t\tmtype = self.unpack('byte')\n\t\t\twhile mtype != 127:\n\t\t\t\tmtype2 = mtype >> 5\n\t\t\t\tt = 0\n\t\t\t\tif mtype2 == 0: t = self.unpack('byte') \n\t\t\t\tif mtype2 == 1: t = self.unpack('short') \n\t\t\t\tif mtype2 == 2: t = self.unpack('int') \n\t\t\t\tif mtype2 == 3: t = self.unpack('float') \n\t\t\t\tif mtype2 == 4: t = self.unpack('string16')\n\t\t\t\tif mtype2 == 5:\n\t\t\t\t\tt = {}\n\t\t\t\t\tt[\"id\"] = self.unpack('short')\n\t\t\t\t\tt[\"count\"] = self.unpack('byte')\n\t\t\t\t\tt[\"damage\"] = self.unpack('short')\n\t\t\t\tif mtype2 == 6:\n\t\t\t\t\tt = []\n\t\t\t\t\tfor i in range(3):\n\t\t\t\t\t\ts = self.unpack('int')\n\t\t\t\t\t\tt.append(s)\n\t\t\t\tt = (mtype, t)\n\t\t\t\to.append(t)\n\t\t\t\tmtype = self.unpack('byte')\n\t\t\treturn o",
"def get_version_key(self, version):\n if self._generic_only:\n return GENERIC_VERSION\n else:\n self.check_version_exists(version)\n return version",
"def update_interaction_model_slot_type_version_v1(self, slot_type_id, version, slot_type_update, **kwargs):\n # type: (str, str, SlotTypeUpdate_ae01835f, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_interaction_model_slot_type_version_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'slot_type_id' is set\n if ('slot_type_id' not in params) or (params['slot_type_id'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'version' is set\n if ('version' not in params) or (params['version'] is None):\n raise ValueError(\n \"Missing the required parameter `version` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'slot_type_update' is set\n if ('slot_type_update' not in params) or (params['slot_type_update'] is None):\n raise ValueError(\n \"Missing the required parameter `slot_type_update` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/api/custom/interactionModel/slotTypes/{slotTypeId}/versions/{version}/update'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'slot_type_id' in params:\n path_params['slotTypeId'] = params['slot_type_id']\n if 'version' in params:\n path_params['version'] = params['version']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'slot_type_update' in params:\n body_params = params['slot_type_update']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that version is successfully updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"There is no slot type defined for the slotTypeId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def list_data_version_and_types(self):\n\n return self.dataset_registry.list_data_version_and_types()",
"def getData(self):\n return struct.unpack(\"!Q\",self.data)[0]",
"def getData(self):\n return struct.unpack(\"!Q\",self.data)[0]",
"def get_item(self, key):\n search_slot = self.count_hash(key, len(self.slots))\n\n if self.slots[search_slot] == key:\n data = self.data[search_slot]\n elif isinstance(self.slots[search_slot], tuple):\n index_tuple = (self.slots[search_slot].index(key))\n data = (self.data[search_slot][index_tuple])\n else:\n data = None\n\n return data",
"def get(self, uid: Union[UUID, str], version: int) -> GemTable:\n path = self._get_path(uid) + \"/versions/{}\".format(version)\n data = self.session.get_resource(path)\n return self.build(data)",
"def get_data_type(self, idx):\n return(self.data[idx].dtype)",
"def value(self):\n if self.partner is not None:\n # outputslot-inputsslot, inputslot-inputslot and outputslot-outputslot case\n temp = self[:].wait()\n elif self._value is None:\n # outputslot case\n temp = self[:].wait()\n else:\n # _value case\n return self._value\n if isinstance(temp, numpy.ndarray) and temp.shape != (1,):\n return temp\n else:\n try:\n return temp[0]\n except IndexError:\n self.logger.warn(\"FIXME: Slot.value for slot {} is {},\"\n \" which should be wrapped in an ndarray.\".format(\n self.name, temp))\n return temp",
"def vol_from_api_data(api_data):\n vol = [x['content'] for x in api_data['varFields']\n if x['fieldTag'] == 'v']\n return vol[0] if vol else None",
"def type_version_arn(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"type_version_arn\")",
"def _get_data(data_type, table, force):\n if force or data_type not in _cache:\n _cache[data_type] =read_table(table)\n return _cache[data_type]",
"def get_frame_slot_value(self, slot):\n # FrameObject is a dictionary of slot names and values.\n [slotName, value] = self.pgdb.sendPgdbFnCall('get-frame-slot-value', self.frameid, Symbol(slot))\n if not slotName:\n raise PythonCycError(\"Slot \"+slot+\" does not exist for frame \"+self.frameid+\" from organism (orgid) \"+self.pgdb._orgid)\n # Modify slot name to allow Python's syntax (e.g., '_' instead of '-').\n self.__dict__[convertLispIdtoPythonId(slotName)] = value\n return self",
"async def get(self, kind=None):\n if kind is None:\n kind = self.data_type\n\n data = await self.read()\n if kind == DataType.TEXT:\n return data.decode()\n elif kind == DataType.BINARY:\n return data"
] | [
"0.61960006",
"0.57121027",
"0.56872183",
"0.5595791",
"0.54473484",
"0.54208326",
"0.5415714",
"0.540754",
"0.53402525",
"0.5313842",
"0.52186906",
"0.5184387",
"0.51615036",
"0.51375926",
"0.51199",
"0.5100999",
"0.5041112",
"0.5034288",
"0.49926922",
"0.49520558",
"0.49520558",
"0.4927066",
"0.48887205",
"0.48806825",
"0.4872408",
"0.48642343",
"0.48594108",
"0.48445746",
"0.48257253",
"0.48056185"
] | 0.675903 | 0 |
Get status for given importId. | def get_import_status_v1(self, import_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, ImportResponse_364fa39f]
operation_name = "get_import_status_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'import_id' is set
if ('import_id' not in params) or (params['import_id'] is None):
raise ValueError(
"Missing the required parameter `import_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/imports/{importId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'import_id' in params:
path_params['importId'] = params['import_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.import_response.ImportResponse", status_code=200, message="OK."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.import_response.ImportResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def GetImportStatus(self, table_name, import_id):\n conn = self._Connect()\n result = conn.Call(\n dict(method='bigquery.imports.get',\n parents=[('tables', table_name)],\n collection='imports',\n operation=bq.REST.GET,\n resource_name=import_id,\n rpc_param_map=[('resource_name', 'import_id')]))\n return result",
"def export_status(self, file_id):\n response = self._client.get('workbenches/export/%(file_id)s/status',\n path_params={'file_id': file_id})\n return loads(response.text).get('status')",
"def get_status_by_id(cls, request, id):\n return request.dbsession.query(cls).get(id).status",
"def get_import_status(self):\n return AsyncResult(self.import_task_id).state",
"def get_status(id):\n task = run_ctx_request.AsyncResult(id)\n if task.state == states.PENDING:\n abort(404)\n if task.state == states.RECEIVED or task.state == states.STARTED:\n return '', 202, {'Location': url_for('api.get_status', id=id)}\n return task.info",
"async def get_task_status(task_id: TaskId):",
"def get_status_of_id(sku_id):\n if not sku_id:\n return None\n\n status_query = list(sku_database.find({\"SKU_unit\": int(sku_id)}, {'_id': 0, 'Status': 1}))\n status = status_query[0][\"Status\"]\n return status",
"def status_by_package_id(self, package_id):\n return self._delivery_service.package_status(int(package_id))",
"def get_status(job_id):\n job = fetch_data.AsyncResult(job_id, app=app)\n return jsonify({'job_id': job_id, 'status': job.status})",
"def get_status(self, job_id):\n\n result = self.redis.get('job_status:' + str(job_id))\n return pickle.loads(result) if result else None",
"def get_status(self, scenario_id):\n table = self.get_execute_table()\n try:\n return table.loc[int(scenario_id), \"status\"]\n except KeyError:\n raise Exception(f\"Scenario not found in execute list, id = {scenario_id}\")",
"def sis_import_status():\n # Get status of last SIS imports\n path = 'v1/accounts/{account_id}/sis_imports'\n url = config.Canvas_base_api_url_write + path.format(account_id=config.Canvas_account_id)\n headers = {'Authorization': 'Bearer {token}'.format(token=config.CanvasSISImportToken)}\n r = requests.get(url, headers=headers)\n rJson = r.json()\n print(rJson['sis_imports'][0])\n return print('Thats It')",
"def get_volume_status(self, volume_id):\n r = self.get_volume_details(volume_id)\n return r['status'], None",
"def status(self, id):",
"def get_dataimport_upload_status(\n client: discovery.Resource,\n dataimport_ref: DataImportReference) -> UploadStatus:\n request = client.management().uploads().list(\n accountId=dataimport_ref.account_id,\n webPropertyId=dataimport_ref.property_id,\n customDataSourceId=dataimport_ref.dataset_id)\n response = request.execute()\n if response['items']:\n # Considers an upload as completed when the list of items is not empty.\n return UploadStatus.COMPLETED\n return UploadStatus.PENDING",
"def get_task_status(id):\n # obtain the task and validate it\n global background_tasks\n rv = background_tasks.get(id)\n if rv is None:\n return not_found(None)\n\n # if the task object is a Thread object that means that the task is still\n # running. In this case return the 202 status message again.\n if isinstance(rv, Thread):\n return jsonify({}), 202, {'Location': url_for('get_task_status', id=id)}\n\n # If the task object is not a Thread then it is assumed to be the response\n # of the finished task, so that is the response that is returned.\n # If the application is configured to auto-delete task status resources once\n # the task is done then the deletion happens now, if not the client is\n # expected to send a delete request.\n if app.config['AUTO_DELETE_BG_TASKS']:\n del background_tasks[id]\n return rv",
"def request_status(job_id):\n status = _database_operations.get_status(job_id, Session())\n if status is None:\n flask.abort(404)\n else:\n return json.dumps({\n 'status': status.status,\n 'finished': status.finished\n })",
"def get_status(self, run_id):\n return self.client._perform_json(\n \"GET\", \"/projects/%s/runnables/%s/state/%s\" % (self.project_key, self.runnable_type, run_id))",
"def get_saved_export_task_status(export_instance_id):\n download_data = _get_saved_export_download_data(export_instance_id)\n return get_task_status(download_data.task)",
"def retrieve_task(self, task_id):\n r = requests.get('/'.join([self.base_url, self.ENDPOINT_TASK_STATUS,\n str(task_id)]))\n return r.json()",
"def id_status(self):\n return self._id_status",
"def _get_image_status(self, image_id):\n image_status = None\n image = self._get_nova_client().images.get(image_id)\n\n if image is not None:\n image_status = image.status\n\n return image_status",
"def status(self, scanid=None):\n params = {}\n if scanid is not None:\n params['scanId'] = scanid\n return six.next(six.itervalues(self.zap._request(self.zap.base + 'spider/view/status/', params)))",
"async def get_status(self, sms_id: int) -> SmsStatus:\n raise NotImplementedError",
"def getStatus(self, rule_id, correlation_search, existing_statuses, session_key, force_refresh=False):\n\n # Determine if the correlation search has an existing status in incident review\n if rule_id in existing_statuses:\n existing_status_entry = existing_statuses[rule_id]\n logger.debug(\"Found existing status (%s) for %s\", existing_status_entry.status, rule_id)\n else:\n existing_status_entry = None\n\n # Return the status if it is not blank\n if existing_status_entry is not None and existing_status_entry.status and len(existing_status_entry.status) > 0:\n logger.debug(\"Returning status from: existing entry, status=%s, rule_id=%s\", existing_status_entry.status, rule_id)\n return existing_status_entry.status\n\n # If a status was not found in the incident review then use the default for the correlation search\n if force_refresh:\n self.refreshCorrelationSearches(session_key)\n status = self.correlation_search_info.get(correlation_search, {}).get('default_status')\n\n if status is not None:\n logger.debug(\"Returning status from: correlation search default, status=%s, rule_id=%s\", status, rule_id)\n return status\n else:\n logger.debug(\"Could not find correlation search default status for search '%s', rule_id=%s\", correlation_search, rule_id)\n\n # Use the default status if we could not get a status\n status = self.DEFAULT_STATUS\n\n if status is not None:\n logger.debug(\"Returning status from: system default, status=%s, rule_id=%s\", status, rule_id)\n return status\n\n # If we were unable to find a status, then return the default\n logger.debug(\"Returning status from: module default, status=%s, rule_id=%s\", self.DEFAULT_NOTABLE_EVENT_STATUS, rule_id)\n return self.DEFAULT_NOTABLE_EVENT_STATUS",
"def get_upload_status(self, upload_id: str, token: str) -> Upload:\n data, _, _ = self.json('get', f'/{upload_id}', token)\n return self._parse_upload_status(data)",
"def check_status(self, message_id):\n\n values = {'token': self._token, 'reference': message_id}\n return self._request(self.CHECK_STATUS_URL, values)",
"def job_status(self, job_id):\n\n response = self.batch_client.describe_jobs(jobs=[job_id])\n return response[\"jobs\"][0][\"status\"]",
"def get_task_status(task_id):\r\n mock_request = Mock()\r\n mock_request.REQUEST = {'task_id': task_id}\r\n response = instructor_task_status(mock_request)\r\n status = json.loads(response.content)\r\n return status",
"async def fetch_account_status(account_id):\n res_object = requests.get(_ACCOUNTS_URL.format(account_id=account_id))\n return res_object.json() if res_object.status_code == 200 else {}"
] | [
"0.7933597",
"0.68047285",
"0.6748428",
"0.64408904",
"0.6373497",
"0.6065455",
"0.60640645",
"0.60167086",
"0.5936407",
"0.5853885",
"0.57882464",
"0.57276386",
"0.5698958",
"0.56675047",
"0.5657032",
"0.56455195",
"0.560577",
"0.5524094",
"0.55119205",
"0.5497134",
"0.5496376",
"0.5489353",
"0.54566884",
"0.5439388",
"0.5423156",
"0.54072493",
"0.53958803",
"0.5393135",
"0.53787863",
"0.5366506"
] | 0.7191057 | 1 |
Creates a new skill for given vendorId. | def create_skill_for_vendor_v1(self, create_skill_request, **kwargs):
# type: (CreateSkillRequest_92e74e84, **Any) -> Union[ApiResponse, object, CreateSkillResponse_2bad1094, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "create_skill_for_vendor_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'create_skill_request' is set
if ('create_skill_request' not in params) or (params['create_skill_request'] is None):
raise ValueError(
"Missing the required parameter `create_skill_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_skill_request' in params:
body_params = params['create_skill_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.create_skill_response.CreateSkillResponse", status_code=202, message="Accepted; Returns a URL to track the status in 'Location' header."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.create_skill_response.CreateSkillResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list_skills_for_vendor_v1(self, vendor_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, ListSkillResponse_527462d0, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"list_skills_for_vendor_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'vendor_id' is set\n if ('vendor_id' not in params) or (params['vendor_id'] is None):\n raise ValueError(\n \"Missing the required parameter `vendor_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n if 'vendor_id' in params:\n query_params.append(('vendorId', params['vendor_id']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'skill_id' in params:\n query_params.append(('skillId', params['skill_id']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.list_skill_response.ListSkillResponse\", status_code=200, message=\"Returns list of skills for the vendor.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.list_skill_response.ListSkillResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create(self):\n # type: () -> AbstractSkill\n raise NotImplementedError",
"def addSkill(self, skillName, maxLevel, creditStart, creditIncrement):\r\n self.skills[skillName] = SkillObject(skillName, maxLevel, creditStart, creditIncrement)\r\n self.orderedSkills.append(skillName)",
"def addSkill(skill, db, **kwargs):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if skill_data:\n return colored(\"ERROR: Skill {S} is already in the skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n db.execute(\n 'INSERT INTO mystatus (skill, power, points)'\n 'VALUES (?, ?, ?)', (str(skill), str(kwargs['power']), \"0\"))\n db.commit()\n return colored(\"Add new skill: \" + str(skill), 'cyan')",
"def addSkill(self, newskill):\n self.skills.append( newskill )",
"def addSkillIntoPlayerDatabase(self, userid, name, level = 0):\r\n if not isinstance(userid, int):\r\n userid = self.getUserIdFromSteamId(userid)\r\n self.execute(\"INSERT OR IGNORE INTO Skill (UserID, name, level) VALUES (?,?,?)\", userid, name, level)\r\n return self.cursor.lastrowid",
"def __init__(__self__, *,\n alexa_skill_id: pulumi.Input[str],\n is_enabled: pulumi.Input[bool]):\n pulumi.set(__self__, \"alexa_skill_id\", alexa_skill_id)\n pulumi.set(__self__, \"is_enabled\", is_enabled)",
"def associate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"associate_isp_with_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def skill(ctx: Context, public_id: PublicId):\n _eject_item(ctx, \"skill\", public_id)",
"def create_skill(skillname, skillpath, category):\n if Skill.query.filter_by(path=skillpath).first():\n raise AttributeError\n new_skill = Skill(name=skillname, path=skillpath)\n if not category:\n new_skill.root = True\n db.session.add(new_skill)\n db.session.commit()\n database_controller.create_hierarchy(category, skillpath)",
"def create_player(player: Player) -> None:\n with engine.connect() as conn:\n\n conn.execute(\n player_table.insert().values(\n steamid=player.steamid,\n level=player.level,\n xp=player.xp,\n credits=player.credits,\n )\n )\n\n skills = list(player.skills)\n result = conn.execute(\n skill_table.insert().values([\n {\n 'key': skill.key,\n 'level': skill.level,\n 'steamid': player.steamid,\n }\n for skill in skills\n ])\n )\n\n for id, skill in zip(result.inserted_primary_key, skills):\n skill._db_id = id",
"def add_skills_to_profile():\n # get specific objects\n profile = storage.get(\"Profile\", profile_id)\n skills = storage.get(\"Skills\", skills_id)\n if profile is not None and skills is not None:\n # check every skill in profile\n for profile_skill in profile.skills:\n # if the given skill is already linked to profile, return\n if profile_skill.id == skills.id:\n return jsonify(skills.to_dict()), 200\n # if skill is not in profile, append skill and save\n profile.skills.append(skills)\n profile.save()\n return jsonify(skills.to_dict()), 201\n\n # if id not in database, abort\n abort(404)",
"def add_skill(skill_list, skill): #inputs the skill dictionary and skill\r\n\tif skill==\"Gun Combat\":\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in guns:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\t\telse:\r\n\t\t\t\t\tskill=stellagama.random_choice(guns)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(guns)\r\n\telif skill in [\"Blade Combat\", \"Blade Cbt\"]:\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in melee:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\t\telse:\r\n\t\t\t\t\tskill=stellagama.random_choice(melee)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(melee)\r\n\telif skill==\"Vehicle\":\r\n\t\tif stellagama.dice(1,6)>=3:\r\n\t\t\tfor item in vehicles:\r\n\t\t\t\tif item in skill_list:\r\n\t\t\t\t\tskill=item\r\n\t\t\telse:\r\n\t\t\t\tskill=stellagama.random_choice(vehicles)\r\n\t\telse:\r\n\t\t\tskill=stellagama.random_choice(vehicles)\r\n\tif skill in skill_list:\r\n\t\tskill_list[skill] += 1\r\n\telif skill not in skill_list:\r\n\t\tskill_list[skill] = 1\r\n\treturn skill_list #outputs the skill dictionary\r",
"def create_isp_for_vendor_v1(self, create_in_skill_product_request, **kwargs):\n # type: (CreateInSkillProductRequest_816cf44b, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ProductResponse_b388eec4, BadRequestError_f854b05]\n operation_name = \"create_isp_for_vendor_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'create_in_skill_product_request' is set\n if ('create_in_skill_product_request' not in params) or (params['create_in_skill_product_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_in_skill_product_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_in_skill_product_request' in params:\n body_params = params['create_in_skill_product_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.isp.product_response.ProductResponse\", status_code=201, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.isp.product_response.ProductResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def submit_skill_for_certification_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"submit_skill_for_certification_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/submit'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'submit_skill_for_certification_request' in params:\n body_params = params['submit_skill_for_certification_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Success. There is no content but returns Location in the header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def associate_catalog_with_skill_v0(self, skill_id, catalog_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, BadRequestError_a8ac8b44, Error_d660d58]\n operation_name = \"associate_catalog_with_skill_v0\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'catalog_id' is set\n if ('catalog_id' not in params) or (params['catalog_id'] is None):\n raise ValueError(\n \"Missing the required parameter `catalog_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v0/skills/{skillId}/catalogs/{catalogId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'catalog_id' in params:\n path_params['catalogId'] = params['catalog_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Successful operation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v0.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def _set_skill(caller, _, **kwargs):\n pool = _skill_pool(caller, kwargs.get(\"skill\"))\n caller.db.d1_skills[kwargs.get(\"skill\")][\"rank\"] += 1\n caller.ndb.pregen[\"skills\"] = pool\n\n return \"node_skills\"",
"def create_deployment(self, ApiId: str, Description: str = None, StageName: str = None) -> Dict:\n pass",
"def create_intent(intent_name):\n try:\n response=client.get_intent(\n name=intent_name,\n version=\"$LATEST\"\n )\n print \"There is a %s intent in your account, please consider delete it or using another name\" %(intent_name)\n return\n except:\n pass\n\n response=client.put_intent(\n name=intent_name,\n description='the demo intent',\n sampleUtterances=[\n 'Can I book a hotel',\n ],\n confirmationPrompt={\n 'messages': [\n {\n 'contentType': 'PlainText',\n 'content': 'Your hotel booking is ready, do you want to place an order?'\n },\n ],\n 'maxAttempts': 2,\n },\n rejectionStatement={\n 'messages': [\n {\n 'contentType': 'PlainText' ,\n 'content': 'Ok. I will discard the hotel booking information'\n },\n ],\n },\n conclusionStatement={\n 'messages': [\n {\n 'contentType': 'PlainText',\n 'content': 'Your hotel booking has been confirmed'\n },\n ],\n },\n fulfillmentActivity={\n 'type': 'ReturnIntent'\n }\n )\n print \"Intent %s created successfully\" %(intent_name)\n return",
"def new_skill_interaction(self, skill):\n self.skill_interact[skill] = True",
"def target_create(obj, product_name, slo_id, sli_name, target_from, target_to, target_file):\n client = get_client(obj)\n\n product = client.product_list(name=product_name)\n if not product:\n fatal_error('Product {} does not exist'.format(product_name))\n\n product = product[0]\n\n slo = client.slo_list(product, id=slo_id)\n if not slo:\n fatal_error('SLO {} does not exist'.format(slo_id))\n\n slo = slo[0]\n\n product = client.product_list(name=slo['product_name'])[0]\n\n sli = client.sli_list(product=product, name=sli_name)\n if not sli or not sli_name:\n fatal_error('SLI {} does not exist'.format(sli_name))\n sli = sli[0]\n\n with Action(\n 'Creating Targets for SLO: {} for product: {}'.format(slo['title'], slo['product_name']), nl=True) as act:\n if target_file:\n target = json.load(target_file)\n else:\n target = {'sli_uri': sli['uri'], 'from': target_from, 'to': target_to}\n\n validate_target(target, act)\n\n if not act.errors:\n t = client.target_create(slo, target['sli_uri'], target_from=target.get('from'), target_to=target.get('to'))\n\n print(json.dumps(t, indent=4))",
"def sli_create(obj, product_name, sli_file):\n client = get_client(obj)\n\n product = client.product_list(name=product_name)\n if not product:\n fatal_error('Product {} does not exist'.format(product_name))\n\n product = product[0]\n\n with Action('Creating SLI for product: {}'.format(product_name), nl=True) as act:\n sli = json.load(sli_file)\n\n validate_sli(obj, sli, act)\n\n if not act.errors:\n res = client.sli_create(product, sli['name'], sli['unit'], sli['source'])\n print(json.dumps(res, indent=4))",
"def delete_skill_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_skill_created(self):\n\t\tself.skill.save()\n\t\tskill_instance = Skill.objects.get(pk=1)\n\t\tself.assertEqual(\n\t\t\tskill_instance.user,\n\t\t\tself.skill.user,\n\t\t\t'User don\\'t match.'\n\t\t)\n\t\tself.assertEqual(\n\t\t\tskill_instance.tag,\n\t\t\tself.tag,\n\t\t\t'Skill tag\\'s don\\'t match.'\n\t\t)",
"def create_app(StackId=None, Shortname=None, Name=None, Description=None, DataSources=None, Type=None, AppSource=None, Domains=None, EnableSsl=None, SslConfiguration=None, Attributes=None, Environment=None):\n pass",
"def vendor_id(self, vendor_id):\n\n self._vendor_id = vendor_id",
"def create_provider(\n provider_id:UUID = Form(...),\n name:str = Form(...),\n qualification:str = Form(...),\n speciality:str = Form(...),\n phone:str = Form(...),\n department:Optional[str] = Form(\"N/A\"),\n organization:str = Form(...),\n location:Optional[str] = Form(\"N/A\"),\n address:str = Form(...),\n active:bool = Form(...)\n ):\n\n post_data = {\n \"name\": name,\n \"qualification\": qualification,\n \"speciality\": speciality,\n \"phone\": phone,\n \"department\": department,\n \"organization\": organization,\n \"location\": location,\n \"address\": address,\n \"active\": active\n }\n provider_data = open_for_reading()\n if str(provider_id) in provider_data.keys():\n response = {\"message\": \"ID already exists\"}\n else:\n provider_data[str(provider_id)] = post_data\n open_for_writing(data=provider_data)\n response = {\"message\": \"provider created\"}\n\n return response",
"def set_skill_enablement_v1(self, skill_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"set_skill_enablement_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/stages/{stage}/enablement'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"No Content; Confirms that enablement is successfully created/updated.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def rollback_skill_v1(self, skill_id, create_rollback_request, **kwargs):\n # type: (str, CreateRollbackRequest_e7747a32, **Any) -> Union[ApiResponse, object, CreateRollbackResponse_5a2e8250, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"rollback_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'create_rollback_request' is set\n if ('create_rollback_request' not in params) or (params['create_rollback_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_rollback_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/rollbacks'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_rollback_request' in params:\n body_params = params['create_rollback_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.create_rollback_response.CreateRollbackResponse\", status_code=201, message=\"Rollback request created; Returns the generated identifier to track the rollback request and returns a URL to track the status in Location header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.create_rollback_response.CreateRollbackResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def vendorid(self, vendorid):\n\n self._vendorid = vendorid"
] | [
"0.56765413",
"0.566364",
"0.5663285",
"0.5602312",
"0.55841464",
"0.5244242",
"0.5207224",
"0.51427853",
"0.51056373",
"0.5064332",
"0.5049388",
"0.5019362",
"0.49746248",
"0.49152339",
"0.48530075",
"0.47677076",
"0.47220677",
"0.46827847",
"0.46745673",
"0.46149892",
"0.46112964",
"0.4589716",
"0.45570228",
"0.4516455",
"0.44721264",
"0.447189",
"0.447013",
"0.44686618",
"0.4460461",
"0.44456333"
] | 0.680146 | 0 |
GetResourceSchema API provides schema for skill related resources. The schema returned by this API will be specific to vendor because it considers public beta features allowed for the vendor. | def get_resource_schema_v1(self, resource, vendor_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetResourceSchemaResponse_9df87651, BadRequestError_f854b05]
operation_name = "get_resource_schema_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'resource' is set
if ('resource' not in params) or (params['resource'] is None):
raise ValueError(
"Missing the required parameter `resource` when calling `" + operation_name + "`")
# verify the required parameter 'vendor_id' is set
if ('vendor_id' not in params) or (params['vendor_id'] is None):
raise ValueError(
"Missing the required parameter `vendor_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/resourceSchema/{resource}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'resource' in params:
path_params['resource'] = params['resource']
query_params = [] # type: List
if 'vendor_id' in params:
query_params.append(('vendorId', params['vendor_id']))
if 'operation' in params:
query_params.append(('operation', params['operation']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.resource_schema.get_resource_schema_response.GetResourceSchemaResponse", status_code=200, message="Returns a S3 presigned URL to location of schema"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Invalid request"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="Unauthorized"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=403, message="Forbidden"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Too Many Requests"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.resource_schema.get_resource_schema_response.GetResourceSchemaResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_schema():\n if not os.path.isfile(_schema_file):\n create_schema()\n with open(_schema_file, 'r') as fd:\n out = decode_json(fd)\n return out",
"def get_schema(self):\n response = self.client.get(self._get_collection_url('schema'))\n\n return response.get('schema', {})",
"def schema(self) -> 'outputs.TableSchemaResponse':\n return pulumi.get(self, \"schema\")",
"def schema(self):\n return _parse_schema_resource(self._properties.get(\"schema\", {}))",
"def get_schema(self):\r\n return self.__schema",
"def get_schema(cls):\n return cls.schema()",
"def sample_schema(self):\n if 'sample' not in self._schemas:\n logging.debug(f\"{self.id} - no schema? {self._schemas}\")\n return None\n return self._schemas['sample']",
"def skills():\n with app.app_context():\n results = Skill.query.all()\n return SkillsResponse(skills=results).json(), 200",
"def skills(self):\n if \"skills\" in self._prop_dict:\n return self._prop_dict[\"skills\"]\n else:\n return None",
"def get_schema(self) -> dict:\n return schemas.get_object_schema(self.schema)",
"def _get_schema(name):\n global SCHEMA\n\n loaded_schema = SCHEMA.get(name)\n if not loaded_schema:\n filename = \"{}/{}.json\".format(_get_directory(), name)\n if os.path.exists(filename):\n SCHEMA[name] = json.load(open(filename, 'r'))\n\n return SCHEMA.get(name)",
"def skill(self):\n return self._get(\"skill\")",
"def get_model_schema(*, name: str) -> typing.Optional[types.Schema]:\n model = get_model(name=name)\n if model is None:\n return None\n return model._schema # pylint: disable=protected-access",
"async def get_schema(\n self,\n issuer_did: str,\n name: str,\n version: str) -> str: # issuer, verifier, prover\n\n req_json = await ledger.build_get_schema_request(\n self.did,\n issuer_did,\n json.dumps({'name': name, 'version': version}))\n resp_json = await ledger.submit_request(self.pool.handle, req_json)\n resp = json.loads(resp_json)\n resp['result']['data']['keys'] = resp['result']['data'].pop('attr_names')\n return json.dumps(resp['result'])",
"def get_schema(schema): # noqa: E501\n return 'do some magic!'",
"async def get_schema(request: Request, namespace: str, project: str):\n # endpoint to schema.databio.org/...\n # like pipelines/ProseqPEP.yaml\n\n try:\n schema = eido.read_schema(\n f\"https://schema.databio.org/{namespace}/{project}.yaml\"\n )[0]\n except IndexError:\n raise HTTPException(status_code=404, detail=\"Schema not found\")\n\n return schema",
"def endpoint_skills():\n q = \"\"\"\n SELECT ?localName\n WHERE { ?entity rdfs:subClassOf* cogrobtut:Skill .\n\t bind( strafter(str(?entity), \"#\") as ?localName) .\n }\n \"\"\"\n res = utils.kb.query(q, initNs=utils.namespaces)\n res_rows = [x for x in res]\n individuals=[]\n for row in res_rows:\n for elem in row:\n individuals.append(elem)\n return jsonify({\"result\" : individuals})",
"def get_schema(self) -> dict:",
"def schemas(self):\n if not self._schemas:\n self._schemas = get_schema(self.attributes.workspace.namespace, self.attributes.workspace.name)\n return self._schemas",
"def list_schemas(jwt_payload: dict):\n DJConnector.set_datajoint_config(jwt_payload)\n\n # Attempt to connect return true if successful, false is failed\n return [row[0] for row in dj.conn().query(\"\"\"\n SELECT SCHEMA_NAME FROM information_schema.schemata\n WHERE SCHEMA_NAME != \"information_schema\"\n ORDER BY SCHEMA_NAME\n \"\"\")]",
"def _get_schema(self):\n self._pick()\n return Schema()",
"def schema(self):\n return self._schema",
"def get_schema(): # noqa: WPS440\n return config.DEFAULT_SCHEMA",
"def get_schema(self, engine_name):\n endpoint = \"engines/{}/schema\".format(engine_name)\n return self.swiftype_session.request('get', endpoint)",
"def getTableSchema(self, lsstLevel, dbName, tableName):\n return self._doRequest(self.httpClient.getTableSchema, lsstLevel, dbName, tableName)",
"def get_skill(skillpath):\n return Skill.query.filter_by(path=skillpath).first()",
"def get_json(schema):\n\n data = request.get_json(force=True, silent=True, cache=False)\n\n message = schema.validate(data)\n\n if message:\n raise BadRequest(message)\n\n return data",
"def schema(self) -> str:\n return parse_schema(self._spec[\"schema\"])",
"def _Dynamic_GetSchema(self, req, schema, request_id=None):\n # This is not used, but it is required for the method signature.\n del request_id\n\n app_str = req.app()\n self.__ValidateAppId(app_str)\n schema.set_more_results(False)",
"def get_schema(self, schema_versions_info):\n schema = None\n version = api_version_request.APIVersionRequest(VOLUME_MICROVERSION)\n for items in schema_versions_info:\n min_version = api_version_request.APIVersionRequest(items['min'])\n max_version = api_version_request.APIVersionRequest(items['max'])\n # This is case where COMPUTE_MICROVERSION is None, which means\n # request without microversion So select base v2.1 schema.\n if version.is_null() and items['min'] is None:\n schema = items['schema']\n break\n # else select appropriate schema as per COMPUTE_MICROVERSION\n elif version.matches(min_version, max_version):\n schema = items['schema']\n break\n if schema is None:\n raise exceptions.JSONSchemaNotFound(\n version=version.get_string(),\n schema_versions_info=schema_versions_info)\n return schema"
] | [
"0.59521794",
"0.5908274",
"0.57825756",
"0.5744435",
"0.5438769",
"0.54080755",
"0.54057866",
"0.53965545",
"0.5362591",
"0.5359217",
"0.53531814",
"0.52605706",
"0.52461493",
"0.5244036",
"0.5198851",
"0.5177402",
"0.5172437",
"0.50903076",
"0.5087525",
"0.50371695",
"0.50369686",
"0.5019268",
"0.50159866",
"0.5015936",
"0.49752593",
"0.49638358",
"0.4962815",
"0.49593103",
"0.4958659",
"0.49574515"
] | 0.6104081 | 0 |
Generates hosted skill repository credentials to access the hosted skill repository. | def generate_credentials_for_alexa_hosted_skill_v1(self, skill_id, hosted_skill_repository_credentials_request, **kwargs):
# type: (str, HostedSkillRepositoryCredentialsRequest_79a1c791, **Any) -> Union[ApiResponse, object, HostedSkillRepositoryCredentialsList_d39d5fdf, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "generate_credentials_for_alexa_hosted_skill_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'hosted_skill_repository_credentials_request' is set
if ('hosted_skill_repository_credentials_request' not in params) or (params['hosted_skill_repository_credentials_request'] is None):
raise ValueError(
"Missing the required parameter `hosted_skill_repository_credentials_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/alexaHosted/repository/credentials/generate'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'hosted_skill_repository_credentials_request' in params:
body_params = params['hosted_skill_repository_credentials_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.alexa_hosted.hosted_skill_repository_credentials_list.HostedSkillRepositoryCredentialsList", status_code=200, message="Response contains the hosted skill repository credentials"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error e.g. Authorization Url is invalid"))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.alexa_hosted.hosted_skill_repository_credentials_list.HostedSkillRepositoryCredentialsList")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_credentials(self):\r\n \r\n try:\r\n import argparse\r\n #flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\r\n if self.noauth == True:\r\n flags = tools.argparser.parse_args(args=['--noauth_local_webserver'])\r\n else:\r\n flags = tools.argparser.parse_args(args=[])\r\n except ImportError:\r\n flags = None \r\n \r\n home_dir = os.path.expanduser('~')\r\n credential_dir = os.path.join(home_dir, '.credentials')\r\n if not os.path.exists(credential_dir):\r\n os.makedirs(credential_dir)\r\n credential_path = os.path.join(credential_dir,'sheets.googleapis.com-allstarbot.json')\r\n\r\n store = Storage(credential_path)\r\n credentials = store.get()\r\n if not credentials or credentials.invalid:\r\n secret = Path(self.CLIENT_SECRET_FILE)\r\n if secret.exists():\r\n flow = client.flow_from_clientsecrets(self.CLIENT_SECRET_FILE, self.SCOPES)\r\n else:\r\n print(\"client_secret.json not found, using env vars\")\r\n if not os.environ.get('client_id') or not os.environ.get('client_secret'): \r\n print(\"env vars client_id and client_secret not found. canceling\")\r\n raise Exception(\"client secret error\")\r\n else:\r\n flow = OAuth2WebServerFlow(\r\n os.environ.get('client_id'),\r\n os.environ.get('client_secret'),\r\n self.SCOPES) \r\n \r\n flow.params['access_type'] = 'offline'\r\n flow.user_agent = self.APPLICATION_NAME\r\n if flags:\r\n credentials = tools.run_flow(flow, store, flags)\r\n else: # Needed only for compatibility with Python 2.6\r\n credentials = tools.run(flow, store)\r\n print('Storing credentials to ' + credential_path)\r\n return credentials",
"def get_credentials(self):\n home_dir = os.path.expanduser(\"~\")\n credential_dir = os.path.join(home_dir, \".credentials\")\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir, \"autoto.json\")\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n credentials = tools.run_flow(flow, store, self.auth_flags)\n print(\"Storing credentials to \" + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'sally.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'reseller-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\r\n home_dir = os.path.expanduser('~')\r\n credential_dir = os.path.join(home_dir, '.credentials')\r\n if not os.path.exists(credential_dir):\r\n os.makedirs(credential_dir)\r\n credential_path = os.path.join(credential_dir,\r\n 'bis-python-quickstart.json')\r\n\r\n store = oauth2client.file.Storage(credential_path)\r\n credentials = store.get()\r\n if not credentials or credentials.invalid:\r\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\r\n flow.user_agent = APPLICATION_NAME\r\n if flags:\r\n credentials = tools.run_flow(flow, store, flags)\r\n else: # Needed only for compatibility with Python 2.6\r\n credentials = tools.run(flow, store)\r\n print('Storing credentials to ' + credential_path)\r\n return credentials",
"def get_credentials():\n # normal, sane way of doing this that really shouldn't be changed\n #home_dir = os.path.expanduser('~')\n #credential_dir = os.path.join(home_dir, '.credentials')\n #if not os.path.exists(credential_dir):\n # os.makedirs(credential_dir)\n #credential_path = os.path.join(credential_dir,'calendar-python-quickstart.json')\n\n # stupid hacky way that I came up with to fix an issue with running this app as root\n credential_path = os.path.join('./credentials','calendar-python-quickstart.json') \n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'grader.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n credentials = tools.run_flow(flow, store, tools.argparser.parse_args(args=[]))\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser(os.getcwd())\n credential_dir = os.path.join(home_dir, '.credentials')\n print(credential_dir)\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'credentialv_modify.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'thejam_calendar.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\r\n home_dir = os.path.expanduser('~')\r\n credential_dir = os.path.join(home_dir, '.credentials')\r\n if not os.path.exists(credential_dir):\r\n os.makedirs(credential_dir)\r\n credential_path = os.path.join(credential_dir,'drive-python-quickstart.json')\r\n\r\n store = Storage(credential_path)\r\n credentials = store.get()\r\n if not credentials or credentials.invalid:\r\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\r\n flow.user_agent = APPLICATION_NAME\r\n if flags:\r\n credentials = tools.run_flow(flow, store, flags)\r\n else: # Needed only for compatibility with Python 2.6\r\n credentials = tools.run(flow, store)\r\n print('Storing credentials to ' + credential_path)\r\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'appsactivity-python-showtime.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n print('Storing credentials to ' + credential_path)\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials(self):\r\n home_dir = os.path.expanduser('~')\r\n credential_dir = os.path.join(home_dir, '.credentials')\r\n if not os.path.exists(credential_dir):\r\n os.makedirs(credential_dir)\r\n credential_path = os.path.join(credential_dir, self.CRED_FILENAME)\r\n \r\n store = Storage(credential_path)\r\n credentials = store.get()\r\n if not credentials or credentials.invalid:\r\n flow = client.flow_from_clientsecrets(self.CLIENT_SECRET_FILE, self.SCOPES)\r\n flow.user_agent = self.APPLICATION_NAME\r\n if flags:\r\n credentials = tools.run_flow(flow, store, flags)\r\n else: # Needed only for compatibility with Python 2.6\r\n credentials = tools.run(flow, store)\r\n print('Storing credentials to ' + credential_path)\r\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(config['client secret file'], SCOPES)\n flow.user_agent = APPLICATION_NAME\n if args:\n credentials = tools.run_flow(flow, store, args)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def repository_create_hosted():\n pass",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir, 'google-photos-stats.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n credentials = tools.run_flow(flow, store, flags)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\r\n home_dir = os.path.expanduser('~')\r\n credential_dir = os.path.join(home_dir, '.credentials')\r\n if not os.path.exists(credential_dir):\r\n os.makedirs(credential_dir)\r\n credential_path = os.path.join(credential_dir,\r\n 'calendar-python-quickstart.json')\r\n\r\n store = oauth2client.file.Storage(credential_path)\r\n credentials = store.get()\r\n if not credentials or credentials.invalid:\r\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\r\n flow.user_agent = APPLICATION_NAME\r\n if flags:\r\n credentials = tools.run_flow(flow, store, flags)\r\n else: # Needed only for compatibility with Python 2.6\r\n credentials = tools.run(flow, store)\r\n print('Storing credentials to ' + credential_path)\r\n return credentials",
"def get_credentials():\n #home_dir = os.path.expanduser('~')\n home_dir = os.path.expanduser('/home/pi/')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n try:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\n except ImportError:\n flags = None\n\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'appsactivity-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(GoogleGsuiteAPI.CLIENT_SECRET_FILE, GoogleGsuiteAPI.SCOPES)\n flow.user_agent = GoogleGsuiteAPI.APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def credentials():\n\n username = os.environ.get('OS_USERNAME')\n password = os.environ.get('OS_PASSWORD')\n tenant_name = (os.environ.get('OS_TENANT_NAME') or\n os.environ.get('OS_PROJECT_NAME'))\n auth_url = os.environ.get('OS_AUTH_URL')\n\n config = configparser.RawConfigParser()\n if config.read(_CREDS_FILE):\n username = username or config.get('admin', 'user')\n password = password or config.get('admin', 'pass')\n tenant_name = tenant_name or config.get('admin', 'tenant')\n auth_url = auth_url or config.get('auth', 'uri')\n\n return {\n 'username': username,\n 'password': password,\n 'tenant_name': tenant_name,\n 'uri': auth_url\n }",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials(self):\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'homework_logger-gmail-api.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(self.CLIENT_SECRET_FILE, self.SCOPES)\n flow.user_agent = self.APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials",
"def get_credentials():\n credential_dir = os.path.realpath('.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-quickstart.json')\n\n store = oauth2client.file.Storage(credential_path) # stores the users credentials --> TODO: put in database\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n\n credentials = tools.run_flow(flow, store, flags)\n\n print('Storing credentials to ' + credential_path)\n return credentials"
] | [
"0.5910984",
"0.58889234",
"0.5878909",
"0.58545816",
"0.58484316",
"0.5845955",
"0.57923484",
"0.57289153",
"0.5717822",
"0.5663259",
"0.56557184",
"0.56421167",
"0.5642021",
"0.5642021",
"0.56393",
"0.56220835",
"0.5617574",
"0.5574237",
"0.5557065",
"0.55498415",
"0.5539461",
"0.5530603",
"0.549237",
"0.5480761",
"0.5480761",
"0.5480761",
"0.5480761",
"0.5480761",
"0.54548603",
"0.5447291"
] | 0.6119863 | 0 |
End beta test. End a beta test for a given Alexa skill. System will revoke the entitlement of each tester and send accessend notification email to them. | def end_beta_test_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "end_beta_test_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest/end'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message="Accept. Return a URL to track the resource in 'Location' header."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def trial_end(self, parameter_id, success, **kwargs):",
"def end_test(self, name, attributes):\n test = Test(name=name, attributes=attributes)\n self.current_scope = \"SUITE\"\n if self._suite_setup_failed:\n # If test failed because of failing suite setup, output log message with error severity.\n message = {\n \"message\": u\"[ERROR] Suite Setup failed!\",\n \"level\": \"FAIL\"\n }\n self.log_message(message=message)\n self.robot_service.finish_test(test=test)",
"def end_suite(self, name, attributes):\n suite = Suite(attributes=attributes)\n self.current_scope = \"SUITE\"\n\n if attributes['tests']:\n self.robot_service.finish_suite(suite=suite)\n\n if attributes[\"id\"] == FIRST_SUITE_ID:\n self.robot_service.terminate_service()\n # in case launch was created automatically, we can finish launch automatically\n if self._launch_id is None:\n # automatically close report portal launch\n self.robot_service.finish_launch(launch=suite)\n # terminating service\n self.robot_service.terminate_service()",
"def stopTest(self, test):\n self.logger.debug(\">>> Finished %s\\n\\n\" % test.id())",
"def stopTest(self, test):",
"def stopTest(self, test):\n self.complete_output()",
"def notify_qa_sign_off(self):\n if self.pr.is_merged and self.pr.base_branch == self.pr.config.mainBranch \\\n and self.pr.head_branch == self.pr.config.testBranch:\n msg = MSG_QA_SIGN_OFF.format(person=self.pr.config.personToBeNotified, pr=self.pr.link_pretty,\n dev_ops_team=self.pr.config.devOpsTeamToBeNotified,\n tech_team=self.pr.config.techLeadsToBeNotified)\n\n self.slack.postToSlack(self.pr.config.alertChannelName, msg,\n data=self.slack.getBot(self.pr.config.alertChannelName, self.merged_by))\n\n \"\"\" for bot to keep data ready for future use\"\"\"\n write_to_file_from_top(self.pr.config.releaseFreezeDetailsPath, \":clubs:\" +\n str(datetime.now(pytz.timezone('Asia/Calcutta')).strftime(\n '%B %d,%Y at %I.%M %p')) + \" with <\" + self.pr.link_pretty + \"|master> code\")\n clear_file(self.pr.config.codeFreezeDetailsPath)",
"def test_stop_with_permission(self):\n self.create_user_with_role(\n self.user.name, self.user.email, self.user.password, Role.tester)\n self.create_forktest(\"own-fork-commit\", TestPlatform.linux, regression_tests=[2])\n with self.app.test_client() as c:\n response = c.post(\n '/account/login', data=self.create_login_form_data(self.user.email, self.user.password))\n response = c.get('/test/stop_test/3')\n test = Test.query.filter(Test.id == 3).first()\n self.assertEqual(test.finished, True)",
"def end_test(self, name, attributes):\n print(f\"test ended with result : {attributes['status']} \")\n if attributes['status'] == \"FAIL\":\n CustomUtils.take_screenshot(f\"{name}.png\")",
"def api_end_game(self):\n pass",
"def stop_test(self, test_item):\n msg = messages.StopTest(test_id=test_item.identifier)\n self._request(msg)",
"def teardown_test(self):\n self.log.info('Tearing down the test case')\n self.iperf_server.stop()\n self.access_point.bridge.teardown(self.brconfigs)\n self.access_point.close()\n wputils.reset_host_interface(self.pkt_sender.interface)\n self.mon.usb('on')",
"def end(self, activity, session):\n raise PermissionDenied(\"Cette activité est fermé.\")",
"def test_finish_activity(self):\n activity = Activity.objects.first()\n\n data = {\n 'result': 'result text'\n }\n\n url, parsed = self.prepare_urls('v1:activity-finish', subdomain=self.company.subdomain, kwargs={'pk': activity.id})\n \n response = self.client.post(url, data, HTTP_HOST=parsed.netloc)\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)\n\n self.authenticate_user()\n response = self.client.post(url, data, HTTP_HOST=parsed.netloc)\n self.assertEqual(response.status_code, status.HTTP_200_OK)",
"def send_beta_role_email(action, user, email_params):\r\n if action == 'add':\r\n email_params['message'] = 'add_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n elif action == 'remove':\r\n email_params['message'] = 'remove_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n else:\r\n raise ValueError(\"Unexpected action received '{}' - expected 'add' or 'remove'\".format(action))\r\n\r\n send_mail_to_student(user.email, email_params)",
"def tearDown(self):\n self.testbed.deactivate()",
"def tearDown(self):\n self.testbed.deactivate()",
"def endCompetition(self):\n self.robot_exit = True",
"def test_terminate_agreement(self):\n pass",
"def test_revoke_inactive(self):\n self.invite.active = False\n self.invite.save()\n url = reverse(\n 'projectroles:api_invite_revoke',\n kwargs={'projectinvite': self.invite.sodar_uuid},\n )\n response = self.request_knox(url, method='POST')\n self.assertEqual(response.status_code, 400, msg=response.content)",
"def stop_test(self, request):\n request.worker.stop_test(request.message.test_id)\n\n return SuccessReply()",
"def update_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"async def stop(self, context):\n try:\n if context.author.is_mod:\n self.tournament.start = False\n Tournament.persons = 0\n bracket_url = self.tournament.create_bracket()\n print(bracket_url)\n await context.send(bracket_url)\n except Exception as error:\n print(error)",
"async def stop(self, context):\n try:\n if context.author.is_mod:\n self.tournament.start = False\n Tournament.persons = 0\n bracket_url = self.tournament.create_bracket()\n print(bracket_url)\n await context.send(bracket_url)\n except Exception as error:\n print(error)",
"def test_deactivate_and_save():\n course_run_enrollment = CourseRunEnrollmentFactory.create(\n active=True, change_status=None\n )\n program_enrollment = ProgramEnrollmentFactory.create(\n active=True, change_status=None\n )\n enrollments = [course_run_enrollment, program_enrollment]\n for enrollment in enrollments:\n enrollment.deactivate_and_save(ENROLL_CHANGE_STATUS_REFUNDED)\n enrollment.refresh_from_db()\n enrollment.active = False\n enrollment.change_status = ENROLL_CHANGE_STATUS_REFUNDED",
"def end(c: Composition) -> None:\n c.run(\"testdrive\", \"verify-data.td\")",
"def test_resend_inactive(self):\n self.invite.active = False\n self.invite.save()\n url = reverse(\n 'projectroles:api_invite_resend',\n kwargs={'projectinvite': self.invite.sodar_uuid},\n )\n response = self.request_knox(url, method='POST')\n self.assertEqual(response.status_code, 400, msg=response.content)\n self.assertEqual(len(mail.outbox), 0)",
"def gameEnd():\n result = cs411_game.gameEnd(request.form.get('Games_Game_ID'),\n\trequest.form.get('Contestant_Coontestant_ID'))\n if result == 1: return prepJSON({\"message\": \"success\"})\n else: raise InvalidUsage(result[\"message\"], 403)",
"def exit(self): \n self.teo_exchange_intent = self.teo_wallet\n self.withdraw_intent = self.euro_wallet\n\n self.register_teo_exchange(self.teo_exchange_intent)\n self.register_withdraw(self.withdraw_intent)\n\n if self.teo_wallet + self.euro_wallet == 0:\n print('Agent exited: ', self.__class__.__name__)\n self.model.schedule.remove(self)",
"def end(self, send_logout_to_apis=False, request=None):\n self.ended_at = now()\n self.save()\n\n if send_logout_to_apis and request:\n from oidc_apis.backchannel_logout import send_backchannel_logout_to_apis_in_token_scope\n\n tokens = [se.content_object for se in self.get_elements_by_model(Token)]\n for token in filter(None, tokens):\n send_backchannel_logout_to_apis_in_token_scope(token, request, sid=str(self.id))"
] | [
"0.5841196",
"0.58019316",
"0.5657902",
"0.5640518",
"0.5543084",
"0.55353415",
"0.54623264",
"0.5451301",
"0.5403376",
"0.53503865",
"0.53335947",
"0.53321385",
"0.5331289",
"0.533081",
"0.5317022",
"0.5311898",
"0.5311898",
"0.5286873",
"0.5272455",
"0.52439624",
"0.52367234",
"0.5228589",
"0.52115196",
"0.52115196",
"0.52068543",
"0.5202104",
"0.51643974",
"0.51643234",
"0.512839",
"0.5120722"
] | 0.6728911 | 0 |
Get beta test. Get beta test for a given Alexa skill. | def get_beta_test_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BetaTest_e826b162, BadRequestError_f854b05]
operation_name = "get_beta_test_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest", status_code=200, message="Success."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="Thrown if user tries to request a new simulation while the old simulation is in progress."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def create_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"create_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Success. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def end_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"end_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/end'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def beta(self):\n return self._beta",
"def beta(self):\n return self._beta",
"def getBeta(self):\n\t\treturn self.relativistic_beta",
"def _beta(self):\n return _handle_ab(self.solution, self.use_const)[1]",
"def start_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"start_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/start'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def tstat_beta(self):\n return self._tstat_beta",
"def _tstat_beta(self):\n return _handle_ab(self._tstat_all, self.use_const)[1]",
"def getBeta(self, alpha):\n return 2.0*(2.0-alpha) + -4.0*np.sqrt(1.0-alpha)",
"def bestBeta(sample,bins,N,l,u):\r\n\r\n betaGrid,df,traces=modelOnBetaGrid(sample,bins,N,l,u)\r\n minIndex=df.index[0]\r\n\r\n return betaGrid[minIndex]",
"def estimate_sample_beta(sample):\n x_s, y_s = zip(*sample)\n reg.fit(x_s, y_s)\n betas = reg.weights_\n return betas",
"def getAction(self, gameState):\n \"*** YOUR CODE HERE ***\"\n return self.alpha_beta(gameState, 0, self.depth, (-10e8, None), (10e8, None))[1]",
"def getAction(self, gameState):\n return self.alphaBetaState(gameState, 0, 0, -float('inf'), float('inf'))",
"def get_test(arn=None):\n pass",
"def test_get_skill_name(self):\n result = self.runner.invoke(\n cli,\n [*CLI_LOG_OPTION, \"config\", \"get\", \"skills.dummy.name\"],\n standalone_mode=False,\n )\n assert result.exit_code == 0\n assert result.output == \"dummy\\n\"",
"def beta(self):\n return self[1::2]",
"def getAction(self, gameState):\n \"*** YOUR CODE HERE ***\"\n best_result = self.getaplhabeta(gameState, 0, 0, gameState.getNumAgents(), -float('inf'), float('inf'))\n return best_result[0] # return the result",
"def get_beta(self,df,tick,ind):\n cov = get_cov(df,tick,ind)\n var = df[ind].var()\n beta = cov / var\n return beta",
"def test_alphabeta_interface(self):\n h, w = 9, 9 # board size\n test_depth = 1\n starting_location = (2, 7)\n adversary_location = (0, 0) # top left corner\n iterative_search = False\n search_method = \"alphabeta\"\n heuristic = lambda g, p: 0. # return 0 everywhere\n\n # create a player agent & a game board\n agentUT = game_agent.CustomPlayer(\n test_depth, heuristic, iterative_search, search_method)\n agentUT.time_left = lambda: 99 # ignore timeout for fixed-depth search\n board = isolation.Board(agentUT, 'null_agent', w, h)\n\n # place two \"players\" on the board at arbitrary (but fixed) locations\n board.apply_move(starting_location)\n board.apply_move(adversary_location)\n\n for move in board.get_legal_moves():\n next_state = board.forecast_move(move)\n v, _ = agentUT.alphabeta(next_state, test_depth)\n\n self.assertTrue(type(v) == float,\n (\"Alpha Beta function should return a floating \" +\n \"point value approximating the score for the \" +\n \"branch being searched.\"))",
"def skill(self):\n return self._get(\"skill\")",
"def get_beta_sheet(self):\n return self.beta_sheet",
"def get_sample_badge(self):\n\n badgr = self.get_badgr_setup()\n with vcr.use_cassette('tests/vcr_cassettes/badge_retrieval.yaml'):\n return badgr.badges[0]",
"def pvalue_beta(self):\n return self._pvalue_beta",
"def get_optimal_beta(self):\n if self.annealing:\n # find the epoch/index that had the highest NDCG@k value\n index_max_ndcg = np.argmax(self.val_ndcg)\n\n # using this index find the value that beta had at this epoch\n return self.ls_beta[index_max_ndcg]\n else:\n return self.beta",
"def test_allow_beta(self):\r\n user = UserFactory()\r\n allow_access(self.course, user, 'beta')\r\n self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(user))",
"def _se_beta(self):\n return _handle_ab(self._se_all, self.use_const)[1]",
"def _get_alpha_beta(self):\n alpha = tf.nn.softplus(self.alpha_prime)\n beta = -alpha + tf.nn.softplus(self.beta_prime)\n return alpha, beta",
"def beta_channel(self):\n return self._data[ATTR_BETA_CHANNEL]"
] | [
"0.62065864",
"0.60728866",
"0.5912442",
"0.5846177",
"0.5846177",
"0.5825687",
"0.57786304",
"0.5759203",
"0.5674933",
"0.56633794",
"0.54740316",
"0.5328713",
"0.5317437",
"0.5276266",
"0.52476704",
"0.52083284",
"0.5155649",
"0.51427096",
"0.51348656",
"0.51102877",
"0.5080767",
"0.50621516",
"0.50478923",
"0.5046779",
"0.50269234",
"0.5010521",
"0.49841794",
"0.4970034",
"0.49576524",
"0.49426383"
] | 0.72415125 | 0 |
Create beta test. Create a beta test for a given Alexa skill. | def create_beta_test_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "create_beta_test_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_test_body' in params:
body_params = params['create_test_body']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message="Success. Return a URL to track the resource in 'Location' header."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BetaTest_e826b162, BadRequestError_f854b05]\n operation_name = \"get_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\", status_code=200, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\")\n\n if full_response:\n return api_response\n return api_response.body",
"def start_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"start_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/start'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def end_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"end_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/end'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def post(self):\n data = request.json\n create_testing_scenario(data)\n return None, 201",
"def test_allow_beta(self):\r\n user = UserFactory()\r\n allow_access(self.course, user, 'beta')\r\n self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(user))",
"def test_create_boat(self):\n pass",
"def test_create_team(self):\n pass",
"def test_alphabeta_interface(self):\n h, w = 9, 9 # board size\n test_depth = 1\n starting_location = (2, 7)\n adversary_location = (0, 0) # top left corner\n iterative_search = False\n search_method = \"alphabeta\"\n heuristic = lambda g, p: 0. # return 0 everywhere\n\n # create a player agent & a game board\n agentUT = game_agent.CustomPlayer(\n test_depth, heuristic, iterative_search, search_method)\n agentUT.time_left = lambda: 99 # ignore timeout for fixed-depth search\n board = isolation.Board(agentUT, 'null_agent', w, h)\n\n # place two \"players\" on the board at arbitrary (but fixed) locations\n board.apply_move(starting_location)\n board.apply_move(adversary_location)\n\n for move in board.get_legal_moves():\n next_state = board.forecast_move(move)\n v, _ = agentUT.alphabeta(next_state, test_depth)\n\n self.assertTrue(type(v) == float,\n (\"Alpha Beta function should return a floating \" +\n \"point value approximating the score for the \" +\n \"branch being searched.\"))",
"def test_create_scenario(self):\n pass",
"def test_create(self, client, job, agent_token):\n stage_url = '{base}/stages/teststage'.format(base=job_url_for(job))\n response = client.put(\n stage_url,\n headers={'x_dockci_api_key': agent_token},\n data={'success': 'true'},\n )\n\n assert response.status_code == 200 # TODO 201\n\n response_data = json.loads(response.data.decode())\n assert response_data.pop('success') == True\n\n response = client.get(stage_url)\n response_data = json.loads(response.data.decode())\n assert response_data.pop('success') == True",
"def add_testers_to_beta_test_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"add_testers_to_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/add'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def create_test_goal(context, **kw):\n goal = get_test_goal(context, **kw)\n goal.create()\n return goal",
"def createMakingTest(tx, query, personId, testId, date, hour, result):\n tx.run(query, personId=personId, testId=testId, date=date, hour=hour, result=result)",
"def create_test_audit(context, **kw):\n audit = get_test_audit(context, **kw)\n audit.create()\n return audit",
"def test_create_scenario1(self):\n pass",
"def test_intent_classifier_add_testing_samples(self):\n pass",
"def test_create(session, client, jwt, desc, json_data, roles, status, has_account):\n current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)\n current_app.config.update(AUTH_SVC_URL=MOCK_URL_NO_KEY)\n headers = None\n # setup\n if has_account and BCOL_HELP in roles:\n headers = create_header_account(jwt, roles, 'test-user', BCOL_HELP)\n elif has_account and GOV_ACCOUNT_ROLE in roles:\n headers = create_header_account(jwt, roles, 'test-user', '1234')\n elif has_account:\n headers = create_header_account(jwt, roles)\n else:\n headers = create_header(jwt, roles)\n\n # test\n response = client.post('/api/v1/financing-statements',\n json=json_data,\n headers=headers,\n content_type='application/json')\n\n # check\n assert response.status_code == status\n if response.status_code == HTTPStatus.CREATED:\n registration: Registration = Registration.find_by_registration_number(response.json['baseRegistrationNumber'],\n 'PS12345', True)\n assert registration.verification_report",
"def create_beta_priors(df):\n df['alpha'] = np.minimum(np.maximum((1 - df.expected) * np.power(df.expected, 2) / df.variance - df.expected, 0.1), 15)\n df['beta'] = df.alpha / df.expected - df.alpha\n return df",
"def create_test_action(context, **kw):\n action = get_test_action(context, **kw)\n action.create()\n return action",
"def test_skills(\n self, mock_get_ai_details, mock_get_ai, mock_get_categories\n ):\n\n mock_get_ai.return_value = self.ai\n mock_get_ai_details.return_value = self.ai_details\n\n mock_get_ai_details.return_value['skills'] = [\n {'name': 'bot 1'},\n {'name': 'bot 2'},\n {'name': 'bot 3'},\n {'name': 'bot 4'},\n {'name': 'bot 5'},\n {'name': 'bot 6'},\n ]\n\n response = self.client.get(reverse(\n 'studio:edit_bot',\n kwargs={'aiid': self.ai['aiid']}\n ))\n\n self.assertContains(response, 'bot 1')\n self.assertContains(response, 'bot 2')\n self.assertContains(response, 'bot 3')\n self.assertContains(response, 'bot 4')\n self.assertContains(response, 'bot 5')\n self.assertNotContains(response, 'bot 6')\n self.assertNotContains(response, 'Speed up your bot building process by '\n 'starting with one of our Templates from the store.')",
"def test_teams_create(self):\n pass",
"def create_test_action_plan(context, **kw):\n action_plan = get_test_action_plan(context, **kw)\n action_plan.create()\n return action_plan",
"def test_create_experiment_hit_branch(self):\n with OrionState(experiments=[config]) as cfg:\n experiment = create_experiment(\n config[\"name\"],\n space={\"y\": \"uniform(0, 10)\"},\n branching={\"enable\": True},\n storage=cfg.storage_config,\n )\n\n assert experiment.name == config[\"name\"]\n assert experiment.version == 2\n assert experiment.algorithm\n assert experiment.algorithm.configuration == config[\"algorithm\"]\n assert experiment.max_trials == config[\"max_trials\"]\n assert experiment.max_broken == config[\"max_broken\"]\n assert experiment.working_dir == config[\"working_dir\"]",
"def test_ask_yesno_yes(self):\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'yes'\n\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'yes')",
"def test_create_goal(self):\n pass",
"def test_create_activity(self):\n pass",
"def test_ask_yesno_no(self):\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'nope'\n\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'no')",
"def test_create_ban(self):\n pass",
"def estimate_sample_beta(sample):\n x_s, y_s = zip(*sample)\n reg.fit(x_s, y_s)\n betas = reg.weights_\n return betas"
] | [
"0.67994094",
"0.65799725",
"0.6277017",
"0.60846496",
"0.5496496",
"0.5472379",
"0.54534733",
"0.53817886",
"0.5377961",
"0.5373045",
"0.5372878",
"0.53613985",
"0.5318546",
"0.52971",
"0.5256494",
"0.5179809",
"0.51281613",
"0.50656486",
"0.50383884",
"0.5002523",
"0.49994695",
"0.4999264",
"0.49918392",
"0.49889317",
"0.49632567",
"0.4954383",
"0.49452168",
"0.49266",
"0.4886127",
"0.48812717"
] | 0.7222054 | 0 |
Update beta test. Update a beta test for a given Alexa skill. | def update_beta_test_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "update_beta_test_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_test_body' in params:
body_params = params['create_test_body']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="Thrown if user tries to request a new simulation while the old simulation is in progress."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="PUT",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def end_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"end_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/end'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_skills_updated(self):\n assert self.agent_config.skills == {self.new_skill_id}",
"def test_skills_updated(self):\n assert self.skill_config.skills == {self.new_skill_id}",
"def stepETAUpdate(build, step, ETA, expectations):",
"def get_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BetaTest_e826b162, BadRequestError_f854b05]\n operation_name = \"get_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\", status_code=200, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_update(self, init_db, audit):\n params = {\n \"resource_type\": \"Category\",\n \"action\": \"Updated\",\n \"activity\": \"changed name\"\n }\n audit.update(**params)\n assert audit.resource_type == params['resource_type']\n assert audit.action == params['action']\n assert audit.activity == params['activity']",
"def test_beta_updates_to_stable(self):\n self.change_version(self.version_1_2_0, '1.2beta')\n self.change_status(self.version_1_2_0, amo.STATUS_BETA)\n self.change_status(self.version_1_2_2, amo.STATUS_BETA)\n\n version, file = self.get('1.2beta', self.version_int,\n self.app, self.platform)\n assert version == self.version_1_2_1",
"def test_update(self, client, stage, agent_token):\n stage_url = stage_url_for(stage)\n response = client.put(\n stage_url,\n headers={'x_dockci_api_key': agent_token},\n data={'success': 'false'},\n )\n\n assert response.status_code == 200\n\n response_data = json.loads(response.data.decode())\n assert response_data.pop('success') == False\n\n response = client.get(stage_url)\n response_data = json.loads(response.data.decode())\n assert response_data.pop('success') == False",
"def test_update_team(self):\n pass",
"def test_update_scenario(self):\n pass",
"def setBetaFactor(self, newBeta):\n self.beta = newBeta\n self.gamma = self.calculateGammaFactors()",
"def test_update():\n learner = optlearner.VolatilityLearner()\n\n for reward in [0, 1]:\n slow_pIk = slow_update(learner, reward)\n learner._update(reward)\n yield npt.assert_array_equal, slow_pIk, learner.pIk\n learner.reset()",
"def test_update(self):\n optimizer = \"RandomSearch\"\n name = \"test_init_experiment\"\n param_defs = {\n \"x\": MinMaxNumericParamDef(0, 1),\n \"name\": NominalParamDef([\"A\", \"B\", \"C\"])\n }\n minimization = True\n\n LAss = PrettyLabAssistant()\n LAss.init_experiment(name, optimizer, param_defs, minimization=minimization)\n cand = LAss.get_next_candidate(name)\n cand.result = 1\n LAss.update(name, cand)\n assert_items_equal(LAss.exp_assistants[name].experiment.candidates_finished, [cand])\n assert_equal(LAss.exp_assistants[name].experiment.candidates_finished[0].result, 1)",
"def updateSkillPoints(skill, db, delta):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if not skill_data:\n return colored(\"ERROR: Skill {S} is not in your skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n new_points = max(0, skill_data['points'] + int(delta))\n db.execute(\n 'UPDATE mystatus SET points = ? WHERE skill = ?', (str(new_points), str(skill)))\n db.commit()\n return colored(\"{S}\\' power is updated from {OLD} -> {NEW}\".format(\n S=str(skill), OLD=str(skill_data['points']), NEW=str(new_points)), 'cyan')",
"def create_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"create_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Success. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_update_skills_to_completed(self):\n self._build_sample_graph()\n self._create_lessons() # 3 lessons in unit 1\n self._add_student_and_progress() # sa completed, sb in progress\n self._create_linear_progress() # Lesson 1 and 2 completed\n self.lesson1.properties[SKILLS_KEY] = [self.sa.id,\n self.sb.id]\n self.course.save()\n\n start_time = time.time()\n tracker = SkillCompletionTracker(self.course)\n lprogress_tracker = UnitLessonCompletionTracker(self.course)\n lprogress = lprogress_tracker.get_or_create_progress(self.student)\n tracker.update_skills(self.student, lprogress, self.lesson1.lesson_id)\n # Nothing changes with sa\n sprogress = models.StudentPropertyEntity.get(\n self.student, SkillCompletionTracker.PROPERTY_KEY)\n progress_value = transforms.loads(sprogress.value)\n self.assertIn(tracker.COMPLETED, progress_value[str(self.sa.id)])\n self.assertLessEqual(\n progress_value[str(self.sa.id)][tracker.COMPLETED], start_time)\n\n # Update in sb\n self.assertIn(tracker.COMPLETED, progress_value[str(self.sb.id)])\n self.assertGreaterEqual(\n progress_value[str(self.sb.id)][tracker.COMPLETED], start_time)",
"def updateEMPSampleData(self, sample_id, sample_score, emp_status, web_app_user_id):\n con = self.getMetadataDatabaseConnection()\n con.cursor().callproc('qiime_assets.update_emp_sample_data', [sample_id, sample_score, emp_status, web_app_user_id])",
"def start_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"start_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/start'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_beta_to_stable(self):\n self.change_version(self.version_1_2_0, '1.2beta')\n self.change_status(self.version_1_2_0, amo.STATUS_BETA)\n\n version, file = self.get('1.2beta', self.version_int,\n self.app, self.platform)\n assert version == self.version_1_2_2",
"def test_do_update(test_dao):\r\n DUT = dtmFunction(test_dao, test=True)\r\n DUT.do_select_all(revision_id=1)\r\n\r\n _function = DUT.tree.get_node(1).data\r\n _function.availability_logistics = 0.9832\r\n\r\n _error_code, _msg = DUT.do_update(1)\r\n\r\n assert _error_code == 0\r\n assert _msg == (\"RAMSTK SUCCESS: Updating the RAMSTK Program \" \"database.\")",
"def TestItem(ss, idx):\n cur = ss.TestEnv.Trial.Cur\n ss.TestEnv.Trial.Cur = idx\n ss.TestEnv.SetTrialName()\n\n ss.Net.LayerByName(\"Output\").SetType(emer.Compare)\n ss.ApplyInputs(ss.TestEnv)\n ss.AlphaCyc(False)\n ss.TrialStats(False)\n ss.TestEnv.Trial.Cur = cur",
"def test_update_vip(self):\r\n resource = 'vip'\r\n cmd = vip.UpdateVip(test_cli20.MyApp(sys.stdout), None)\r\n self._test_update_resource(resource, cmd, 'myid',\r\n ['myid', '--name', 'myname',\r\n '--tags', 'a', 'b'],\r\n {'name': 'myname', 'tags': ['a', 'b'], })",
"def test_update_goal(self):\n pass",
"def test_update_vip(self):\n resource = 'vip'\n cmd = vip.UpdateVip(test_cli20.MyApp(sys.stdout), None)\n self._test_update_resource(resource, cmd, 'myid',\n ['myid', '--name', 'myname',\n '--tags', 'a', 'b'],\n {'name': 'myname', 'tags': ['a', 'b'], })",
"def test_update(self):\n\n\n username,userpass = self.testdata.find_account_for('toolsubmitter')\n\n self.utils.account.login_as(username,userpass)\n\n self.contribtool.update(TOOLNAME,username,userpass)",
"def test_update_balance(self):\n current_year_tuple = (0.1, 0.1, 0.8)\n iteration_balance = 90\n contribution = 10\n expected_result = 110\n test_balance = investment_growth.update_balance(iteration_balance, contribution, current_year_tuple)\n self.assertEqual(test_balance, expected_result)",
"def test_update_activity(self):\n pass",
"def updateBeta(self):\n\n priorBeta = np.copy(self.beta) # 返り値で更新幅を与えるので初期値を保持しておく\n W = self.__genW() # diag Matrix\n # update beta : Fisher Scoring Update\n result = np.matmul(np.matmul(self.X.T, W), self.X)\n result = np.matmul(np.linalg.inv(result), self.X.T)\n result = np.matmul(result, W)\n # claimFreq=0の人は, firstIterationでmu=0の0割が必ず発生する. 適切な対処法は+epsilonで良い?\n z = (self.Y - self.mu)/(self.mu + DoubleGLM.EPSILON) + np.log(self.mu + DoubleGLM.EPSILON)\n self.beta = np.matmul(result, z)\n\n # update current mu\n self.mu = np.exp(np.matmul(self.X, self.beta))\n # update current deviance\n d1 = self.Y * (self.Y**(1-self.p) - self.mu**(1-self.p)) / (1-self.p)\n d2 = (self.Y**(2-self.p) - self.mu**(2-self.p)) / (2-self.p)\n self.d = 2*self.w * (d1 - d2)\n\n return np.abs(priorBeta - self.beta)",
"def test_update_team_state(self):\n pass",
"def test_update(self):\n pass"
] | [
"0.6030136",
"0.59667206",
"0.5931028",
"0.57376856",
"0.5693456",
"0.5592109",
"0.5580282",
"0.5520951",
"0.54991055",
"0.54870695",
"0.5486362",
"0.54673177",
"0.5458189",
"0.54581165",
"0.54083073",
"0.5290761",
"0.5281577",
"0.5252588",
"0.52507883",
"0.5238994",
"0.51973057",
"0.51769114",
"0.5146355",
"0.5143779",
"0.5142607",
"0.51416016",
"0.51322407",
"0.51167274",
"0.5110991",
"0.5104823"
] | 0.69719386 | 0 |
Start beta test Start a beta test for a given Alexa skill. System will send invitation emails to each tester in the test, and add entitlement on the acceptance. | def start_beta_test_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "start_beta_test_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest/start'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message="Accept. Return a URL to track the resource in 'Location' header."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"create_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Success. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def update_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def startTest(asset):",
"def add_testers_to_beta_test_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"add_testers_to_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/add'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def end_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"end_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/end'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BetaTest_e826b162, BadRequestError_f854b05]\n operation_name = \"get_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\", status_code=200, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\")\n\n if full_response:\n return api_response\n return api_response.body",
"def send_beta_role_email(action, user, email_params):\r\n if action == 'add':\r\n email_params['message'] = 'add_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n elif action == 'remove':\r\n email_params['message'] = 'remove_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n else:\r\n raise ValueError(\"Unexpected action received '{}' - expected 'add' or 'remove'\".format(action))\r\n\r\n send_mail_to_student(user.email, email_params)",
"def start_test(self, test_item):\n msg = messages.StartTest(test_id=test_item.identifier)\n self._request(msg)",
"def test_jam_attempt(self):\n self.run_test_suites(self.jam_test_suite_list)",
"def test_teams_invite_member(self):\n pass",
"def start_test(self, name, attributes):\n test = Test(name=name, attributes=attributes)\n self.current_scope = \"TEST\"\n self.robot_service.start_test(test=test)",
"def test_launch(self):\n\n\n username,userpass = self.testdata.find_account_for('toolsubmitter')\n\n self.utils.account.login_as(username,userpass)\n\n self.contribtool.launch(TOOLNAME,username,userpass)",
"def start_suite(self, name, attributes):\n suite = Suite(attributes=attributes)\n self.current_scope = \"SUITE\"\n if attributes[\"id\"] == FIRST_SUITE_ID:\n self._init_service()\n # if launch id is specified, use it\n # otherwise create launch automatically\n if self._launch_id is not None:\n self.robot_service.rp.launch_id = self._launch_id\n else:\n if self.pabot_used:\n raise Exception(\"Pabot used but launch_id is not provided. \"\n \"Please, correctly initialize listener with launch_id argument.\")\t\t\t\n # fill launch description with contents of corresponding variable value\n suite.doc = self.robot_variables.launch_doc.replace(\"?\", \"\\n\").replace(\"!\", \" \")\n # automatically creating new report portal launch\n launch_id = self.robot_service.start_launch(launch_name=self.robot_variables.launch_name,\n launch=suite)\n # save launch id for service\n self.robot_service.rp.launch_id = launch_id\n # initialize report portal service to use in test run\n if attributes['tests']:\n self.robot_service.start_suite(name=attributes['longname'], suite=suite)",
"def start_test(self, request):\n request.worker.start_test(request.message.test_id)\n\n return SuccessReply()",
"def test_activate_form(self, mock_sendmail):\r\n res = self.testapp.post('/api/v1/suspend',\r\n params={'email': u'[email protected]'},\r\n status=200)\r\n\r\n success = json.loads(res.body)\r\n self.assertTrue(\r\n 'message' in success,\r\n \"Should be successful with admin email address: \" + str(res))\r\n self.assertTrue(mock_sendmail.called)",
"def test_allow_beta(self):\r\n user = UserFactory()\r\n allow_access(self.course, user, 'beta')\r\n self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(user))",
"async def beginner(self, ctx):\n await ctx.send(f'Testing beginner')",
"def test_create_user_auto_activate(self, services):\n data = {\n 'username': 'John',\n 'email': '[email protected]',\n 'password': 'test123!',\n 'phone': '1234567890',\n 'first_name': 'Chuck',\n 'last_name': 'Norris',\n 'university': {\n \"name\": \"random_university\"\n },\n 'academic_field': {'name': \"random_field\"},\n 'academic_level': {'name': \"random_level\"},\n 'gender': \"M\",\n 'birthdate': \"1999-11-11\",\n }\n\n response = self.client.post(\n reverse('user-list'),\n data,\n format='json',\n )\n\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n self.assertEqual(json.loads(response.content)['phone'], '1234567890')\n\n user = User.objects.get(email=\"[email protected]\")\n activation_token = ActionToken.objects.filter(\n user=user,\n type='account_activation',\n )\n\n self.assertTrue(user.is_active)\n self.assertEqual(1, len(activation_token))\n\n # Test that no email was sent:\n self.assertEqual(len(mail.outbox), 0)",
"def test_request_project_invitation(self):\n pass",
"def startTestHook(self):",
"def batch_test_open():\n try:\n WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.CLASS_NAME, \"cdk-overlay-pane\")))\n ActionChains(browser).send_keys(Keys.ESCAPE).perform()\n except:\n print(\"No migration pop-up\")\n\n WebDriverWait(browser, 2).until(EC.element_to_be_clickable((By.LINK_TEXT, config.app_name)))\n browser.find_element_by_link_text(config.app_name).click()\n WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.CLASS_NAME, 'nav-section')))\n buttons = browser.find_elements_by_class_name('nav-section')\n buttons[1].click()\n WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.XPATH, '//button[contains(text(), '\n '\"Batch testing\")]')))\n browser.find_element_by_xpath('//button[contains(text(), \"Batch testing\")]').click()",
"def on_launch(launch_request, session):\r\n # Dispatch to your skill's launch message\r\n return get_welcome_response()",
"def test_approve(self):\n\n username,userpass = self.testdata.find_account_for('toolsubmitter')\n\n self.utils.account.login_as(username,userpass)\n\n self.contribtool.approve(TOOLNAME,TOOLLICENSEDATA)",
"def test_skills(self):\n yield self.nodes[0].overlay.trustchain.add_skill('test')\n yield self.deliver_messages()\n peer1_pub_key = self.nodes[0].overlay.trustchain.my_peer.public_key.key_to_bin()\n self.assertTrue(self.nodes[0].overlay.trustchain.persistence.get_skills(peer1_pub_key))\n\n skills = self.nodes[1].overlay.trustchain.persistence.get_skills(peer1_pub_key)\n self.assertTrue(skills)\n\n # Peer 2 endorses peer 1 now\n block, _ = yield self.nodes[1].overlay.trustchain.endorse_skill(peer1_pub_key, skills[0]['block_num'])\n yield self.deliver_messages()\n self.assertTrue(self.nodes[1].overlay.trustchain.persistence.did_endorse_skill(block))\n\n skills = self.nodes[0].overlay.trustchain.persistence.get_skills(peer1_pub_key)\n self.assertEqual(skills[0]['endorsements'], 1)",
"def on_launch(launch_request, session):\r\n\r\n #print(\"****on_launch requestId=\" + launch_request['requestId'] +\r\n # \", sessionId=\" + session['sessionId'])\r\n # Dispatch to your skill's launch\r\n return get_welcome_response()",
"def setUp(self):\n pyauto.PyUITest.setUp(self)\n\n webapp = self.InstallExtension(self.GetWebappPath())\n self.host.LaunchApp(webapp)\n self.account = self.GetPrivateInfo()['test_chromoting_account']",
"def test_openedx_studio_launch_request(self):\n\n consumer = LTIConsumerFactory(slug=\"consumer\")\n passport = LTIPassportFactory(title=\"consumer1_passport1\", consumer=consumer)\n\n user_count = get_user_model().objects.count()\n\n # User 1 is using ashley from openedx studio in the course \"TEST1\"\n user1 = self._authenticate(\n {\n \"context_id\": \"course-v1:TEST1+0001+2020_T1\",\n \"context_label\": \"TEST1\",\n \"context_title\": \"test course 1\",\n \"custom_component_display_name\": \"Forum\",\n \"launch_presentation_return_url\": \"\",\n \"lis_result_sourcedid\": \"course-v1%3ATEST1%2B0001%2B2020_T1:-c7b2c44b1d\",\n \"lti_message_type\": \"basic-lti-launch-request\",\n \"lti_version\": \"LTI-1p0\",\n \"resource_link_id\": \"-c7b2c44b1d\",\n \"roles\": \"Instructor\",\n \"user_id\": \"student\",\n },\n passport,\n )\n\n # A new ashley user should have been created\n self.assertEqual(user_count + 1, get_user_model().objects.count())\n self.assertEqual(\"Educational team\", user1.public_username)\n self.assertEqual(\"\", user1.email)\n self.assertEqual(consumer, user1.lti_consumer)\n self.assertNotEqual(\"student@consumer\", user1.username)\n\n # User 2 is using ashley from openedx studio in the course \"TEST1\"\n # (it is basically the same LTI launch request than user 1)\n user2 = self._authenticate(\n {\n \"context_id\": \"course-v1:TEST1+0001+2020_T1\",\n \"context_label\": \"TEST1\",\n \"context_title\": \"test course 1\",\n \"custom_component_display_name\": \"Forum\",\n \"launch_presentation_return_url\": \"\",\n \"lis_result_sourcedid\": \"course-v1%3ATEST1%2B0001%2B2020_T1:-c7b2c44b1d\",\n \"lti_message_type\": \"basic-lti-launch-request\",\n \"lti_version\": \"LTI-1p0\",\n \"resource_link_id\": \"-c7b2c44b1d\",\n \"roles\": \"Instructor\",\n \"user_id\": \"student\",\n },\n passport,\n )\n\n # user1 and user2 should be the same. No new user should have been created, since they\n # came from the same LTI context_id.\n self.assertEqual(user_count + 1, get_user_model().objects.count())\n self.assertEqual(user1, user2)\n\n # User 3 is using ashley from openedx studio in the course \"TEST2\"\n user3 = self._authenticate(\n {\n \"context_id\": \"course-v1:TEST2+0001+2020_T1\",\n \"context_label\": \"TEST2\",\n \"context_title\": \"test course 2\",\n \"custom_component_display_name\": \"Forum\",\n \"launch_presentation_return_url\": \"\",\n \"lis_result_sourcedid\": \"course-v1%3ATEST2%2B0001%2B2020_T1:-a2a2a2a2a2\",\n \"lti_message_type\": \"basic-lti-launch-request\",\n \"lti_version\": \"LTI-1p0\",\n \"resource_link_id\": \"-a2a2a2a2a2\",\n \"roles\": \"Instructor\",\n \"user_id\": \"student\",\n },\n passport,\n )\n # A new ashley user should have been created for user 3\n self.assertEqual(user_count + 2, get_user_model().objects.count())\n self.assertEqual(\"Educational team\", user3.public_username)\n self.assertEqual(\"\", user3.email)\n self.assertEqual(consumer, user3.lti_consumer)\n self.assertNotEqual(\"student@consumer\", user3.username)\n self.assertNotEqual(user1, user3)",
"def run():\n\n # Set up environment and agent\n e = Environment() # create environment (also adds some dummy traffic)\n a = e.create_agent(LearningAgent) # create agent\n e.set_primary_agent(a, enforce_deadline=False) # specify agent to track\n # NOTE: You can set enforce_deadline=False while debugging to allow longer trials\n\n # Now simulate it\n sim = Simulator(e, update_delay=0.0000001, display=False) # create simulator (uses pygame when display=True, if available)\n # NOTE: To speed up simulation, reduce update_delay and/or set display=False\n\n sim.run(n_trials=100) # run for a specified number of trials\n # NOTE: To quit midway, press Esc or close pygame window, or hit Ctrl+C on the command-line\n\n print 'alpha, gamma:', a.alpha, a.gamma\n print 'penalties:', a.total_penalties\n print 'total rewards:', a.total_rewards",
"def begin_trial(self):\n self._post(endpoint='{}/cm/trial/begin'.format(self.api_version))",
"def startTestRun(self):"
] | [
"0.58114564",
"0.57895595",
"0.55495626",
"0.5533645",
"0.55101997",
"0.55059665",
"0.5502358",
"0.5391071",
"0.5317593",
"0.52452296",
"0.52154356",
"0.5197792",
"0.5160328",
"0.5117921",
"0.50091255",
"0.49877074",
"0.49205288",
"0.49053085",
"0.49028757",
"0.48723567",
"0.48458496",
"0.48397437",
"0.4838865",
"0.4830496",
"0.4822028",
"0.48188776",
"0.48165634",
"0.48097184",
"0.4806468",
"0.47971022"
] | 0.6586409 | 0 |
Add testers to an existing beta test. Add testers to a beta test for the given Alexa skill. System will send invitation email to each tester and add entitlement on the acceptance. | def add_testers_to_beta_test_v1(self, skill_id, testers_request, **kwargs):
# type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "add_testers_to_beta_test_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'testers_request' is set
if ('testers_request' not in params) or (params['testers_request'] is None):
raise ValueError(
"Missing the required parameter `testers_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest/testers/add'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'testers_request' in params:
body_params = params['testers_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def send_beta_role_email(action, user, email_params):\r\n if action == 'add':\r\n email_params['message'] = 'add_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n elif action == 'remove':\r\n email_params['message'] = 'remove_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n else:\r\n raise ValueError(\"Unexpected action received '{}' - expected 'add' or 'remove'\".format(action))\r\n\r\n send_mail_to_student(user.email, email_params)",
"def add_test(self, testsuite, test):\n self.tests[testsuite].append(TestCase(test, self))\n self.num_tests += 1",
"def remove_testers_from_beta_test_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"remove_testers_from_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/remove'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_teams_add_user_to_team_by_batch_v1(self):\n pass",
"def addTest(self, test):\r\n self.tests.append(test)\r\n return",
"def test_teams_invite_member(self):\n pass",
"def test_integration_tests(mocker, testclient):\n if not PARAMS.get(\"token\"):\n # Pass if no token for acceptance tests\n return\n\n test_data = {}\n test_data[\"list_schedules\"] = list_schedule_tester(testclient)\n test_data[\"get_schedules\"] = get_schedule_tester(testclient, test_data[\"list_schedules\"][\"data\"][0][\"id\"])\n test_data[\"on_call\"] = get_on_call_tester(testclient, test_data[\"list_schedules\"][\"data\"][0][\"id\"])\n\n # Create alert\n alert_raw_response = create_alerts_tester(testclient)\n test_data[\"create_alert\"] = alert_raw_response\n alert_id = alert_raw_response.get(\"alertId\")\n # List alerts\n test_data[\"list_alerts\"] = list_alerts_tester(testclient)\n # Get the alert we just created\n test_data[\"get_alert\"] = get_alert_tester(testclient, alert_id)\n # Ack the same alert\n test_data[\"ack_alert\"] = ack_alert_tester(testclient, alert_id)\n # Close the same alert\n test_data[\"close_alert\"] = close_alert_tester(testclient, alert_id)\n # Delete the alert we just created\n test_data[\"delete_alert\"] = delete_alert_tester(testclient, alert_id)\n\n if os.getenv(\"GEN_TEST_DATA\"):\n # If set, test JSON added to test_data\n for k, v in test_data.items():\n with open(f\"test_data/{k}.json\", \"w\") as fh:\n json.dump(v, fh, indent=4, sort_keys=True)",
"def update_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def request_feedback_from_testers_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"request_feedback_from_testers_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/requestFeedback'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def send_reminder_to_testers_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"send_reminder_to_testers_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/sendReminder'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def add_experiment(self, experiment, trial_runner):\n generator = generate_trials(experiment.spec, experiment.name)\n while True:\n try:\n trial_runner.add_trial(next(generator))\n except StopIteration:\n break",
"def create_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"create_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Success. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_list_of_testers_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListTestersResponse_991ec8e9]\n operation_name = \"get_list_of_testers_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.beta_test.testers.list_testers_response.ListTestersResponse\", status_code=200, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.beta_test.testers.list_testers_response.ListTestersResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_allow_beta(self):\r\n user = UserFactory()\r\n allow_access(self.course, user, 'beta')\r\n self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(user))",
"def test_teams_add_user_to_team_v1(self):\n pass",
"def test_teams_add_user_to_team_v2(self):\n pass",
"def test_add(self):\n # Everything added will be deleted later in test_delete.\n first_name = 'Trevor'\n last_name = 'Harvey'\n entry_date = '04/19/2012'\n title = 'Test'\n minutes = 34\n notes = 'testing entries. and regex (555) 555-3425'\n self.data.add(first_name, last_name, entry_date, title, minutes, notes)\n # second test add\n first_name = 'Nik'\n last_name = 'Silver'\n entry_date = '01/14/1827'\n title = '[email protected]'\n minutes = 34\n notes = 'This is an email test.'\n\n self.data.add(first_name, last_name, entry_date, title, minutes, notes)",
"def test_intent_classifier_add_testing_samples(self):\n pass",
"def get_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BetaTest_e826b162, BadRequestError_f854b05]\n operation_name = \"get_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\", status_code=200, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_add_to_blacklist(self):\n\n self.feature_test.add_to_blacklist(3)\n self.assertTrue(3 in Feature(\"testing\").blacklist)",
"def test_add_team_member(self):\n pass",
"def multipleValidTxTest(self):\n log.info(\"--------------------Multiple valid Tx tests now started-------------------\")\n\n self.mvb.txWaitingPool += self.readTxFromFile('./TxFiles/MultipleValidTestTx.json')\n self.mvb.broadcastTxPools()",
"def add_experiments(self, environment_name, environment_builder_params, agent_names_list,\n agent_builders_params, **run_params):\n assert self._is_sweep is False or self._is_sweep is None\n self._is_sweep = False\n\n self.add_environment(environment_name, environment_builder_params, **run_params)\n\n for agent_name, agent_params in zip(agent_names_list, agent_builders_params):\n self.add_agent(environment_name, agent_name, agent_params)",
"def send_test_email_for_bulk_emails(tester_id, email_subject, email_body):\n tester_name = user_services.get_username(tester_id)\n tester_email = user_services.get_email_from_user_id(tester_id)\n _send_email(\n tester_id, tester_id, feconf.BULK_EMAIL_INTENT_TEST,\n email_subject, email_body, tester_email, sender_name=tester_name)",
"def add_test(self,test):\n l = test.id.split('.')\n s_obj = self\n while len(l) > 0:\n s_name = l.pop(0)\n if len(l) > 0:\n if s_name in s_obj.suites:\n s_obj = s_obj.suites[s_name]\n else:\n new_suite = Suite(s_name,parent=s_obj)\n s_obj.suites[s_name] = new_suite\n s_obj = new_suite\n s_obj.tests.append(test)",
"def test_intent_classifier_add_training_samples(self):\n pass",
"def addCustomTests(self, tests):\n pass",
"def test_send_email_on_invite(self):\n\n league = self.create_league()\n\n season = self.create_season(league)\n team = self.create_team(season)\n\n player = self.create_player()\n\n send_user_email_on_join(player, team.id)\n\n self.assertEqual(len(mail.outbox), 1)\n\n # if testing manually:\n # import pathlib\n # pathlib.Path(\"test_email.html\").write_text(last_sent.body)",
"def add_experiences(\n self,\n curr_all_info: AllBrainInfo,\n next_all_info: AllBrainInfo,\n take_action_outputs: ActionInfoOutputs,\n ) -> None:\n raise UnityTrainerException(\n \"The process_experiences method was not implemented.\"\n )",
"def test_inviteToEvent(self):\n # Create sample itinerary for alex for the event day\n self.json_post('/createItinerary/alex', dict(\n name = 'New Day',\n date = '2015-08-21T00:00:00.000Z'\n ))\n # Create sample itinerary for naina for the event day\n self.json_post('/createItinerary/naina', dict(\n name = 'New Day1',\n date = '2015-08-21T00:00:00.000Z'\n ))\n # Create sample itinerary for bugi for the event day\n self.json_post('/createItinerary/bugi', dict(\n name = 'New Day',\n date = '2015-08-21T00:00:00.000Z'\n ))\n # Create sample itinerary for amy for the event day\n self.json_post('/createItinerary/amy', dict(\n name = 'New Day',\n date = '2015-08-21T00:00:00.000Z'\n ))\n\n event = dict(start = '2015-08-21T11:23:00.000Z',\n end = '2015-08-21T11:25:00.000Z',\n date = '2015-08-21T00:00:00.000Z')\n rv = self.json_post('/createEvent/alex', event)\n uid = str('alex_' + event['start'] + event['end'])\n assert uid in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/bbbb', event)\n assert 'Invalid username' in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = \"invalidid\",\n invited = 'naina'\n ))\n print(rv.data)\n assert \"Event not found\" in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'bbbbb'\n ))\n assert \"Shared user does not exist\" in str(rv.data)\n\n # Share event with naina\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'naina'\n ))\n assert uid in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'naina'\n ))\n assert \"Already sent invitation\" in str(rv.data)\n\n rv = self.json_post('/createEvent/naina', dict(\n uid = uid\n ))\n assert uid in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'naina'\n ))\n assert \"Already shared with user\" in str(rv.data)\n\n # Share event with amy\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'amy'\n ))\n assert uid in str(rv.data)\n\n # Share event with amy\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'bugi'\n ))\n assert uid in str(rv.data)\n\n # Share event with amy\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'amy'\n ))\n assert \"Already sent invitation\" in str(rv.data)\n\n rv = self.json_post('/createEvent/amy', dict(\n uid = uid\n ))\n print(rv.data)\n assert uid in str(rv.data)"
] | [
"0.5863338",
"0.5774639",
"0.572012",
"0.5425559",
"0.53766775",
"0.532046",
"0.5312371",
"0.53067374",
"0.5284947",
"0.52377874",
"0.52059793",
"0.51717895",
"0.51412475",
"0.50801593",
"0.5077373",
"0.50261235",
"0.49931276",
"0.4890633",
"0.48818922",
"0.4881252",
"0.4875264",
"0.4857629",
"0.4848681",
"0.48453683",
"0.48426095",
"0.4814578",
"0.4812112",
"0.47948056",
"0.4783003",
"0.47771627"
] | 0.74168843 | 0 |
List testers. List all testers in a beta test for the given Alexa skill. | def get_list_of_testers_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListTestersResponse_991ec8e9]
operation_name = "get_list_of_testers_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest/testers'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.beta_test.testers.list_testers_response.ListTestersResponse", status_code=200, message="Success."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.beta_test.testers.list_testers_response.ListTestersResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list_tests(arn=None, nextToken=None):\n pass",
"def add_testers_to_beta_test_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"add_testers_to_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/add'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def lab_test_list(\n self, params: Optional[Dict] = None, headers: Optional[Dict] = None\n ) -> List[LabTestDetails]:\n method = self._get_method(\"lab_tests\")\n\n return self.call_api_get(method=method, params=params, headers=headers)",
"def remove_testers_from_beta_test_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"remove_testers_from_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/remove'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def list_feature_tests(self):\n\t\treturn self.test_names",
"def list_suites(arn=None, nextToken=None):\n pass",
"def List(ctx):\n \"\"\"Note: This method is available only through the per-node API endpoint 5.0 or later.\"\"\"\n if ctx.element is None:\n ctx.logger.error(\"You must establish at least one connection and specify which you intend to use.\")\n exit()\n\n\n\n ctx.logger.info(\"\")\n try:\n ListTestsResult = ctx.element.list_tests()\n except common.ApiServerError as e:\n ctx.logger.error(e.message)\n exit()\n except BaseException as e:\n ctx.logger.error(e.__str__())\n exit()\n\n cli_utils.print_result(ListTestsResult, ctx.logger, as_json=ctx.json, depth=ctx.depth, filter_tree=ctx.filter_tree)",
"def list(ctx):\n handler = ValidateCommandHandler(ctx.obj['qa_dir'])\n if handler.validate():\n handler = ListCommandHandler(ctx.obj['qa_dir'])\n handler.show_test_case_tree()\n else:\n exit(1)",
"def test_list(self):\n response = self.app.get(self.url('tags.list'))\n # Test response...",
"def list(self):\n print \"\\nAvailable Test Cases\"\n print \"====================\"\n for case in self.cases:\n print case.__name__",
"def get_all_reporters():\r\n for ep in iter_entry_points('attest.reporters'):\r\n yield ep.name",
"def test_teams_list(self):\n pass",
"def test_get_learners(self):\n pass",
"def list_tiddlers(self, bag):\n prefix, suffix = self._get_jsonp()\n return prefix + JSON.list_tiddlers(self, bag) + suffix",
"def request_feedback_from_testers_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"request_feedback_from_testers_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/requestFeedback'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def teams():\n print 'Getting Teams'\n\n substring = \"%\" + request.args.get('t') + \"%\"\n\n team_list = datastore.get_teams_typeahead(engine, substring, max_teams=10)\n\n print 'Teams:', team_list\n return jsonify(team_list)",
"def list_suites(suitedir=\"./testcases/suites\", cloud=False):\n suites = []\n suites.extend(TestSuite.get_suite_files(suitedir))\n\n # no suitedir, or no suites -> append cloud.get_campaigns()\n\n if cloud:\n names = cloud.get_campaign_names()\n if names:\n suites.append(\"------------------------------------\")\n suites.append(\"FROM CLOUD:\")\n suites.extend(names)\n if not suites:\n return None\n\n from prettytable import PrettyTable\n table = PrettyTable([\"Testcase suites\"])\n for suite in suites:\n table.add_row([suite])\n return table",
"def list_teams():\n name = request.args.get(\"name\", None)\n\n # Search team by name\n if name:\n team = TeamController.get(filters={\"Team\": {\"name\": name}})\n return jsonify(format_team(team)), 200\n\n # Otherwise list of the teams\n teams = TeamController.list()\n return jsonify({\"teams\": [format_team(s) for s in teams]}), 200",
"def alltests(opts):\n \n print \"API Root: %s\" % options.apiroot\n print \"Token: %s\" % options.token\n print \"Output dir: %s\" % options.output\n print \"Running %d%% of tests\" % options.percent\n print\n \n # need to use DEPT-001, not ID#\n coursehistory_tests = [\n # basic tests:\n \"cis-120\", \"math-114\", \"engl-101\", \"econ-001\",\n # miscellaneously somewhat problematic:\n \"engl-016\", \"law-205\", \"hpr-612\", \"rels-414\", \"nurs-322\",\n \"writ-030\", \"be-310\", \"psci-010\", \"psci-136\",\n # crosslistings:\n \"engl-135\", \"writ-135\", \"fnar-264\", \"cogs-001\", \"russ-048\", \"hist-048\",\n # no reviews?:\n \"afam-271\", \"ames-071\", \"slav-532\", \"afam-285\", \"prtg-213\", \"slav-533\",\n # errors:\n \"99999\", \"moo\",\n ]\n\n instructor_tests = [\n # basic tests:\n \"403\", \"631\", \"1883\", \"2217-FERNANDO-C--PEREIRA\", \"1602-BENJAMIN-PIERCE\",\n # crosslistings:\n \"1034-LYLE-H-UNGAR\", \"2709-DAVID-P--COMBERG\",\n # miscellaneously somewhat problematic:\n \"1040-DAVID-FOX\", \"4268-BART-GERARD-C-DE-JONGHE\",\n # the instructors w/ the most sections\n \"1883\", \"1619\", \"2869\", \"942\", \"1644\", \"541\", \"767\", \"434\",\n # concerned citizens:\n \"1759-MAX-C--CAVITCH\", \"2824-TIMOTHY-CORRIGAN\",\n \"1763-EMILY-R-STEINER\", \"1624-VALERIE-ROSS\",\n # no reviews?:\n \"416-LUDO-ROCHER\", \"715-ELIZABETH-ANN-POLLARD\", \"1094-MARIA-A-COWLES\",\n \"1500-ANDREW-GALLIA\", \"1888-RUSSELL-DILEO\",\n \"1450-SORMANE-PEREIRA-GOMES\", \"2188-HUI-YI-CHEN\", \"1165-DOMENIC-VITIELLO\",\n \"2359-CLAUDIA-CANCINO\", \"2737-SHEN-WANG\", \"3229-BERLE-WHITBY\",\n # errors:\n \"99999\", \"moo\",\n ]\n\n dept_tests = [\n #fast\n \"CSE\", \"LAW\", \"ANAT\", \"KORN\", \"LATN\", \"COGS\", \"MSCI\", \"GAS\",\n #medium\n \"CIS\", \"MATH\", \"FNAR\", \"ACCT\", \"FNCE\", \"BE\", \"MUSC\", \"OPIM\",\n #slow\n #\"SPAN\", \"NURS\", \"ENGL\",\n #error\n \"EROR\"]\n\n index_tests = [\"\", \"instructors\", \"coursehistories\", \"depts\",\n \"semesters\", \"semesters/2010c\"]\n\n course_tests = [] # filled in by coursehistory_tests\n\n for t in fraclist(index_tests, options.percent):\n test(opts, t)\n \n for t in fraclist(coursehistory_tests, options.percent):\n obj = test(opts, \"coursehistories/%s\" % t)\n test(opts, \"coursehistories/%s/reviews\" % t)\n\n # now \"find\" some courses\n course_tests.append(\"2010c-%s\" % t)\n try:\n courseid = sorted(obj[\"result\"][\"courses\"])[0][\"id\"]\n course_tests.append(courseid)\n except (TypeError, KeyError, IndexError):\n pass\n \n for t in course_tests: # don't fraclist an autogenerated list\n # Some of the autogenerated courses don't exist, so ignore errors.\n root_success = test(opts, \"courses/%s\" % t, lderror_ok=True)\n if root_success:\n # Course exists, don't expect errors.\n test(opts, \"courses/%s/reviews\" % t)\n test(opts, \"courses/%s/coursehistories/\" % t)\n test(opts, \"courses/%s/sections\" % t)\n \n if test(opts, \"courses/%s/sections/001\" % t, lderror_ok=True):\n test(opts, \"courses/%s/sections/001/reviews\" % t) \n if '-' in str(t): # if we have a yyyys-dept-num test\n test(opts, \"sections/%s-001\" % t)\n # not tested: sections/001/reviews/instructor-id\n test(opts, \"courses/%s/sections/401\" % t, lderror_ok=True)\n \n for t in fraclist(instructor_tests, options.percent):\n test(opts, \"instructors/%s\" % t)\n test(opts, \"instructors/%s/sections\" % t)\n test(opts, \"instructors/%s/reviews\" % t)\n \n for t in fraclist(dept_tests, options.percent):\n test(opts, \"depts/%s\" % t)\n test(opts, \"depts/%s/reviews\" % t)\n test(opts, \"semesters/2010c/%s\" % t)",
"def list_tests(self, executable):\n # This will return an exit code with the number of tests available\n try:\n output = subprocess.check_output(\n [executable, \"--list-test-names-only\"],\n stderr=subprocess.STDOUT,\n universal_newlines=True,\n )\n except subprocess.CalledProcessError as e:\n output = e.output\n\n result = output.strip().split(\"\\n\")\n\n return result",
"def test_get_list_teams(self):\n args = {\n 'name': 'test team',\n 'capacity': '11',\n 'number_players': '6',\n 'pitch_postcode': 'E1 6LT',\n 'time': '2019-01-01 13:00'\n }\n team = Team(args)\n db.session.add(team)\n db.session.commit()\n response = self.client.get('/teams')\n self.assertEqual(response.status_code, 200)\n self.assertIn(b'test team', response.data)",
"def get_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BetaTest_e826b162, BadRequestError_f854b05]\n operation_name = \"get_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\", status_code=200, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.beta_test.beta_test.BetaTest\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_tests():\n # tests = ['test_build_gaussian_pyramid_random', 'test_build_gaussian_pyramid_static', 'test_build_laplacian_pyramid_random', 'test_build_laplacian_pyramid_static', 'test_laplacian_to_image', 'test_render_pyramid_random', 'test_render_pyramid_static']\n # return [tester.TestEx3(method) for method in tests]\n return [tester.TestEx3(method) for method in dir(tester.TestEx3) if method.startswith('test')]",
"def list_test_cases(program):\n\n return list(INFO[program].test_cases)",
"def generate_test_list(tdir):\n\n # Skip this if it already exists\n if os.path.exists(os.path.join(tdir.name, \"kstest-list\")):\n return\n\n kstest_log = os.path.join(tdir.name, \"kstest.log\")\n with open(kstest_log) as f:\n for line in f.readlines():\n if not line.startswith(\"Running tests: \"):\n continue\n\n tests = [os.path.basename(os.path.splitext(s)[0]) for s in line[15:].split()]\n with open(os.path.join(tdir.name, \"kstest-list\"), \"wt\") as klf:\n for t in tests:\n print(t, file=klf)\n break",
"def test_list(request, target, format=None):\n if request.method == 'GET':\n tests = Test.objects.filter(target=target)\n serializer = TestSerializer(tests, many=True)\n return Response(serializer.data)",
"def run_list_cli_tests(experiment_id: int) -> None:\n\n subprocess.check_call(\n [\"det\", \"-m\", conf.make_master_url(), \"experiment\", \"list-trials\", str(experiment_id)]\n )\n\n subprocess.check_call(\n [\"det\", \"-m\", conf.make_master_url(), \"experiment\", \"list-checkpoints\", str(experiment_id)]\n )\n subprocess.check_call(\n [\n \"det\",\n \"-m\",\n conf.make_master_url(),\n \"experiment\",\n \"list-checkpoints\",\n \"--best\",\n str(1),\n str(experiment_id),\n ]\n )",
"def test_intent_classifier_get_testing_samples(self):\n pass",
"def list_requesters():\n from mephisto.core.local_database import LocalMephistoDB\n from tabulate import tabulate\n\n db = LocalMephistoDB()\n requesters = db.find_requesters()\n dict_requesters = [r.to_dict() for r in requesters]\n click.echo(tabulate(dict_requesters, headers=\"keys\"))",
"def list(self, request):\n team_leaders = self.controller.retrieve_all_teams_leaders()\n serializer = data_serializers.TeamLeaderPresenterSerializer(team_leaders, many=True)\n return Response(serializer.data)"
] | [
"0.6136159",
"0.60158587",
"0.5808102",
"0.5689838",
"0.5637473",
"0.5607448",
"0.55265653",
"0.55152833",
"0.53794444",
"0.5343225",
"0.51300997",
"0.50666624",
"0.50428826",
"0.5004781",
"0.49133348",
"0.4888233",
"0.4852565",
"0.48202467",
"0.4814024",
"0.48007804",
"0.47958457",
"0.479178",
"0.47797817",
"0.47741225",
"0.47723448",
"0.4756418",
"0.47532302",
"0.4750282",
"0.4744847",
"0.4743438"
] | 0.7114685 | 0 |
Remove testers from an existing beta test. Remove testers from a beta test for the given Alexa skill. System will send access end email to each tester and remove entitlement for them. | def remove_testers_from_beta_test_v1(self, skill_id, testers_request, **kwargs):
# type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "remove_testers_from_beta_test_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'testers_request' is set
if ('testers_request' not in params) or (params['testers_request'] is None):
raise ValueError(
"Missing the required parameter `testers_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest/testers/remove'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'testers_request' in params:
body_params = params['testers_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def add_testers_to_beta_test_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"add_testers_to_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/add'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def send_beta_role_email(action, user, email_params):\r\n if action == 'add':\r\n email_params['message'] = 'add_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n elif action == 'remove':\r\n email_params['message'] = 'remove_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n else:\r\n raise ValueError(\"Unexpected action received '{}' - expected 'add' or 'remove'\".format(action))\r\n\r\n send_mail_to_student(user.email, email_params)",
"def test_teams_remove_user_from_team_v1(self):\n pass",
"def test_teams_remove_customer_from_workgroup_v1(self):\n pass",
"def test_teams_remove_user_from_team_v2(self):\n pass",
"def test_remove_from_blacklist(self):\n\n self.feature_test.add_to_blacklist(3)\n self.feature_test.remove_from_blacklist(3)\n self.assertFalse(3 in Feature(\"testing\").blacklist)",
"def teardown_test_env():\n if not keep_tmp_dirs:\n print('\\nCleaning up temporary directories...')\n shutil.rmtree(tmp_elm_dpath, ignore_errors=True)\n shutil.rmtree(tmp_elm_examples_dpath, ignore_errors=True)\n\n print('Removing conda environment used for testing...')\n sp.call('conda env remove -y -q -n {}'.format(test_env_name), shell=True, executable='/bin/bash', stdout=sp.DEVNULL)",
"def test_user_remove(self):\n\n client = app.test_client()\n\n mail = Mail(app)\n with mail.record_messages() as outbox:\n response = client.post(\n \"/user/signup/\",\n data=json.dumps(\n dict(\n username=\"admin\",\n password=\"admin\",\n email=\"[email protected]\",\n role=\"MANAGER\",\n )\n ),\n content_type=\"application/json\",\n )\n\n assert response.status_code == 200\n url_allow_login = re.search(r'(\\/user\\/signup\\/.*)', outbox[0].body).group()\n\n allow_login_response = client.get(url_allow_login, content_type=\"application/json\")\n\n assert allow_login_response.status_code == 200\n\n response = client.post(\n \"/user/signup/\",\n data=json.dumps(\n dict(\n username=\"user1\",\n password=\"passwd1\",\n email=\"[email protected]\",\n role=\"CUSTOMER\",\n )\n ),\n content_type=\"application/json\",\n )\n\n assert response.status_code == 200\n\n\n headers = {\n \"Authorization\": \"Basic %s\"\n % b64encode(b\"[email protected]:admin\").decode(\"ascii\")\n }\n delete_response = client.delete(\n \"/user/remove/\",\n data=json.dumps(dict(email=\"[email protected]\")),\n headers=headers,\n content_type=\"application/json\",\n )\n\n assert delete_response.status_code == 200\n assert delete_response.get_data().decode(\"utf-8\") == \"<h2>Deleted the user</h2>\"",
"def teardown(bot):\n bot.logger.debug(\n 'Removing extension \"Quiz\"'\n )\n bot.get_cog('Quiz').save_traking_data()\n bot.remove_cog(bot.get_cog('Quiz'))",
"def teardown_method(self):\n\n for bp_name in self.created_bp_list:\n LOG.info(\"Deleting Blueprint {}\".format(bp_name))\n runner = CliRunner()\n result = runner.invoke(cli, [\"delete\", \"bp\", bp_name])\n assert result.exit_code == 0\n\n for app_name in self.created_app_list:\n LOG.info(\"Deleting app {}\".format(app_name))\n self._delete_app(app_name)\n\n self.created_app_list = []\n self.created_bp_list = []",
"def test_remove_from_whitelist(self):\n\n self.feature_test.add_to_whitelist(3)\n self.feature_test.remove_from_whitelist(3)\n self.assertFalse(3 in Feature(\"testing\").whitelist)",
"def test_intent_classifier_del_testing_samples_all(self):\n pass",
"def test_unassign_managing_team(self):\n pass",
"def test_delete_experiment(client, users):\n login_experimenter(client)\n\n exp = ExperimentFactory()\n exp.save()\n\n exp_url = \"/experiments/\" + str(exp.id)\n\n response = client.delete(exp_url)\n assert response.status_code == 200\n assert json_success(response.data)\n\n response = client.get(\"/experiments/\")\n data = response.data.decode(response.charset)\n assert response.status_code == 200\n assert exp.name not in data",
"def test_remove_learner_specific_for_coach_pt1(self):\n self.assertTrue(self.coach2.has_perm(self.AUTH_REMOVE_LEARNER, self.learner_groups[1]))",
"def selenium_teardown():\n families_to_delete, visits_to_delete, responses_to_delete = [], [], []\n\n families_to_delete.extend(Family.objects.filter(study_id_number=59638))\n families_to_delete.extend(Family.objects.filter(study_id_number=83695))\n for f in families_to_delete:\n visits_to_delete.extend(f.visit_set.all())\n for v in visits_to_delete:\n responses_to_delete.extend(v.response_set.all())\n\n for r in responses_to_delete:\n r.delete()\n for v in visits_to_delete:\n v.delete()\n for f in families_to_delete:\n f.delete()",
"def test_remove_from_blacklist_with_string(self):\n email = '[email protected]'\n self.feature_test.add_to_blacklist(email)\n self.feature_test.remove_from_blacklist(email)\n self.assertFalse(email in Feature(\"testing\").blacklist)",
"def test_remove_supervisor_and_projects(\n student_names, project_names, supervisor_names, capacities, seed, clean\n):\n\n *_, game = make_game(\n student_names, project_names, supervisor_names, capacities, seed, clean\n )\n\n supervisor = game.supervisors[0]\n projects = supervisor.projects\n\n game._remove_player(supervisor, \"supervisors\")\n assert supervisor not in game.supervisors\n assert all(project not in game.projects for project in projects)",
"def update_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_test_body' in params:\n body_params = params['create_test_body']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"Thrown if user tries to request a new simulation while the old simulation is in progress.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def tearDown(self):\n self.testbed.deactivate()",
"def tearDown(self):\n self.testbed.deactivate()",
"def test_intent_classifier_del_testing_samples(self):\n pass",
"def test_intent_classifier_del_training_samples(self):\n pass",
"def test_handle_remove(self):\n test_user = User(\"userid\")\n test_user.permissions_level = Permissions.admin\n test_user.github_username = \"githubuser\"\n team = Team(\"BRS\", \"brs\", \"web\")\n team.github_team_id = \"githubid\"\n other_user = User(\"anotheruser\")\n other_user.github_id = \"githubID\"\n other_user.github_username = \"myuser\"\n self.db.retrieve.side_effect = [test_user, other_user,\n test_user, other_user]\n self.db.query.return_value = [team]\n team_attach = [team.get_attachment()]\n with self.app.app_context():\n self.testcommand.handle(\"team add brs ID\", user)\n resp, code = self.testcommand.handle(\"team remove brs ID\", user)\n expect = {'attachments': team_attach,\n 'text': 'Removed ' 'User from brs'}\n self.assertDictEqual(resp, expect)\n self.assertEqual(code, 200)\n self.db.store.assert_called_with(team)\n self.gh.remove_team_member.assert_called_once_with(\"myuser\",\n \"githubid\")",
"def _delete_experiments(self):\n response = self.tsp_client.fetch_experiments()\n for experiment in response.model.experiments:\n self.tsp_client.delete_experiment(experiment.UUID)\n assert response.status_code == 200",
"def test_remove_user(self):\n pass",
"def test_delete_team(self):\n pass",
"def test_remove_learner_specific_for_coach_pt2(self):\n self.assertFalse(self.coach1.has_perm(self.AUTH_REMOVE_LEARNER, self.learner_groups[1]))",
"def test_intent_classifier_del_training_samples_all(self):\n pass",
"def clean_leftovers(tests):\n for test in tests:\n test.clean()"
] | [
"0.5587914",
"0.5545338",
"0.5255967",
"0.52048516",
"0.5184266",
"0.5123379",
"0.51225615",
"0.5080352",
"0.5048985",
"0.50268716",
"0.50224525",
"0.4944203",
"0.49367338",
"0.4936156",
"0.49318147",
"0.49284622",
"0.49223253",
"0.48844877",
"0.48799017",
"0.4877814",
"0.4877814",
"0.48679084",
"0.48397014",
"0.48295352",
"0.48144057",
"0.48084557",
"0.48055318",
"0.47953993",
"0.47921976",
"0.47901198"
] | 0.73148805 | 0 |
Request feedback from testers. Request feedback from the testers in a beta test for the given Alexa skill. System will send notification emails to testers to request feedback. | def request_feedback_from_testers_v1(self, skill_id, testers_request, **kwargs):
# type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "request_feedback_from_testers_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'testers_request' is set
if ('testers_request' not in params) or (params['testers_request'] is None):
raise ValueError(
"Missing the required parameter `testers_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest/testers/requestFeedback'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'testers_request' in params:
body_params = params['testers_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_give_feedback_handler(self):\n self.signup(self.VIEWER_EMAIL, self.VIEWER_USERNAME)\n\n # Load demo exploration\n EXP_ID = '0'\n exp_services.delete_demo('0')\n exp_services.load_demo('0')\n\n # Viewer opens exploration\n self.login(self.VIEWER_EMAIL)\n exploration_dict = self.get_json(\n '%s/%s' % (feconf.EXPLORATION_INIT_URL_PREFIX, EXP_ID))\n state_name_1 = exploration_dict['exploration']['init_state_name']\n\n # Viewer gives 1st feedback\n self.post_json(\n '/explorehandler/give_feedback/%s' % EXP_ID,\n {\n 'state_name': state_name_1,\n 'feedback': 'This is a feedback message.',\n }\n )\n\n # Viewer submits answer '0'\n result_dict = self.submit_answer(EXP_ID, state_name_1, '0')\n state_name_2 = result_dict['state_name']\n\n # Viewer gives 2nd feedback\n self.post_json(\n '/explorehandler/give_feedback/%s' % EXP_ID,\n {\n 'state_name': state_name_2,\n 'feedback': 'This is a 2nd feedback message.',\n }\n )\n self.logout()",
"async def feedback(self, ctx, *, feedback):\n url = os.environ.get(\"FEEDBACK_WEBHOOK\", None)\n if url:\n webhook = Webhook.from_url(url, adapter=RequestsWebhookAdapter())\n embed = discord.Embed(description=feedback, colour=discord.Colour.teal())\n embed.set_author(name=f\"{ctx.author.name}#{ctx.author.discriminator}\", icon_url=ctx.author.avatar_url)\n embed.set_footer(text=f\"User id: {ctx.author.id}\")\n webhook.send(embed=embed)\n await ctx.send(embed=embeds.success(\"Sent the feedback!\"))\n else:\n await ctx.send(embed=embeds.error(\"This command is disabled.\"))",
"def send_beta_role_email(action, user, email_params):\r\n if action == 'add':\r\n email_params['message'] = 'add_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n elif action == 'remove':\r\n email_params['message'] = 'remove_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n else:\r\n raise ValueError(\"Unexpected action received '{}' - expected 'add' or 'remove'\".format(action))\r\n\r\n send_mail_to_student(user.email, email_params)",
"def send_reminder_to_testers_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"send_reminder_to_testers_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/sendReminder'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def check_submit_feedback(context, url):\n payload = {\n \"stack_id\": \"1234-569586048\",\n \"recommendation_type\": \"companion\",\n \"package_name\": \"blah-blah\",\n \"feedback_type\": True,\n \"ecosystem\": None\n }\n context.response = requests.post(context.coreapi_url + url,\n headers=authorization(context),\n data=payload)",
"def send_feedback(app: Flask, feedback: str) -> None:\n mail = Mail(app)\n try:\n msg = Message(\n \"Feedback\",\n sender=\"User\",\n recipients=[app.config[\"MAIL_USERNAME\"]],\n body=feedback,\n )\n mail.send(msg)\n except KeyError:\n print(\"$MAIL_USERNAME not configured\")\n print(f'Feedback: \"{feedback}\"')",
"def add_testers_to_beta_test_v1(self, skill_id, testers_request, **kwargs):\n # type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"add_testers_to_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'testers_request' is set\n if ('testers_request' not in params) or (params['testers_request'] is None):\n raise ValueError(\n \"Missing the required parameter `testers_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers/add'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'testers_request' in params:\n body_params = params['testers_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_post_request_for_team(self):\n\n usual_user = UserFactory(\n username='Usual User',\n email='[email protected]',\n )\n token = Token.objects.get(user=usual_user)\n self.client.credentials(\n HTTP_AUTHORIZATION=f'Token {token.key}')\n data = {'team': self.team.id}\n response = self.client.post(reverse('api:user-team-requests-list'), data=data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n notification = UserNotification.objects.last()\n notification_message = UserNotification.get_notification_text(\n UserNotification.TEAM_REQUEST_WAS_SENT_WITH_DEACTIVATED_EMAIL, username=usual_user.username\n )\n self.assertEqual(notification.message, notification_message)",
"def _build_and_run_request(self, user, fields):\r\n req = self._request_factory.post(\r\n \"/submit_feedback\",\r\n data=fields,\r\n HTTP_REFERER=\"test_referer\",\r\n HTTP_USER_AGENT=\"test_user_agent\",\r\n REMOTE_ADDR=\"1.2.3.4\",\r\n SERVER_NAME=\"test_server\"\r\n )\r\n req.user = user\r\n return views.submit_feedback(req)",
"def feedback(request):\n feedback = request.POST.get('feedback', None)\n if not feedback:\n return {\n 'res': 'failed'\n }\n feedback.replace('\\n', '<br>')\n user = request.user\n subject = email_templates.feedback['subject']\n content = email_templates.feedback['content'] % \\\n (user.username, feedback)\n admin_emails = [admin[1] for admin in ADMINS]\n email_users(subject, content, admin_emails,\n from_email=user.email)\n return {\n 'res': 'success'\n }",
"def _review(self, request, params, app_entity, status, **kwargs):\n\n if status == 'accepted' or status == 'rejected':\n\n default_sender = mail_dispatcher.getDefaultMailSender()\n\n if not default_sender:\n # no default sender abort\n return\n else:\n (sender_name, sender) = default_sender\n\n # construct the contents of the email\n admin_entity = app_entity.applicant\n backup_entity = app_entity.backup_admin\n\n context = {\n 'sender': sender,\n 'sender_name': sender_name,\n 'program_name': app_entity.scope.name,\n 'org_app_name': app_entity.name\n }\n\n if status == 'accepted':\n # use the accepted template and subject\n template = params['accepted_mail_template']\n context['subject'] = 'Congratulations!'\n context['HTTP_host'] = 'http://%s' % (os.environ['HTTP_HOST'])\n elif status == 'rejected':\n # use the rejected template and subject\n template = params['rejected_mail_template']\n context['subject'] = 'Thank you for your application'\n\n for to in [admin_entity, backup_entity]:\n if not to:\n continue\n\n email = accounts.denormalizeAccount(to.account).email()\n context['to'] = email\n context['to_name'] = to.name\n\n # send out the constructed email\n mail_dispatcher.sendMailFromTemplate(template, context)",
"def test_feedback_request(get_interface_params, feedback_mapping, protocol_name):\n from sail_on_client.protocol.localinterface import LocalInterface\n\n config_directory, config_name = get_interface_params\n local_interface = LocalInterface(config_name, config_directory)\n session_id = _initialize_session(local_interface, protocol_name)\n # Post results before posting\n result_files = {}\n protocol_constant = feedback_mapping[0]\n required_files = feedback_mapping[1]\n for required_file in required_files:\n result_files[required_file] = os.path.join(\n os.path.dirname(__file__), f\"test_results_{protocol_name}.1.1.1234.csv\"\n )\n local_interface.post_results(\n result_files, f\"{protocol_name}.1.1.1234\", 0, session_id\n )\n # Get feedback for detection\n response = local_interface.get_feedback_request(\n [\"n01484850_18013.JPEG\", \"n01484850_24624.JPEG\"],\n protocol_constant,\n f\"{protocol_name}.1.1.1234\",\n 0,\n session_id,\n )\n expected = os.path.join(\n local_interface.result_directory,\n f\"{session_id}.{protocol_name}.1.1.1234.0_{protocol_constant}.csv\",\n )\n assert expected == response",
"def send_mail_to_onboard_new_reviewers(user_id, category):\n\n email_subject = 'Invitation to review suggestions'\n\n email_body_template = (\n 'Hi %s,<br><br>'\n 'Thank you for actively contributing high-quality suggestions for '\n 'Oppia\\'s lessons in %s, and for helping to make these lessons better '\n 'for students around the world!<br><br>'\n 'In recognition of your contributions, we would like to invite you to '\n 'become one of Oppia\\'s reviewers. As a reviewer, you will be able to '\n 'review suggestions in %s, and contribute to helping ensure that any '\n 'edits made to lessons preserve the lessons\\' quality and are '\n 'beneficial for students.<br><br>'\n 'If you\\'d like to help out as a reviewer, please visit your '\n '<a href=\"https://www.oppia.org/creator_dashboard/\">dashboard</a>. '\n 'and set your review preferences accordingly. Note that, if you accept,'\n 'you will receive occasional emails inviting you to review incoming '\n 'suggestions by others.<br><br>'\n 'Again, thank you for your contributions to the Oppia community!<br>'\n '- The Oppia Team<br>'\n '<br>%s')\n\n if not feconf.CAN_SEND_EMAILS:\n log_new_error('This app cannot send emails to users.')\n return\n\n recipient_user_settings = user_services.get_user_settings(user_id)\n can_user_receive_email = user_services.get_email_preferences(\n user_id).can_receive_email_updates\n\n if can_user_receive_email:\n # Send email only if recipient wants to receive.\n email_body = email_body_template % (\n recipient_user_settings.username, category, category,\n EMAIL_FOOTER.value)\n _send_email(\n user_id, feconf.SYSTEM_COMMITTER_ID,\n feconf.EMAIL_INTENT_ONBOARD_REVIEWER,\n email_subject, email_body, feconf.NOREPLY_EMAIL_ADDRESS)",
"async def feedback(self, ctx, *, message):\n channel = self.bot.get_channel(config.feedback_channel) # feedback chanel in support server\n\n embed = discord.Embed(title='New Feedback!',\n description=message,\n color=self.bot.color)\n embed.add_field(name='Author',\n value=ctx.author.mention)\n embed.add_field(name='Server',\n value=ctx.guild.name)\n if ctx.message.attachments:\n embed.add_field(name='Attachments',\n value='\\n'.join(f'[{file.filename}]({file.url})' for file in ctx.message.attachments),\n inline=False)\n embed.set_footer(text='Vote on this submissions using the reactions so I can determine what to focus on!')\n\n message = await channel.send(embed=embed)\n await message.add_reaction('<:upvote:651325140663140362>')\n await message.add_reaction('<:downvote:651325233105600544>')\n await ctx.send('Thank you for your submission! '\n 'If you haven\\'t already, consider joining the support server with `support`.')",
"def _record_feedback_in_zendesk(realname, email, subject, details, tags, additional_info):\r\n zendesk_api = _ZendeskApi()\r\n\r\n additional_info_string = (\r\n \"Additional information:\\n\\n\" +\r\n \"\\n\".join(\"%s: %s\" % (key, value) for (key, value) in additional_info.items() if value is not None)\r\n )\r\n\r\n # Tag all issues with LMS to distinguish channel in Zendesk; requested by student support team\r\n zendesk_tags = list(tags.values()) + [\"LMS\"]\r\n new_ticket = {\r\n \"ticket\": {\r\n \"requester\": {\"name\": realname, \"email\": email},\r\n \"subject\": subject,\r\n \"comment\": {\"body\": details},\r\n \"tags\": zendesk_tags\r\n }\r\n }\r\n try:\r\n ticket_id = zendesk_api.create_ticket(new_ticket)\r\n except zendesk.ZendeskError as err:\r\n log.error(\"Error creating Zendesk ticket: %s\", str(err))\r\n return False\r\n\r\n # Additional information is provided as a private update so the information\r\n # is not visible to the user.\r\n ticket_update = {\"ticket\": {\"comment\": {\"public\": False, \"body\": additional_info_string}}}\r\n try:\r\n zendesk_api.update_ticket(ticket_id, ticket_update)\r\n except zendesk.ZendeskError as err:\r\n log.error(\"Error updating Zendesk ticket: %s\", str(err))\r\n # The update is not strictly necessary, so do not indicate failure to the user\r\n pass\r\n\r\n return True",
"def test_get_request(self, zendesk_mock_class, datadog_mock):\r\n req = self._request_factory.get(\"/submit_feedback\", data=self._anon_fields)\r\n req.user = self._anon_user\r\n resp = views.submit_feedback(req)\r\n self.assertEqual(resp.status_code, 405)\r\n self.assertIn(\"Allow\", resp)\r\n self.assertEqual(resp[\"Allow\"], \"POST\")\r\n # There should be absolutely no interaction with Zendesk\r\n self.assertFalse(zendesk_mock_class.mock_calls)\r\n self.assertFalse(datadog_mock.mock_calls)",
"def test_approve(self):\n\n username,userpass = self.testdata.find_account_for('toolsubmitter')\n\n self.utils.account.login_as(username,userpass)\n\n self.contribtool.approve(TOOLNAME,TOOLLICENSEDATA)",
"def test_activate_form(self, mock_sendmail):\r\n res = self.testapp.post('/api/v1/suspend',\r\n params={'email': u'[email protected]'},\r\n status=200)\r\n\r\n success = json.loads(res.body)\r\n self.assertTrue(\r\n 'message' in success,\r\n \"Should be successful with admin email address: \" + str(res))\r\n self.assertTrue(mock_sendmail.called)",
"def receive_feedback(self, winner):\r\n # No implementation needed since player is not a learning agent.\r\n pass",
"def receive_feedback(self, winner):\r\n pass",
"def receive_feedback(self, winner):\r\n pass",
"def test_launch(self):\n\n\n username,userpass = self.testdata.find_account_for('toolsubmitter')\n\n self.utils.account.login_as(username,userpass)\n\n self.contribtool.launch(TOOLNAME,username,userpass)",
"def feedback_email(email, body, name='', reply_to = ''):\r\n return _feedback_email(email, body, Email.Kind.FEEDBACK, name = name,\r\n reply_to = reply_to)",
"def _feedback_email(email, body, kind, name='', reply_to = ''):\r\n Email.handler.add_to_queue(c.user if c.user_is_loggedin else None,\r\n None, [feedback], name, email,\r\n datetime.datetime.now(),\r\n request.ip, kind, body = body,\r\n reply_to = reply_to)",
"def test_send_email_on_invite(self):\n\n league = self.create_league()\n\n season = self.create_season(league)\n team = self.create_team(season)\n\n player = self.create_player()\n\n send_user_email_on_join(player, team.id)\n\n self.assertEqual(len(mail.outbox), 1)\n\n # if testing manually:\n # import pathlib\n # pathlib.Path(\"test_email.html\").write_text(last_sent.body)",
"def batch_test_open():\n try:\n WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.CLASS_NAME, \"cdk-overlay-pane\")))\n ActionChains(browser).send_keys(Keys.ESCAPE).perform()\n except:\n print(\"No migration pop-up\")\n\n WebDriverWait(browser, 2).until(EC.element_to_be_clickable((By.LINK_TEXT, config.app_name)))\n browser.find_element_by_link_text(config.app_name).click()\n WebDriverWait(browser, 3).until(EC.presence_of_element_located((By.CLASS_NAME, 'nav-section')))\n buttons = browser.find_elements_by_class_name('nav-section')\n buttons[1].click()\n WebDriverWait(browser, 5).until(EC.visibility_of_element_located((By.XPATH, '//button[contains(text(), '\n '\"Batch testing\")]')))\n browser.find_element_by_xpath('//button[contains(text(), \"Batch testing\")]').click()",
"def send_test_email():\n from flask_mail import Message\n from website.core import mail\n\n to = ['[email protected]']\n subject = 'Test Email'\n template = '<h1>You Ok?</h1>'\n\n msg = Message(\n subject,\n recipients=to,\n html=template,\n sender=current_app.config['SECURITY_EMAIL_SENDER']\n )\n mail.send(msg)",
"def take_feedback(request):\n from_num = request.POST.get(\"From\", \"\")\n feedback = request.POST.get(\"Body\", \"\")\n logger.debug(\"Feedback from %s: '%s'\" % (from_num, feedback))\n numkey = from_num[2:]\n try:\n possiblePlayers = Player.objects.filter(cell=numkey)\n for p in possiblePlayers:\n p.feedback = p.feedback + ' ' + feedback\n p.save()\n send_thxfeedback(p)\n except:\n logger.error(\"Problem getting feedback from %s '%s'\" % (from_num, feedback), exc_info=True)\n return HttpResponse(\"\")",
"def feedback(ctx, message):\n client = ctx.obj[\"client\"]\n\n if len(message) > 0:\n message = \" \".join(message)\n else:\n message = click.edit(\n text=\"Type your message here. \" + \"Save and exit to send, or just exit to abort.\",\n require_save=True,\n )\n if not message:\n click.echo(\"Aborted.\")\n else:\n click.echo(\"Posting feedback to the Spell team\" + ellipses(ctx.obj[\"utf8\"]))\n with api_client_exception_handler():\n logger.info(\"Sending feedback\")\n client.post_feedback(message)\n click.echo(\n \"Post complete. Thanks so much for your feedback. We'll look into it right away!\"\n )",
"def support(bot, update):\n bot.send_message(chat_id=update.message.chat_id,\n text=_(\"Please, tell me what you need support with :)\"))"
] | [
"0.61726403",
"0.59941983",
"0.58779436",
"0.5732865",
"0.5594313",
"0.5457946",
"0.542713",
"0.5394584",
"0.538811",
"0.5345523",
"0.525281",
"0.5199641",
"0.5169725",
"0.5158993",
"0.5149139",
"0.50917864",
"0.50792634",
"0.5022492",
"0.500505",
"0.4993744",
"0.4993744",
"0.49568444",
"0.4937698",
"0.49282306",
"0.49231306",
"0.4923094",
"0.4888741",
"0.4876432",
"0.48734963",
"0.48575625"
] | 0.67167854 | 0 |
Send reminder to testers in a beta test. Send reminder to the testers in a beta test for the given Alexa skill. System will send invitation email to each tester and add entitlement on the acceptance. | def send_reminder_to_testers_v1(self, skill_id, testers_request, **kwargs):
# type: (str, TestersList_f8c0feda, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "send_reminder_to_testers_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'testers_request' is set
if ('testers_request' not in params) or (params['testers_request'] is None):
raise ValueError(
"Missing the required parameter `testers_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/betaTest/testers/sendReminder'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'testers_request' in params:
body_params = params['testers_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def send_beta_role_email(action, user, email_params):\r\n if action == 'add':\r\n email_params['message'] = 'add_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n elif action == 'remove':\r\n email_params['message'] = 'remove_beta_tester'\r\n email_params['email_address'] = user.email\r\n email_params['full_name'] = user.profile.name\r\n\r\n else:\r\n raise ValueError(\"Unexpected action received '{}' - expected 'add' or 'remove'\".format(action))\r\n\r\n send_mail_to_student(user.email, email_params)",
"def test_send_email_on_invite(self):\n\n league = self.create_league()\n\n season = self.create_season(league)\n team = self.create_team(season)\n\n player = self.create_player()\n\n send_user_email_on_join(player, team.id)\n\n self.assertEqual(len(mail.outbox), 1)\n\n # if testing manually:\n # import pathlib\n # pathlib.Path(\"test_email.html\").write_text(last_sent.body)",
"def send_reminder(self):\n message_contents = \"This is a reminder that your event: \" + self.event_title + \" takes place on \" + self.event_date + \" in \" + self.event_location\n subject = \"Event Reminder\"\n attendees = self.gameplanuser_set.all()\n for attendee in attendees:\n remindermessage = Message.objects.create(sender=self.event_manager, recipient=attendee, contents=message_contents)\n remindermessage.save()",
"def test_email_reminders(self, mock_tz):\n mock_tz.now.return_value = datetime(\n 2015, 2, 10, 19, 0, tzinfo=dt_timezone.utc\n )\n\n # cancellation period starts 2015/2/11 18:00\n event = baker.make_recipe(\n 'booking.future_EV',\n date=datetime(2015, 2, 12, 18, 0, tzinfo=dt_timezone.utc),\n payment_open=True,\n cost=10,\n cancellation_period=24)\n # cancellation period starts 2015/2/12 18:00\n event1 = baker.make_recipe(\n 'booking.future_EV',\n date=datetime(2015, 2, 13, 18, 0, tzinfo=dt_timezone.utc),\n payment_open=True,\n cost=10,\n cancellation_period=24)\n baker.make_recipe(\n 'booking.booking', event=event, _quantity=5,\n )\n baker.make_recipe(\n 'booking.booking', event=event1, _quantity=5,\n )\n # add user emails\n _add_user_email_addresses(Booking)\n\n management.call_command('email_reminders')\n # emails are only sent for event1\n self.assertEqual(len(mail.outbox), 5)",
"def task_send_reminder_email():\n send_reminder_email()\n logger.info(\"Sent reminder email\")",
"def test_meeting_invitation(self):\n pass",
"def test_sending_mail(self):\n\n appt_date = datetime.date.today() + datetime.timedelta(days=7) # Default for email\n reminders.Patient.objects.filter(\n pk__in=[self.test_patient.pk, self.other_patient.pk]\n ).update(next_visit=appt_date)\n confirmed = self.create_confirmed_notification(self.test_patient, appt_date)\n\n self.startRouter()\n self.router.logger.setLevel(logging.DEBUG)\n\n # run email job\n from afrims.apps.reminders.app import daily_email_callback\n daily_email_callback(self.router)\n\n self.assertEqual(len(mail.outbox), 1)\n message = mail.outbox[0]\n self.assertTrue(self.test_contact.email in message.to)\n self.stopRouter()",
"def send_reminder(self):\n pass",
"def test_integration_tests(mocker, testclient):\n if not PARAMS.get(\"token\"):\n # Pass if no token for acceptance tests\n return\n\n test_data = {}\n test_data[\"list_schedules\"] = list_schedule_tester(testclient)\n test_data[\"get_schedules\"] = get_schedule_tester(testclient, test_data[\"list_schedules\"][\"data\"][0][\"id\"])\n test_data[\"on_call\"] = get_on_call_tester(testclient, test_data[\"list_schedules\"][\"data\"][0][\"id\"])\n\n # Create alert\n alert_raw_response = create_alerts_tester(testclient)\n test_data[\"create_alert\"] = alert_raw_response\n alert_id = alert_raw_response.get(\"alertId\")\n # List alerts\n test_data[\"list_alerts\"] = list_alerts_tester(testclient)\n # Get the alert we just created\n test_data[\"get_alert\"] = get_alert_tester(testclient, alert_id)\n # Ack the same alert\n test_data[\"ack_alert\"] = ack_alert_tester(testclient, alert_id)\n # Close the same alert\n test_data[\"close_alert\"] = close_alert_tester(testclient, alert_id)\n # Delete the alert we just created\n test_data[\"delete_alert\"] = delete_alert_tester(testclient, alert_id)\n\n if os.getenv(\"GEN_TEST_DATA\"):\n # If set, test JSON added to test_data\n for k, v in test_data.items():\n with open(f\"test_data/{k}.json\", \"w\") as fh:\n json.dump(v, fh, indent=4, sort_keys=True)",
"async def inviteme(self):\r\n\r\n #Your code will go here\r\n await self.bot.say(\"Here is a link to Invite Me: http://bit.ly/TacoBot\")",
"def notify(nt_id, application, action, remedy, subj, heading):\n\n email = get_email(nt_id)\n lambda_client = boto3.client('lambda')\n messages = create_messages(application, action, remedy)\n print(email)\n email_data = {\n 'sender_mail': SENDER_EMAIL,\n 'email': email,\n 'subj': subj,\n 'heading': heading,\n 'messages': messages,\n 'region': os.environ.get(\"AWS_DEFAULT_REGION\")\n }\n invoke_email_response = lambda_client.invoke(\n FunctionName= os.environ.get(\"formatted_email\"),\n InvocationType= \"RequestResponse\",\n Payload= json.dumps(email_data)\n )\n err = checkError(invoke_email_response, \"Error sending email!\")\n if err:\n print(str(err))\n\n slack_data = {\n 'application_url': APP_URL,\n 'channel': CHANNEL,\n 'message': messages[1].rsplit(\"\\n\",5)[0],\n 'channel_id': CHANNEL_ID,\n 'nt_ids': [nt_id]\n }\n invoke_slack_response = lambda_client.invoke(\n FunctionName= os.environ.get(\"slack_message\"),\n InvocationType= \"RequestResponse\",\n Payload= json.dumps(slack_data)\n )\n err = checkError(invoke_slack_response, \"Error sending slack message!\")\n if err:\n print(str(err))",
"def test_email_additional_addresses(self):\n project = fake_clients.FakeProject(name=\"test_project\")\n\n user = fake_clients.FakeUser(\n name=\"[email protected]\", password=\"123\", email=\"[email protected]\"\n )\n\n assignments = [\n fake_clients.FakeRoleAssignment(\n scope={\"project\": {\"id\": project.id}},\n role_name=\"member\",\n user={\"id\": user.id},\n ),\n fake_clients.FakeRoleAssignment(\n scope={\"project\": {\"id\": project.id}},\n role_name=\"project_admin\",\n user={\"id\": user.id},\n ),\n ]\n\n setup_identity_cache(\n projects=[project], users=[user], role_assignments=assignments\n )\n\n url = \"/v1/actions/InviteUser\"\n headers = {\n \"project_name\": \"test_project\",\n \"project_id\": project.id,\n \"roles\": \"project_admin,member,project_mod\",\n \"username\": \"[email protected]\",\n \"user_id\": \"test_user_id\",\n \"authenticated\": True,\n }\n\n data = {\"email\": \"[email protected]\", \"roles\": [\"member\"]}\n response = self.client.post(url, data, format=\"json\", headers=headers)\n\n self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)\n self.assertEqual(response.json(), {\"notes\": [\"task created\"]})\n\n self.assertEqual(len(mail.outbox), 2)\n\n self.assertEqual(set(mail.outbox[0].to), set([\"[email protected]\"]))\n self.assertEqual(mail.outbox[0].subject, \"invite_user_to_project_additional\")\n\n # Test that the token email gets sent to the other addresses\n self.assertEqual(mail.outbox[1].to[0], \"[email protected]\")\n\n new_token = Token.objects.all()[0]\n url = \"/v1/tokens/\" + new_token.token\n data = {\"password\": \"testpassword\"}\n response = self.client.post(url, data, format=\"json\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)",
"def test_sending_mail(self):\n\n appt_date = datetime.date.today() + datetime.timedelta(days=7) # Default for email\n confirmed = self.create_confirmed_notification(self.test_patient, appt_date)\n\n # run email job\n daily_email_callback(self.router)\n\n self.assertEqual(len(mail.outbox), 1)\n message = mail.outbox[0]\n self.assertTrue(self.test_contact.email in message.to)",
"def test_inviteToEvent(self):\n # Create sample itinerary for alex for the event day\n self.json_post('/createItinerary/alex', dict(\n name = 'New Day',\n date = '2015-08-21T00:00:00.000Z'\n ))\n # Create sample itinerary for naina for the event day\n self.json_post('/createItinerary/naina', dict(\n name = 'New Day1',\n date = '2015-08-21T00:00:00.000Z'\n ))\n # Create sample itinerary for bugi for the event day\n self.json_post('/createItinerary/bugi', dict(\n name = 'New Day',\n date = '2015-08-21T00:00:00.000Z'\n ))\n # Create sample itinerary for amy for the event day\n self.json_post('/createItinerary/amy', dict(\n name = 'New Day',\n date = '2015-08-21T00:00:00.000Z'\n ))\n\n event = dict(start = '2015-08-21T11:23:00.000Z',\n end = '2015-08-21T11:25:00.000Z',\n date = '2015-08-21T00:00:00.000Z')\n rv = self.json_post('/createEvent/alex', event)\n uid = str('alex_' + event['start'] + event['end'])\n assert uid in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/bbbb', event)\n assert 'Invalid username' in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = \"invalidid\",\n invited = 'naina'\n ))\n print(rv.data)\n assert \"Event not found\" in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'bbbbb'\n ))\n assert \"Shared user does not exist\" in str(rv.data)\n\n # Share event with naina\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'naina'\n ))\n assert uid in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'naina'\n ))\n assert \"Already sent invitation\" in str(rv.data)\n\n rv = self.json_post('/createEvent/naina', dict(\n uid = uid\n ))\n assert uid in str(rv.data)\n\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'naina'\n ))\n assert \"Already shared with user\" in str(rv.data)\n\n # Share event with amy\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'amy'\n ))\n assert uid in str(rv.data)\n\n # Share event with amy\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'bugi'\n ))\n assert uid in str(rv.data)\n\n # Share event with amy\n rv = self.json_post('/inviteToEvent/alex', dict(\n uid = uid,\n invited = 'amy'\n ))\n assert \"Already sent invitation\" in str(rv.data)\n\n rv = self.json_post('/createEvent/amy', dict(\n uid = uid\n ))\n print(rv.data)\n assert uid in str(rv.data)",
"def send_reminder():\n\n name = config[\"email\"][\"name\"]\n user = config[\"email\"][\"user\"]\n subject = \"REMINDER: %s\" % sys.argv[1]\n body = sys.argv[2] if len(sys.argv) > 2 else \"\"\n email_helper.send(user, name, user, subject, body)",
"async def send_calendar_invites(andela_user, event):\n invitees = Interest.objects.filter(follower_category=event.social_event)\n invitee_list = [{'email': invitee.follower.user.email}\n for invitee in invitees]\n payload = build_event(event, invitee_list)\n\n calendar = build('calendar', 'v3', credentials=andela_user.credential)\n if settings.ENVIRONMENT == \"production\":\n calendar.events().insert(calendarId='primary', sendNotifications=True,\n body=payload).execute()",
"def test_post_request_for_team(self):\n\n usual_user = UserFactory(\n username='Usual User',\n email='[email protected]',\n )\n token = Token.objects.get(user=usual_user)\n self.client.credentials(\n HTTP_AUTHORIZATION=f'Token {token.key}')\n data = {'team': self.team.id}\n response = self.client.post(reverse('api:user-team-requests-list'), data=data)\n self.assertEqual(response.status_code, status.HTTP_201_CREATED)\n notification = UserNotification.objects.last()\n notification_message = UserNotification.get_notification_text(\n UserNotification.TEAM_REQUEST_WAS_SENT_WITH_DEACTIVATED_EMAIL, username=usual_user.username\n )\n self.assertEqual(notification.message, notification_message)",
"def test_update_email_task_send_email_to_current_user(self):\n\n user = fake_clients.FakeUser(\n name=\"[email protected]\", password=\"123\", email=\"[email protected]\"\n )\n\n setup_identity_cache(users=[user])\n\n url = \"/v1/actions/UpdateEmail\"\n headers = {\n \"project_name\": \"test_project\",\n \"project_id\": \"test_project_id\",\n \"roles\": \"project_admin,member,project_mod\",\n \"username\": \"[email protected]\",\n \"user_id\": user.id,\n \"authenticated\": True,\n }\n\n data = {\"new_email\": \"[email protected]\"}\n response = self.client.post(url, data, format=\"json\", headers=headers)\n\n self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)\n self.assertEqual(response.data, {\"notes\": [\"task created\"]})\n\n self.assertEqual(len(mail.outbox), 2)\n\n self.assertEqual(mail.outbox[0].to, [\"[email protected]\"])\n self.assertEqual(mail.outbox[0].subject, \"update_user_email_additional\")\n\n self.assertEqual(mail.outbox[1].to, [\"[email protected]\"])\n self.assertEqual(mail.outbox[1].subject, \"update_user_email_token\")\n\n new_token = Token.objects.all()[0]\n url = \"/v1/tokens/\" + new_token.token\n\n data = {\"confirm\": True}\n response = self.client.post(url, data, format=\"json\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(user.name, \"[email protected]\")\n\n self.assertEqual(len(mail.outbox), 3)",
"def test_additional_emails_role_no_email(self):\n\n project = fake_clients.FakeProject(name=\"test_project\")\n\n user = fake_clients.FakeUser(\n name=\"[email protected]\", password=\"123\", email=\"[email protected]\"\n )\n\n assignment = fake_clients.FakeRoleAssignment(\n scope={\"project\": {\"id\": project.id}},\n role_name=\"member\",\n user={\"id\": user.id},\n )\n\n setup_identity_cache(\n projects=[project], users=[user], role_assignments=[assignment]\n )\n\n url = \"/v1/actions/InviteUser\"\n headers = {\n \"project_name\": \"test_project\",\n \"project_id\": project.id,\n \"roles\": \"project_admin,member,project_mod\",\n \"username\": \"[email protected]\",\n \"user_id\": \"test_user_id\",\n \"authenticated\": True,\n }\n\n data = {\"email\": \"[email protected]\", \"roles\": [\"member\"]}\n response = self.client.post(url, data, format=\"json\", headers=headers)\n self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED)\n self.assertEqual(response.data, {\"notes\": [\"task created\"]})\n\n self.assertEqual(len(mail.outbox), 1)\n\n # Test that the token email gets sent to the other addresses\n self.assertEqual(mail.outbox[0].to[0], \"[email protected]\")\n\n new_token = Token.objects.all()[0]\n url = \"/v1/tokens/\" + new_token.token\n\n data = {\"confirm\": True, \"password\": \"1234\"}\n response = self.client.post(url, data, format=\"json\")\n self.assertEqual(response.status_code, status.HTTP_200_OK)",
"def button(update, context) -> None:\n query = update.callback_query\n status, item_id, is_waitlist = query.data.split('|||')\n invitation = EventRegistration.objects.get(pk=item_id)\n text = invitation.process_invite(status, is_waitlist)\n safe_message_send(context.bot, query.message.chat_id, text=text)\n query.answer(text)",
"async def test_online_banking_emails(app, session, stan_server, event_loop, client_id, events_stan, future):\n # Call back for the subscription\n from account_mailer.worker import cb_subscription_handler\n\n # vars\n user = factory_user_model_with_contact()\n org = factory_org_model()\n factory_membership_model(user.id, org.id)\n id = org.id\n\n events_subject = 'test_subject'\n events_queue = 'test_queue'\n events_durable_name = 'test_durable'\n with patch.object(notification_service, 'send_email', return_value=None) as mock_send:\n # register the handler to test it\n await subscribe_to_queue(events_stan,\n events_subject,\n events_queue,\n events_durable_name,\n cb_subscription_handler)\n\n # add an event to queue\n mail_details = {\n 'amount': '100.00',\n 'creditAmount': '10.00',\n 'accountId': id\n }\n await helper_add_event_to_queue(events_stan, events_subject, org_id=id,\n msg_type=MessageType.ONLINE_BANKING_UNDER_PAYMENT.value,\n mail_details=mail_details)\n\n mock_send.assert_called\n assert mock_send.call_args.args[0].get('recipients') == '[email protected]'\n assert mock_send.call_args.args[0].get('content').get(\n 'subject') == SubjectType.ONLINE_BANKING_PAYMENT_SUBJECT.value\n assert mock_send.call_args.args[0].get('attachments') is None\n assert mock_send.call_args.args[0].get('content').get('body') is not None\n\n await helper_add_event_to_queue(events_stan, events_subject, org_id=id,\n msg_type=MessageType.ONLINE_BANKING_OVER_PAYMENT.value,\n mail_details=mail_details)\n\n mock_send.assert_called\n assert mock_send.call_args.args[0].get('recipients') == '[email protected]'\n assert mock_send.call_args.args[0].get('content').get(\n 'subject') == SubjectType.ONLINE_BANKING_PAYMENT_SUBJECT.value\n assert mock_send.call_args.args[0].get('attachments') is None\n assert mock_send.call_args.args[0].get('content').get('body') is not None\n\n await helper_add_event_to_queue(events_stan, events_subject, org_id=id,\n msg_type=MessageType.ONLINE_BANKING_PAYMENT.value,\n mail_details=mail_details)\n\n mock_send.assert_called\n assert mock_send.call_args.args[0].get('recipients') == '[email protected]'\n assert mock_send.call_args.args[0].get('content').get(\n 'subject') == SubjectType.ONLINE_BANKING_PAYMENT_SUBJECT.value\n assert mock_send.call_args.args[0].get('attachments') is None\n assert mock_send.call_args.args[0].get('content').get('body') is not None",
"def test_teams_invite_member(self):\n pass",
"def test_appointment_date(self):\n # Default for email\n appt_date = datetime.date.today() + datetime.timedelta(days=7) \n self.create_confirmed_notification(self.test_patient, appt_date)\n self.create_unconfirmed_notification(self.other_patient, appt_date)\n\n # run email job\n from aremind.apps.reminders.app import daily_email_callback\n daily_email_callback(self.router)\n\n self.assertEqual(len(mail.outbox), 1)\n message = mail.outbox[0]\n self.assertPatientInMessage(message, self.test_patient)\n self.assertPatientInMessage(message, self.other_patient)\n self.assertPatientNotInMessage(message, self.unrelated_patient)",
"async def test_account_team_modified(app, session, stan_server, event_loop, client_id, events_stan, future):\n # Call back for the subscription\n from account_mailer.worker import cb_subscription_handler\n\n # vars\n user = factory_user_model_with_contact()\n org = factory_org_model()\n factory_membership_model(user.id, org.id)\n id = org.id\n\n events_subject = 'test_subject'\n events_queue = 'test_queue'\n events_durable_name = 'test_durable'\n with patch.object(notification_service, 'send_email', return_value=None) as mock_send:\n # register the handler to test it\n await subscribe_to_queue(events_stan,\n events_subject,\n events_queue,\n events_durable_name,\n cb_subscription_handler)\n\n # add an event to queue\n mail_details = {\n 'accountId': id,\n }\n await helper_add_event_to_queue(events_stan, events_subject, org_id=id,\n msg_type=MessageType.TEAM_MEMBER_INVITED.value, mail_details=mail_details)\n\n mock_send.assert_called\n assert mock_send.call_args.args[0].get('recipients') == '[email protected]'\n assert mock_send.call_args.args[0].get('content').get('subject') == SubjectType.TEAM_MODIFIED_SUBJECT.value\n assert mock_send.call_args.args[0].get('attachments') is None\n assert mock_send.call_args.args[0].get('content').get('body') is not None",
"def send_test_email():\n from flask_mail import Message\n from website.core import mail\n\n to = ['[email protected]']\n subject = 'Test Email'\n template = '<h1>You Ok?</h1>'\n\n msg = Message(\n subject,\n recipients=to,\n html=template,\n sender=current_app.config['SECURITY_EMAIL_SENDER']\n )\n mail.send(msg)",
"def test_only_send_one_email_to_studio(self, mock_tz):\n mock_tz.now.return_value = datetime(2015, 2, 10, 10, tzinfo=dt_timezone.utc)\n for i in range(5):\n baker.make_recipe(\n 'booking.booking', event=self.event,\n status='OPEN', paid=False,\n payment_confirmed=False,\n user__email=\"unpaid_user{}@test.com\".format(i),\n date_booked= datetime(2015, 2, 9, tzinfo=dt_timezone.utc),\n warning_sent=True,\n date_warning_sent= datetime(2015, 2, 9, 2, tzinfo=dt_timezone.utc),\n )\n\n management.call_command('cancel_unpaid_bookings')\n # emails are sent to user per cancelled booking (6) and studio once\n # for all cancelled bookings\n unpaid_booking = Booking.objects.get(id=self.unpaid.id)\n self.assertEqual(len(mail.outbox), 7)\n self.assertEqual(\n unpaid_booking.status, 'CANCELLED', unpaid_booking.status\n )\n self.assertEqual(\n Booking.objects.filter(status='CANCELLED').count(), 6\n )\n cancelled_booking_emails = [\n [booking.user.email] for booking\n in Booking.objects.filter(status='CANCELLED')\n ]\n all_emails = cancelled_booking_emails + [[settings.DEFAULT_STUDIO_EMAIL]]\n self.assertEqual(\n sorted(all_emails),\n sorted([email.to for email in mail.outbox])\n )",
"def test_invitation_email(self):\n queryset = models.Invitation.objects.filter(id=self.invitation.id)\n self.admin_instance.send_new_activation_email(self.some_request, queryset)\n # check whether there is a mail in the outbox\n self.assertEqual(len(mail.outbox), 1)\n # check subject\n self.assertEqual(\n mail.outbox[0].subject,\n \"Er is een account voor u aangemaakt op sso.lizard.net\",\n )\n self.assertEqual(mail.outbox[0].to, [\"[email protected]\"])\n # check mail starts with 'Hallo Reinout,'\n self.assertTrue(mail.outbox[0].body.startswith(\"Hallo Reinout,\"))",
"def test_invited(self) -> None:\n\n self._perform_background_initial_update()\n\n u1 = self.register_user(\"u1\", \"pass\")\n u1token = self.login(\"u1\", \"pass\")\n r1 = self.helper.create_room_as(u1, tok=u1token)\n\n u2 = self.register_user(\"u2\", \"pass\")\n\n r1stats_ante = self._get_current_stats(\"room\", r1)\n assert r1stats_ante is not None\n\n self.helper.invite(r1, u1, u2, tok=u1token)\n\n r1stats_post = self._get_current_stats(\"room\", r1)\n assert r1stats_post is not None\n\n self.assertEqual(\n r1stats_post[\"current_state_events\"] - r1stats_ante[\"current_state_events\"],\n 1,\n )\n self.assertEqual(\n r1stats_post[\"invited_members\"] - r1stats_ante[\"invited_members\"], +1\n )",
"def test_appointment_date(self):\n appt_date = datetime.date.today() + datetime.timedelta(days=7) # Default for email\n reminders.Patient.objects.filter(\n pk__in=[self.test_patient.pk, self.other_patient.pk]\n ).update(next_visit=appt_date)\n confirmed = self.create_confirmed_notification(self.test_patient, appt_date)\n unconfirmed = self.create_unconfirmed_notification(self.other_patient, appt_date)\n\n self.startRouter()\n self.router.logger.setLevel(logging.DEBUG)\n\n # run email job\n from afrims.apps.reminders.app import daily_email_callback\n daily_email_callback(self.router)\n\n self.assertEqual(len(mail.outbox), 1)\n message = mail.outbox[0]\n self.assertPatientInMessage(message, self.test_patient)\n self.assertPatientInMessage(message, self.other_patient)\n self.assertPatientNotInMessage(message, self.unrelated_patient)\n self.stopRouter()",
"def test_changing_date(self):\n days = 2\n appt_date = datetime.date.today() + datetime.timedelta(days=days)\n confirmed = self.create_confirmed_notification(self.test_patient,\n appt_date)\n unconfirmed = self.create_unconfirmed_notification(self.other_patient,\n appt_date)\n\n # run email job\n from aremind.apps.reminders.app import daily_email_callback\n daily_email_callback(self.router, days=days)\n\n self.assertEqual(len(mail.outbox), 1)\n message = mail.outbox[0]\n self.assertPatientInMessage(message, self.test_patient)\n self.assertPatientInMessage(message, self.other_patient)\n self.assertPatientNotInMessage(message, self.unrelated_patient)"
] | [
"0.6361374",
"0.613323",
"0.5981242",
"0.5869986",
"0.57592195",
"0.5738662",
"0.56054765",
"0.5593407",
"0.5553443",
"0.5533721",
"0.55045986",
"0.54965943",
"0.54770523",
"0.54706186",
"0.54577374",
"0.5449847",
"0.5438888",
"0.53768194",
"0.5370345",
"0.53675",
"0.5366505",
"0.5347229",
"0.5342464",
"0.53375024",
"0.5334985",
"0.5334066",
"0.5315657",
"0.52930737",
"0.52808774",
"0.52807724"
] | 0.6360512 | 1 |
Gets a specific certification resource. The response contains the review tracking information for a skill to show how much time the skill is expected to remain under review by Amazon. Once the review is complete, the response also contains the outcome of the review. Old certifications may not be available, however any ongoing certification would always give a response. If the certification is unavailable the result will return a 404 HTTP status code. | def get_certification_review_v1(self, skill_id, certification_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, CertificationResponse_97fdaad, BadRequestError_f854b05]
operation_name = "get_certification_review_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'certification_id' is set
if ('certification_id' not in params) or (params['certification_id'] is None):
raise ValueError(
"Missing the required parameter `certification_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/certifications/{certificationId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'certification_id' in params:
path_params['certificationId'] = params['certification_id']
query_params = [] # type: List
header_params = [] # type: List
if 'accept_language' in params:
header_params.append(('Accept-Language', params['accept_language']))
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.certification.certification_response.CertificationResponse", status_code=200, message="Successfully retrieved skill certification information."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error e.g. if any request parameter is invalid like certification Id or pagination token etc. If the maxResults is not in the range of 1 to 50, it also qualifies for this error. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceeded the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.certification.certification_response.CertificationResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def request_cert():\n\n api_request = shallow_copy(props)\n\n for key in ['ServiceToken', 'Region', 'Tags', 'Route53RoleArn']:\n api_request.pop(key, None)\n\n if 'ValidationMethod' in props:\n if props['ValidationMethod'] == 'DNS':\n\n # Check that we have all the hosted zone information we need to validate\n # before we create the certificate\n for name in set([props['DomainName']] + props.get('SubjectAlternativeNames', [])):\n get_zone_for(name)\n\n del api_request['DomainValidationOptions']\n\n e['PhysicalResourceId'] = acm.request_certificate(\n IdempotencyToken=i_token,\n **api_request\n )['CertificateArn']\n add_tags()",
"def cert_challenge_http(self) -> 'outputs.CertHttpChallengeResponse':\n return pulumi.get(self, \"cert_challenge_http\")",
"def cert_info(user, course):\r\n if not course.may_certify():\r\n return {}\r\n\r\n return _cert_info(user, course, certificate_status_for_student(user, course.id))",
"def fusion_api_get_certificate_info(self, uri=None, api=None, param='', headers=None):\n param = '/certificates/https/'\n return self.ic.get(uri=uri, api=api, headers=headers, param=param)",
"def get_certifications_list_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListCertificationsResponse_f2a417c6]\n operation_name = \"get_certifications_list_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/certifications'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.certification.list_certifications_response.ListCertificationsResponse\", status_code=200, message=\"Returns list of certifications for the skillId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. if any request parameter is invalid like certification Id or pagination token etc. If the maxResults is not in the range of 1 to 50, it also qualifies for this error. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.certification.list_certifications_response.ListCertificationsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_certificate(self, cert_id):\r\n return self.ssl.getObject(id=cert_id)",
"def find_certificate(p): # find_certificate(props, /)\n\n for page in acm.get_paginator('list_certificates').paginate():\n for certificate in page['CertificateSummaryList']:\n log_info(certificate)\n\n if p['DomainName'].lower() == certificate['DomainName']:\n tags = {tag['Key']: tag['Value'] for tag in\n acm.list_tags_for_certificate(**{'CertificateArn': certificate['CertificateArn']})['Tags']}\n\n if (tags.get('cloudformation:' + 'logical-id') == e['LogicalResourceId'] and\n tags.get('cloudformation:' + 'stack-id') == e['StackId'] and\n tags.get('cloudformation:' + 'properties') == hash_func(p)\n ):\n return certificate['CertificateArn']",
"def fusion_api_get_certificate_status(self, api=None, headers=None):\n return self.certificate_status.get(api, headers)",
"def request_certificate(request):\r\n if request.method == \"POST\":\r\n if request.user.is_authenticated():\r\n xqci = XQueueCertInterface()\r\n username = request.user.username\r\n student = User.objects.get(username=username)\r\n course_key = SlashSeparatedCourseKey.from_deprecated_string(request.POST.get('course_id'))\r\n course = modulestore().get_course(course_key, depth=2)\r\n\r\n status = certificate_status_for_student(student, course_key)['status']\r\n if status in [CertificateStatuses.unavailable, CertificateStatuses.notpassing, CertificateStatuses.error]:\r\n logger.info('Grading and certification requested for user {} in course {} via /request_certificate call'.format(username, course_key))\r\n status = xqci.add_cert(student, course_key, course=course)\r\n return HttpResponse(json.dumps({'add_status': status}), mimetype='application/json')\r\n return HttpResponse(json.dumps({'add_status': 'ERRORANONYMOUSUSER'}), mimetype='application/json')",
"def get_ssl_certificate():",
"def cert_status(self) -> str:\n return pulumi.get(self, \"cert_status\")",
"def get_ssl_certificate() :",
"def get_ssl_certificates_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, SSLCertificatePayload_97891902]\n operation_name = \"get_ssl_certificates_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/sslCertificateSets/~latest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.ssl_certificate_payload.SSLCertificatePayload\", status_code=200, message=\"Response contains the latest version of the ssl certificates.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.ssl_certificate_payload.SSLCertificatePayload\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_certificate_from_arn(self, certificate_arn):\n with stats.timer('get_certificate_from_arn'):\n client = confidant.clients.get_boto_client('acm-pca')\n # When a certificate is issued, it may take a while before it's\n # available via get_certificate. We need to keep retrying until it's\n # fully issued.\n i = 0\n while True:\n try:\n response = client.get_certificate(\n CertificateAuthorityArn=self.settings['arn'],\n CertificateArn=certificate_arn,\n )\n break\n except client.exceptions.RequestInProgressException:\n # Sleep for a maximum of 10 seconds\n if i >= 50:\n raise\n logger.debug(\n 'Sleeping in get_certificate_from_arn for {}'.format(\n certificate_arn,\n )\n )\n time.sleep(.200)\n i = i + 1\n return {\n 'certificate': response['Certificate'],\n 'certificate_chain': response['CertificateChain'],\n }",
"def cert(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"cert\")",
"def cert(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"cert\")",
"def fusion_api_get_appliance_certificate(self, api=None, headers=None):\n return self.wsc.get(api=api, headers=headers)",
"def get_certificate(self, url):\n bearer = 'Authorization: Bearer '+str(self.exchanged_token).split('\\n', 1)[0]\n data = json.dumps({\"service_id\": \"x509\"})\n\n headers = StringIO()\n buffers = StringIO()\n\n c = pycurl.Curl()\n c.setopt(pycurl.URL, url)\n c.setopt(pycurl.HTTPHEADER, [bearer, 'Content-Type: application/json'])\n c.setopt(pycurl.POST, 1)\n c.setopt(pycurl.POSTFIELDS, data)\n c.setopt(c.WRITEFUNCTION, buffers.write)\n c.setopt(c.HEADERFUNCTION, headers.write)\n c.setopt(c.VERBOSE, True)\n\n try:\n c.perform()\n status = c.getinfo(c.RESPONSE_CODE)\n c.close()\n body = buffers.getvalue()\n\n if str(status) != \"303\" :\n self.log.error(\"On \\\"get redirect curl\\\": %s , http error: %s \" % (body, str(status)))\n return False \n except pycurl.error, error:\n errno, errstr = error\n self.log.info('An error occurred: %s' % errstr)\n return False\n \n redirect = self.tts\n for item in headers.getvalue().split(\"\\n\"):\n if \"location\" in item:\n redirect = redirect + item.strip().replace(\"location: \", \"\")\n\n headers = {'Authorization': 'Bearer ' + self.exchanged_token.strip()}\n response = requests.get(redirect, headers=headers)\n\n try:\n response.raise_for_status()\n except requests.exceptions.HTTPError as e:\n # Whoops it wasn't a 200\n self.log.error(\"get_certificate() Error: %s \" %str(e))\n return False\n\n with open('/tmp/output.json', 'w') as outf:\n outf.write(response.content)\n else:\n self.log.error(\"No location in redirect response\")\n\n return True",
"def fusion_api_get_appliance_certificate(self, api=None, headers=None):\n return self.appliance_certificate.get(api, headers)",
"def ssl_cert(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"ssl_cert\")",
"def certificate_auth():\r\n url = 'https://www.12306.cn'\r\n response = requests.get(url, verify=False)\r\n print(response.status_code)\r\n print(response.text)",
"def get_certificate(self, cert_name, callback=None):\n # TODO: get certificate from DHT (alternative to getting from disk).\n# _log.debug(\"get_certificate:\\n\\tmy_node_name={}\\n\\tcert_name={}\\n\\tcallback={}\".format(self.node_name, cert_name, callback))\n try:\n cert = self.get_certificate_locally(cert_name)\n if cert and callback:\n callback(certstring=cert)\n elif cert:\n return cert\n else:\n try:\n self.node.storage.get_index(['certificate',cert_name],\n cb=CalvinCB(self._get_certificate_from_storage_cb,\n callback=callback))\n except Exception as err:\n _log.debug(\"Certificate could not be found in storage, err={}\".format(err))\n raise\n except Exception as err:\n _log.debug(\"Failed searching for certificate locally, cert_name={}, err={}\".format(cert_name, err))",
"def certificate(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"certificate\")",
"def certificate(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"certificate\")",
"def certificate(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"certificate\")",
"def certificate(self) -> pulumi.Output[Optional[str]]:\n return pulumi.get(self, \"certificate\")",
"def get(resource_name, id, opts=None, arn=None, certificate=None, certificate_authority_configuration=None, certificate_chain=None, certificate_signing_request=None, enabled=None, not_after=None, not_before=None, permanent_deletion_time_in_days=None, revocation_configuration=None, serial=None, status=None, tags=None, type=None):\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = dict()\n __props__[\"arn\"] = arn\n __props__[\"certificate\"] = certificate\n __props__[\"certificate_authority_configuration\"] = certificate_authority_configuration\n __props__[\"certificate_chain\"] = certificate_chain\n __props__[\"certificate_signing_request\"] = certificate_signing_request\n __props__[\"enabled\"] = enabled\n __props__[\"not_after\"] = not_after\n __props__[\"not_before\"] = not_before\n __props__[\"permanent_deletion_time_in_days\"] = permanent_deletion_time_in_days\n __props__[\"revocation_configuration\"] = revocation_configuration\n __props__[\"serial\"] = serial\n __props__[\"status\"] = status\n __props__[\"tags\"] = tags\n __props__[\"type\"] = type\n return CertificateAuthority(resource_name, opts=opts, __props__=__props__)",
"def _cert_info(user, course, cert_status):\r\n # simplify the status for the template using this lookup table\r\n template_state = {\r\n CertificateStatuses.generating: 'generating',\r\n CertificateStatuses.regenerating: 'generating',\r\n CertificateStatuses.downloadable: 'ready',\r\n CertificateStatuses.notpassing: 'notpassing',\r\n CertificateStatuses.restricted: 'restricted',\r\n }\r\n\r\n default_status = 'processing'\r\n\r\n default_info = {'status': default_status,\r\n 'show_disabled_download_button': False,\r\n 'show_download_url': False,\r\n 'show_survey_button': False,\r\n }\r\n\r\n if cert_status is None:\r\n return default_info\r\n\r\n status = template_state.get(cert_status['status'], default_status)\r\n\r\n d = {'status': status,\r\n 'show_download_url': status == 'ready',\r\n 'show_disabled_download_button': status == 'generating',\r\n 'mode': cert_status.get('mode', None)}\r\n\r\n if (status in ('generating', 'ready', 'notpassing', 'restricted') and\r\n course.end_of_course_survey_url is not None):\r\n d.update({\r\n 'show_survey_button': True,\r\n 'survey_url': process_survey_link(course.end_of_course_survey_url, user)})\r\n else:\r\n d['show_survey_button'] = False\r\n\r\n if status == 'ready':\r\n if 'download_url' not in cert_status:\r\n log.warning(\"User %s has a downloadable cert for %s, but no download url\",\r\n user.username, course.id)\r\n return default_info\r\n else:\r\n d['download_url'] = cert_status['download_url']\r\n\r\n if status in ('generating', 'ready', 'notpassing', 'restricted'):\r\n if 'grade' not in cert_status:\r\n # Note: as of 11/20/2012, we know there are students in this state-- cs169.1x,\r\n # who need to be regraded (we weren't tracking 'notpassing' at first).\r\n # We can add a log.warning here once we think it shouldn't happen.\r\n return default_info\r\n else:\r\n d['grade'] = cert_status['grade']\r\n\r\n return d",
"def request_cert(session, domain_name, validation_domain):\n if session is None:\n return None\n\n client = session.client('acm')\n validation_options = [\n {\n 'DomainName': domain_name,\n 'ValidationDomain': validation_domain\n },\n ]\n response = client.request_certificate(DomainName=domain_name,\n DomainValidationOptions=validation_options)\n return response",
"def get(resource, **kwargs):\n\t#print(_endpoint(resource, 'GET'))\n\tresp = requests.get(\n\t\t_endpoint(resource, 'GET'),\n\t\tparams=_jsonify_dict_values(kwargs),\n\t\tverify=SERVER_CERT\n\t)\n\tresp.raise_for_status()\n\treturn resp.json()"
] | [
"0.5620197",
"0.56174594",
"0.5616601",
"0.55258906",
"0.5468792",
"0.5397545",
"0.5397481",
"0.5392902",
"0.53675646",
"0.53584164",
"0.5347854",
"0.5339154",
"0.5308388",
"0.5274523",
"0.52729917",
"0.52729917",
"0.52595717",
"0.5217682",
"0.51913583",
"0.51272845",
"0.51179594",
"0.5111789",
"0.51098186",
"0.51098186",
"0.51098186",
"0.5102435",
"0.50975174",
"0.5091737",
"0.5072655",
"0.5038519"
] | 0.7220724 | 0 |
Get list of all certifications available for a skill, including information about past certifications and any ongoing certification. The default sort order is descending on skillSubmissionTimestamp for Certifications. | def get_certifications_list_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListCertificationsResponse_f2a417c6]
operation_name = "get_certifications_list_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/certifications'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.certification.list_certifications_response.ListCertificationsResponse", status_code=200, message="Returns list of certifications for the skillId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error e.g. if any request parameter is invalid like certification Id or pagination token etc. If the maxResults is not in the range of 1 to 50, it also qualifies for this error. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceeded the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.certification.list_certifications_response.ListCertificationsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def getCertifications(self):\n return [c for c in self.objectValues('InstrumentCertification') if c]",
"def getValidCertifications(self):\n certs = []\n today = date.today()\n for c in self.getCertifications():\n validfrom = c.getValidFrom() if c else None\n validto = c.getValidTo() if validfrom else None\n if not validfrom or not validto:\n continue\n validfrom = validfrom.asdatetime().date()\n validto = validto.asdatetime().date()\n if (today >= validfrom and today <= validto):\n certs.append(c)\n return certs",
"def show_all_certifications():\n if not g.user:\n flash(\"Please login to access\", \"danger\")\n return redirect(\"/\")\n if g.user.is_admin == False:\n flash (\"Unauthorized\", \"danger\")\n return redirect(\"/login\")\n\n \n certs = Cert.query.all()\n ## all possible certs...\n \n return render_template(\"certs_display.html\", certs = certs)",
"def my_courses(self, signer):\n return list(chain(*[p.user_courses(signer=signer) for p in self.providers]))",
"def extract_courses():\n if settings.XPRO_COURSES_API_URL:\n return requests.get(settings.XPRO_COURSES_API_URL, timeout=20).json()\n return []",
"def cert_chains(self) -> 'outputs.CertificateChainsResponse':\n return pulumi.get(self, \"cert_chains\")",
"def certificates(self):\n if self.user.is_superuser:\n return Certificate.objects.all()\n else:\n return Certificate.objects.filter(licensee__in=self.licensees.all())",
"def getLatestValidCertification(self):\n cert = None\n lastfrom = None\n lastto = None\n for c in self.getCertifications():\n validfrom = c.getValidFrom() if c else None\n validto = c.getValidTo() if validfrom else None\n if not validfrom or not validto:\n continue\n validfrom = validfrom.asdatetime().date()\n validto = validto.asdatetime().date()\n if not cert \\\n or validto > lastto \\\n or (validto == lastto and validfrom > lastfrom):\n cert = c\n lastfrom = validfrom\n lastto = validto\n return cert",
"def list_authorities():\n try:\n certs = client().certificates.get_authorities()\n if not certs:\n logger.info(\n 'ctl:cert:authorities', 'No certificate authorities found'\n )\n return\n llen = len(sorted(certs, key=lambda x: len(x[\"id\"]))[-1][\"id\"])\n for x in sorted(certs, key=lambda x: x[\"id\"]):\n click.echo(\n click.style(\n '{name: <{fill}}'.format(name=x[\"id\"], fill=llen + 3),\n fg=\"white\", bold=True) + \"Expires \" +\n click.style(x[\"expiry\"].strftime(\"%c\"), fg=\"yellow\")\n )\n except Exception as e:\n raise CLIException(str(e))",
"def getCoursesList(self, pageSize=100):\n results = self.service.courses().list(pageSize=pageSize).execute()\n self.courses = results.get('courses', [])\n if not self.courses:\n return []\n return self.courses # Might not have to return self.courses, but it's useful for now",
"def get_sorted_topics_courses(self):\n return sorted(self.topics_courses, key=lambda course_topic: course_topic.stats.score, reverse=True)",
"def get_courses(self):\r\n\r\n return self.def_ms.get_courses()",
"def _get_tls_cert_details(url, domain_validator):\n result, x509 = domain_validator.in_abuse_list(url)\n cert_df = pd.DataFrame()\n if x509 is not None:\n cert_df = pd.DataFrame(\n {\n \"SN\": [x509.serial_number],\n \"Subject\": [[(i.value) for i in x509.subject]],\n \"Issuer\": [[(i.value) for i in x509.issuer]],\n \"Expired\": [x509.not_valid_after],\n \"InAbuseList\": result,\n }\n )\n return cert_df",
"def get_courses(self, depth=0):\r\n return self.courses.values()",
"def get_sorted_courses(self, include_unscheduled=False) -> List[Course]:\n return sorted(\n filter(\n lambda c: c.time is not None or include_unscheduled, self.get_courses()\n ),\n key=lambda c: (0, 0) if not c.time else (c.weekday(), c.time.start),\n )",
"def get_ssl_certificates_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, SSLCertificatePayload_97891902]\n operation_name = \"get_ssl_certificates_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/sslCertificateSets/~latest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.ssl_certificate_payload.SSLCertificatePayload\", status_code=200, message=\"Response contains the latest version of the ssl certificates.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.ssl_certificate_payload.SSLCertificatePayload\")\n\n if full_response:\n return api_response\n return api_response.body",
"def certificates(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:\n return pulumi.get(self, \"certificates\")",
"def certificates(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:\n return pulumi.get(self, \"certificates\")",
"def challenges(self):\n return [gc.challenge for gc in GrandChallenge.objects.filter(round=self.round_number).order_by('challenge__status')]",
"async def all_skills_data(self) -> AllSkillsData:\n return AllSkillsData(**await self.get(\"/skill/all\"))",
"def get_runtime_certificate_chain_as_list(self):\n # TODO: make for flexible to support intermediate certificates\n# _log.debug(\"get_runtime_certificate_chain_as_list: my_node_name={}\".format(self.node_name))\n cert_chain_list_of_strings = []\n cert_chain_list_of_x509 = []\n try:\n cert_chain_str = self.get_runtime_certificate_chain_as_string()\n cert_part = cert_chain_str.split(BEGIN_CRT_LINE)\n cert_chain_list_of_strings = []\n cert_chain_list_of_strings.append(\"{}{}\".format(BEGIN_CRT_LINE, cert_part[1]))\n cert_chain_list_of_strings.append(\"{}{}\".format(BEGIN_CRT_LINE, cert_part[2]))\n cert_chain_list_of_x509.append(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,\n cert_chain_list_of_strings[0]))\n cert_chain_list_of_x509.append(OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,\n cert_chain_list_of_strings[1]))\n return cert_chain_list_of_strings, cert_chain_list_of_x509\n except Exception:\n _log.debug(\"Failed to get the runtimes certificate chain\")\n raise",
"def get_certification_review_v1(self, skill_id, certification_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, CertificationResponse_97fdaad, BadRequestError_f854b05]\n operation_name = \"get_certification_review_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'certification_id' is set\n if ('certification_id' not in params) or (params['certification_id'] is None):\n raise ValueError(\n \"Missing the required parameter `certification_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/certifications/{certificationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'certification_id' in params:\n path_params['certificationId'] = params['certification_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n if 'accept_language' in params:\n header_params.append(('Accept-Language', params['accept_language']))\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.certification.certification_response.CertificationResponse\", status_code=200, message=\"Successfully retrieved skill certification information.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. if any request parameter is invalid like certification Id or pagination token etc. If the maxResults is not in the range of 1 to 50, it also qualifies for this error. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.certification.certification_response.CertificationResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def build_certifications(data_dir, output_dir):\n return yamls_to_certification.create_yaml_certifications(\n data_dir=data_dir, output_dir=output_dir\n )",
"def all_skill_list(self):\n data_skill_list = self.data_skill_list()\n self.skill_list = []\n for i in range(len(self.data_profile)):\n if 'skills' in self.data_profile[i].keys():\n for j in range(len(self.data_profile[i]['skills'])):\n for skills in self.data_profile[i]['skills'][j]['skills']:\n if skills['title'] in data_skill_list:\n self.skill_list.append(skills['title'])\n return",
"def credential_list():\n rows = safeisland.list_certificates()\n certs = []\n for row in rows:\n# certs.append(row[\"cert\"])\n certs.append({\"uuid\": row[\"uuid\"], \"cert\": row[\"cert\"]})\n\n return {\"payload\": certs}",
"def loaded_certificates(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['LoadedCertificateArgs']]]]:\n return pulumi.get(self, \"loaded_certificates\")",
"def fetch_x509_context(self) -> X509Context:",
"def certificates(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['CertificateReferenceArgs']]]]:\n return pulumi.get(self, \"certificates\")",
"def list_certificates_request(self, vault_name: str, limit: int, offset: int) -> list[dict]:\n url = f'https://{vault_name}{self.azure_cloud.suffixes.keyvault_dns}/certificates'\n\n response = self.http_request(\n 'GET', full_url=url, resource=self.get_vault_resource())\n\n return self.get_entities_independent_of_pages(response, limit, offset, self.get_vault_resource())",
"def upcoming_courses(aud):\n \n courses = [c for c in aud.all_courses() if c.grade == u\"*\"]\n return [c.number.replace(\"-\", \"\") for c in courses]"
] | [
"0.6214057",
"0.588732",
"0.5573819",
"0.5352922",
"0.5189842",
"0.5186954",
"0.51683956",
"0.51323736",
"0.4976819",
"0.49328792",
"0.49286246",
"0.4897881",
"0.48967645",
"0.4860845",
"0.48502275",
"0.47953802",
"0.47909367",
"0.47909367",
"0.4778207",
"0.4773883",
"0.4765669",
"0.476222",
"0.47249037",
"0.47122627",
"0.46923083",
"0.4691004",
"0.46875307",
"0.46864155",
"0.4620833",
"0.4594898"
] | 0.64700496 | 0 |
Deletes an existing experiment for a skill. | def delete_experiment_v1(self, skill_id, experiment_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "delete_experiment_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'experiment_id' is set
if ('experiment_id' not in params) or (params['experiment_id'] is None):
raise ValueError(
"Missing the required parameter `experiment_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'experiment_id' in params:
path_params['experimentId'] = params['experiment_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="DELETE",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def delete(ctx):\n user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n ctx.obj.get('experiment'))\n if not click.confirm(\"Are sure you want to delete experiment `{}`\".format(_experiment)):\n click.echo('Existing without deleting experiment.')\n sys.exit(1)\n\n try:\n response = PolyaxonClient().experiment.delete_experiment(\n user, project_name, _experiment)\n # Purge caching\n ExperimentManager.purge()\n except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n Printer.print_error('Could not delete experiment `{}`.'.format(_experiment))\n Printer.print_error('Error message `{}`.'.format(e))\n sys.exit(1)\n\n if response.status_code == 204:\n Printer.print_success(\"Experiment `{}` was delete successfully\".format(_experiment))",
"def delete_experiment(self, exp_id):\n folder = self.um.experiment_path(exp_id)\n self.um.delete_folder(folder)\n\n return \"OK\"",
"def remove_experiment(self, experiment_name):\n self.cur.execute(\n \"\"\"\n DELETE FROM experiments WHERE experiment_name=%(experiment_name)s;\n DELETE FROM performance WHERE experiment_name=%(experiment_name)s;\n DELETE FROM in_process WHERE experiment_name=%(experiment_name)s;\n \"\"\",\n {\n 'experiment_name': experiment_name\n }\n )\n if self.status_message:\n self.return_status('DELETE')",
"def delete_experiment_and_alternatives(self, experiment):\n if not experiment:\n return\n\n # First delete from datastore\n experiment.delete()\n experiment.reset_counters()\n\n for alternative in self.get_alternatives(experiment.name):\n alternative.delete()\n\n self.remove_from_cache(experiment)",
"def destroy(self, request, pk=None):\n exp = Experiment.objects.get(pk=pk)\n serializer = None\n exp.delete()\n return send_response(request.method, serializer)",
"def delete_skill(id, skill):\n with app.app_context():\n user = User.query.get(id)\n if user is None:\n return \"User not found\", 404\n skill_db = Skill.query.filter_by(name=skill).first()\n if skill_db is None:\n return \"Skill not found\", 404\n user.skills.remove(skill_db)\n user_response = UsersResponse(\n users=[\n {\n \"id\": user.id,\n \"name\": user.name,\n \"skills\": [skill.name for skill in user.skills]\n }\n ]\n )\n db.session.commit()\n return user_response.json(), 200",
"def test_delete_experiment(client, users):\n login_experimenter(client)\n\n exp = ExperimentFactory()\n exp.save()\n\n exp_url = \"/experiments/\" + str(exp.id)\n\n response = client.delete(exp_url)\n assert response.status_code == 200\n assert json_success(response.data)\n\n response = client.get(\"/experiments/\")\n data = response.data.decode(response.charset)\n assert response.status_code == 200\n assert exp.name not in data",
"def _delete_experiments(self):\n response = self.tsp_client.fetch_experiments()\n for experiment in response.model.experiments:\n self.tsp_client.delete_experiment(experiment.UUID)\n assert response.status_code == 200",
"def delete(parameters, session):\n from Modules.Classes.ExperimentalScenario import ExperimentalScenario\n # Received --> [id_exeriment]\n # Retrieve all scenarios associated with target experiment\n exp_sc = session.query(ExperimentalScenario).filter(ExperimentalScenario.experiment_id == parameters[0]).all()\n for item in exp_sc:\n # Retrieve all ExperimentalScenarioPattern association for current experimental scenario\n exp_scenarios_pat = session.query(ExperimentalScenarioPattern).filter(and_(\n ExperimentalScenarioPattern.experimental_scenario_id == item.id,\n ExperimentalScenarioPattern.pattern_type == 2)).all()\n for item2 in exp_scenarios_pat:\n session.delete(item2)\n session.commit()\n session.close()\n msg_rspt = Message(action=2, comment='Register deleted successfully')\n return msg_rspt",
"def delete(task, eid):\n ServerManager.get()\n result = ServerManager.api.remove_experiment(task, eid)\n if result.response_type == 'success':\n click.echo(click.style(result.message, fg='green'))\n else:\n click.echo(click.style(result.message, fg='red'))",
"def __delitem__(self, skillName):\r\n self.removeSkill(skillName)",
"def skill(ctx: Context, public_id: PublicId):\n _eject_item(ctx, \"skill\", public_id)",
"def delete_demo(exploration_id):\n exploration = get_exploration_by_id(exploration_id, strict=False)\n if not exploration:\n # This exploration does not exist, so it cannot be deleted.\n logging.info('Exploration with id %s was not deleted, because it '\n 'does not exist.' % exploration_id)\n else:\n delete_exploration(ADMIN_COMMITTER_ID, exploration_id)",
"def delete_experiment(filename):\n experiment_directory = os.path.dirname(os.path.abspath(__file__)) + EXPERIMENT_UPLOAD_FOLDER\n response_code = 400\n response = \"\"\n if filename in os.listdir(experiment_directory):\n try:\n os.remove(os.path.join(experiment_directory, filename))\n response = f\"File {filename} was successfully deleted.\"\n response_code = 200\n except IsADirectoryError:\n response = f\"{filename} exists, but is a directory and not a file. Deletion failed.\"\n else:\n response = f\"File {filename} does not exist and so couldn't be deleted.\"\n return make_response(jsonify({'message': response}), response_code)",
"def delete_study(self, study_id: int) -> None:\n raise NotImplementedError",
"def delete_experiment(self, id):\n experiment = self.dbsession.query(Experiment).filter_by(id=id).first()\n if experiment is None:\n return False\n experimentgroups = experiment.experimentgroups\n for experimentgroup in experimentgroups:\n self.delete_experimentgroup_in_clients(experimentgroup.id)\n self.dbsession.delete(experiment)\n return [] == self.dbsession.query(Experiment).filter_by(id=id).all()",
"def delete_exam(request, exam_id):\n\n\temp = models.Employee.objects.get(user=request.user)\n\tif not emp.exam_permit:\n\t\traise Http404\n\texam = models.ExamName.objects.filter(\n\t\tpk=exam_id, soft_delete=False\n\t).first()\n\tif not exam:\n\t\traise Http404\n\texam.soft_delete = True\n\tactivity = 'Deleted Exam' + str(exam) + '.\\n'\n\texam.save(update_fields=['soft_delete'])\n\thistory = models.History(\n\t\t\t\tuser=emp,\n\t\t\t\tactivity=activity,\n\t\t\t\tactivity_type=\"delete exam\"\n\t\t\t)\n\thistory.save()\n\treturn HttpResponseRedirect('/view-exams')",
"def deleteStudy(self, study_id, full_delete):\n con = self.getMetadataDatabaseConnection()\n con.cursor().callproc('qiime_assets.study_delete', [study_id, full_delete])",
"def delete(self, expectation_suite_id: int) -> None:\n _client = client.get_instance()\n path_params = [\n \"project\",\n _client._project_id,\n \"featurestores\",\n self._feature_store_id,\n \"featuregroups\",\n self._feature_group_id,\n \"expectationsuite\",\n expectation_suite_id,\n ]\n\n major, minor = self._variable_api.parse_major_and_minor(\n self._variable_api.get_version(\"hopsworks\")\n )\n if major == \"3\" and minor == \"0\":\n del path_params[-1]\n\n _client._send_request(\"DELETE\", path_params)",
"def delete_question(request, question_id):\n raise NotImplementedError",
"def unload(self, skillName):\r\n es.unload(\"%s/skills/%s\" % (info.basename, skillName))",
"def delete_sample(namespace, workspace, sample_id):\n body = [{\"entityType\": \"sample\", \"entityName\": sample_id}]\n res = firecloud_api.delete_entities(namespace, workspace, body)\n return res",
"def detach_skill(self, skill_id):\n with self.lock:\n skill_parsers = [\n p.name for p in self.engine.intent_parsers if\n p.name.startswith(skill_id)\n ]\n self.engine.drop_intent_parser(skill_parsers)\n self._detach_skill_keywords(skill_id)\n self._detach_skill_regexes(skill_id)",
"def removeSkill(self, skillName):\r\n if self.__contains__(skillName):\r\n del self.skills[skillName]\r\n del self.orderedSkills[self.orderedSkills.index(skillName)]",
"def delete_story(self, story):\n raise NotImplementedError",
"def delete(self, request, s_id):\n simulation = Simulation.objects.get(id=s_id)\n simulation.delete()\n return HttpResponse(HTTPStatus.OK)",
"def delete(self):\n key = self.request.get('key')\n\n if not self.assert_xsrf_token_or_fail(\n self.request, self.XSRF_TOKEN, {'key': key}):\n return\n\n if not CourseOutlineRights.can_delete(self):\n transforms.send_json_response(\n self, 401, 'Access denied.', {'key': key})\n return\n\n question = QuestionDAO.load(key)\n if not question:\n transforms.send_json_response(\n self, 404, 'Question not found.', {'key': key})\n return\n\n used_by = QuestionDAO.used_by(question.id)\n if used_by:\n group_names = ['\"%s\"' % x for x in used_by]\n transforms.send_json_response(\n self, 403,\n ('Question in use by question groups:\\n%s.\\nPlease delete it '\n 'from those groups and try again.') % ',\\n'.join(group_names),\n {'key': key})\n return\n\n QuestionDAO.delete(question)\n transforms.send_json_response(self, 200, 'Deleted.')",
"def dropSkill(skill, db):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if not skill_data:\n return colored(\"ERROR: Skill {S} is not in your skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n db.execute(\n 'DELETE FROM mystatus WHERE skill = ?', (str(skill), ))\n db.commit()\n return colored(\"Drop skill: \" + str(skill), 'cyan')",
"def delete_skill_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def delete(ctx):\n user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n ctx.obj.get('group'))\n\n if not click.confirm(\"Are sure you want to delete experiment group `{}`\".format(_group)):\n click.echo('Existing without deleting experiment group.')\n sys.exit(0)\n\n try:\n response = PolyaxonClient().experiment_group.delete_experiment_group(\n user, project_name, _group)\n # Purge caching\n GroupManager.purge()\n except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n Printer.print_error('Could not delete experiment group `{}`.'.format(_group))\n Printer.print_error('Error message `{}`.'.format(e))\n sys.exit(1)\n\n if response.status_code == 204:\n Printer.print_success(\"Experiment group `{}` was delete successfully\".format(_group))"
] | [
"0.75951886",
"0.70176864",
"0.6887585",
"0.6750253",
"0.66612613",
"0.66010493",
"0.64526707",
"0.64486927",
"0.6433302",
"0.62364894",
"0.60881037",
"0.60593563",
"0.59835654",
"0.58690006",
"0.5865851",
"0.58418304",
"0.5839061",
"0.5823958",
"0.5795506",
"0.57483846",
"0.5712763",
"0.56910664",
"0.5674828",
"0.5664565",
"0.5650048",
"0.5648412",
"0.56150925",
"0.5610559",
"0.5582403",
"0.55704486"
] | 0.7176662 | 1 |
Updates the exposure of an experiment that is in CREATED or RUNNING state. | def update_exposure_v1(self, skill_id, experiment_id, update_exposure_request, **kwargs):
# type: (str, str, UpdateExposureRequest_ce52ce53, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "update_exposure_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'experiment_id' is set
if ('experiment_id' not in params) or (params['experiment_id'] is None):
raise ValueError(
"Missing the required parameter `experiment_id` when calling `" + operation_name + "`")
# verify the required parameter 'update_exposure_request' is set
if ('update_exposure_request' not in params) or (params['update_exposure_request'] is None):
raise ValueError(
"Missing the required parameter `update_exposure_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/exposurePercentage'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'experiment_id' in params:
path_params['experimentId'] = params['experiment_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'update_exposure_request' in params:
body_params = params['update_exposure_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_exposure(self, exposure):\n self.logger.info(f'Setting exposure to {exposure}')\n self._driver.ExposureTime.SetValue(exposure)",
"def expose(self):\n\n ## Determine type of exposure (exp, series, stack)\n exptype = str(self.exptypeComboBox.currentText())\n mode = self.modedict[exptype]\n\n ## Get exposure parameters\n if mode == \"bias\":\n exptime = 0.0\n else:\n exptime = self.exptimeSpinBox.value()\n imcount = self.imstackSpinBox.value()\n seqnum = self.imnumSpinBox.value()\n mintime = self.minexpSpinBox.value()\n maxtime = self.maxexpSpinBox.value()\n step = self.tstepSpinBox.value()\n\n ## Determine filter kwargs\n if self.filterToggleButton.isChecked():\n kwargs = {'filter_name' : str(self.filterComboBox.currentText())}\n else:\n kwargs = {'monowl' : self.monoSpinBox.value()}\n\n if self.testimCheckBox.isChecked():\n title = 'test'\n else:\n title = str(self.imtitleLineEdit.text())\n\n ## Build filepath\n filepath = os.path.join(str(self.imfilenameLineEdit.text()),title)\n \n ## Check if single exposure\n if exptype in [\"Exposure\", \"Dark\", \"Bias\"]:\n\n ## Perform exposure\n self.logger.info(\"Starting {0}s {1} image.\".format(exptime, exptype))\n self.image_start.emit(1)\n\n try:\n filename = exposure.im_acq(mode, filepath, exptime, seqnum, **kwargs)\n self.image_taken.emit(1)\n except subprocess.CalledProcessError:\n self.logger.exception(\"Error in executable {0}_acq. Image not taken.\".format(mode))\n except OSError:\n self.logger.exception(\"Executable {0}_acq not found. Image not taken\".format(mode))\n except IOError:\n self.logger.exception(\"File already exits. Image not taken.\")\n else:\n self.logger.info(\"Exposure {0} finished successfully.\".format(filename))\n self.seqnum_inc.emit(seqnum)\n subprocess.Popen(['ds9', '-mosaicimage', 'iraf', filename,\n '-zoom', 'to', 'fit', '-cmap', 'b'])\n\n ## Check if a stack of exposures of same type\n elif exptype in [\"Exposure Stack\", \"Dark Stack\", \"Bias Stack\"]:\n\n total = seqnum + imcount\n self.logger.info(\"Starting {0}s {1} stack.\".format(exptime, exptype))\n self.image_start.emit(imcount)\n\n try:\n for i in range(seqnum, total):\n self.logger.info(\"Starting image {0} of {1}.\".format(i+1-seqnum, imcount))\n filename = exposure.im_acq(mode, filepath, exptime, i, **kwargs)\n self.logger.info(\"Exposure {0} finished successfully.\".format(filename))\n self.image_taken.emit(i+1-seqnum)\n self.seqnum_inc.emit(i)\n except subprocess.CalledProcessError:\n self.logger.exception(\"Error in executable {0}_acq. Image not taken.\".format(mode))\n except OSError:\n self.logger.exception(\"Executable {0}_acq not found. Image not taken.\".format(mode))\n except IOError:\n self.logger.exception(\"File already exists. Image not taken.\")\n else:\n self.logger.info(\"Exposure stack finished successfully.\")\n subprocess.Popen(['ds9', '-mosaicimage', 'iraf', filename, '-zoom', 'to', 'fit', '-cmap', 'b'])\n \n ## Check if a series of exposures of increase exposure time\n elif exptype in [\"Exposure Series\", \"Dark Series\"]:\n\n ## Parameter checks\n if mintime > maxtime:\n self.logger.warning(\"Minimum time must be less than Maximum time. Series not started.\")\n return\n elif step <= 0:\n self.logger.warning(\"Time step must be greater than 0. Series not started.\")\n return\n\n ## Construct array of exposure times\n t = mintime\n time_array = []\n while t <= maxtime:\n time_array.append(t)\n t += step\n \n ## Perform series\n self.logger.info(\"Starting {0} series with mintime {1}, maxtime {2}, and step {3}.\".format(exptype, mintime, maxtime, step))\n self.image_start.emit(len(time_array))\n \n try:\n for i, time in enumerate(time_array):\n self.logger.info(\"Starting {0}s {1} image.\".format(time, mode))\n filename = exposure.im_acq(mode, filepath, time, seqnum, **kwargs)\n self.logger.info(\"Exposure {0} finished successfully.\".format(filename))\n self.image_taken.emit(i+1)\n except subprocess.CalledProcessError:\n self.logger.exception(\"Error in executable {0}_acq. Image not taken.\".format(mode))\n except OSError:\n self.logger.exception(\"Executable {0}_acq not found. Image not taken.\".format(mode))\n except IOError:\n self.logger.exception(\"File already exists. Image not taken.\")\n else:\n self.logger.info(\"Exposure series finished successfully.\")\n subprocess.Popen(['ds9', '-mosaicimage', 'iraf', filename, '-zoom', 'to', 'fit', '-cmap', 'b'])\n self.seqnum_inc.emit(seqnum)",
"def exposureCallback(self, config):\n rospy.loginfo('Set exposure: {}'.format(config['exposure']))",
"def expose(self, cmd, expTime, expType):\n\n if not expType:\n expType = 'test'\n if cmd:\n cmd.inform('exposureState=\"exposing\"')\n if expType not in ('bias', 'test') and expTime > 0:\n time.sleep(expTime + self._exposureOverheadTime())\n\n if cmd:\n cmd.inform('exposureState=\"reading\"')\n\n f = pyfits.open('/home/chyan/mhs/data/mcs/schmidt_fiber_snr400_rmod71.fits')\n image = f[0].data\n # image = numpy.random.normal(self.biasLevel,\n # scale=self.readNoise,\n # size=self.imageSize).astype('u2')\n\n if expType != 'test':\n time.sleep(self._readoutTime())\n return image",
"def update(self, request, pk=None):\n exp = Experiment.objects.get(pk=pk)\n serializer = ExperimentSerializer(exp, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return send_response(request.method, serializer)",
"def expose(self, cmd):\n\n expType = cmd.cmd.keywords[0].name\n if expType in ('bias', 'test'):\n expTime = 0.0\n else:\n expTime = cmd.cmd.keywords[\"expTime\"].values[0]\n\n filename, image = self._doExpose(cmd, expTime, expType)\n cmd.finish('exposureState=done')",
"def select_exposure(self):\n exp1_selected = self.exp1_radio.isChecked()\n\n if self.recording_sequence:\n self.record_sequence() # stop current recording\n\n if exp1_selected: # then exp1\n ifi_ndx = self.exp1_ifi_select.currentIndex()\n self.camera.set_exposure(self.exp1_select.currentIndex(), ifi_ndx)\n else:\n ifi_ndx = self.exp2_ifi_select.currentIndex()\n self.camera.set_exposure(self.exp2_select.currentIndex(), ifi_ndx)\n\n temp = list(self.dpar.iwindow_toggle_save)\n self.dpar.iwindow_toggle_save = list(self.dpar.iwindow[0])\n self.dpar.iwindow[0] = temp\n self._update_scrollbars()\n\n self.rec_seq_button.setEnabled(ifi_ndx > 0)\n\n et = np.int(np.round(self.camera.actual_exposure_time_ms))\n self.write_to_log('Exposure %d ms' % et)",
"def update(ctx, name, description, tags):\n user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n ctx.obj.get('experiment'))\n update_dict = {}\n\n if name:\n update_dict['name'] = name\n\n if description:\n update_dict['description'] = description\n\n tags = validate_tags(tags)\n if tags:\n update_dict['tags'] = tags\n\n if not update_dict:\n Printer.print_warning('No argument was provided to update the experiment.')\n sys.exit(0)\n\n try:\n response = PolyaxonClient().experiment.update_experiment(\n user, project_name, _experiment, update_dict)\n except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n Printer.print_error('Could not update experiment `{}`.'.format(_experiment))\n Printer.print_error('Error message `{}`.'.format(e))\n sys.exit(1)\n\n Printer.print_success(\"Experiment updated.\")\n get_experiment_details(response)",
"def changeExposure(cam=0, increment=None, value=None):\n try:\n if increment is not None:\n exposure = commands.getoutput(\"v4l2-ctl -d {} --get-ctrl exposure_absolute\".format(cam)).split()[1]\n exposure = int(exposure)\n exposure = max(0, exposure + increment)\n elif value is not None:\n exposure = max(0, value)\n else:\n raise Exception(\"increment or value must be an integer\")\n commands.getoutput(\"v4l2-ctl -d {} --set-ctrl exposure_absolute={}\".format(cam, exposure))\n print \"Exposure {}\".format(exposure)\n except Exception as e:\n print \"Failed to change exposure: {}\".format(e)",
"def exp(self, exposure_time):\n print(f\"exp: {exposure_time}\")\n self.device_control.exposure = exposure_time\n yield",
"def expose(self):\n if self.camera is None: # test mode -- immediately return test image\n print(\"NO SPECTRAL CAMERA FOUND -- USING TEST DATA\")\n self.filename = \"example_fits_files/Mooi\"\n return\n\n exposure_time = self.time.get()\n try:\n self.exposure_time = float(exposure_time)\n except:\n message = \"Exposure time \\\"{0}\\\" cannot be converted to floating point number\".format(exposure_time)\n messagebox.showerror(\"Error\", message)\n raise ValueError(message)\n filename = \"spectra/{0}\".format(timestamp())\n self.camera.spectrum(self.exposure_time, filename)\n self.filename = filename",
"def refresh(self):\n connection = self._connection\n with self._refresh_lock:\n self._aiexperiment = connection.aiexperiments(self.id).fetch()",
"def testPersistence(self):\n exposure = lsst.afw.image.ExposureF(1, 1)\n exposure.setPsf(self.psf)\n self.assertIsNotNone(exposure.getPsf())\n with lsst.utils.tests.getTempFilePath(\".fits\") as filename:\n exposure.writeFits(filename)\n copy = lsst.afw.image.ExposureF(filename).getPsf()\n self.assertIsNotNone(copy)\n self.assertIsInstance(copy, GaussianOversampledPsf)\n self.assertGaussianOversampledPsfEqual(copy, self.psf)",
"def toggle_exposure(self):\n\n checked1 = self.exp1_radio.isChecked()\n if checked1:\n self.exp2_radio.setChecked(True)\n else:\n self.exp1_radio.setChecked(True)\n self.select_exposure()",
"def exposure(self) -> Quantity:\n if self._exp is None:\n raise ModelNotAssociatedError(\"There are no XSPEC fits associated with this Spectrum\")\n else:\n exp = Quantity(self._exp, 's')\n\n return exp",
"def toggleExposure(self, state):\n if state == False:\n freenect.sync_get_video_with_res(\n resolution=freenect.RESOLUTION_HIGH)\n # print(freenect.sync_set_autoexposure(False))\n freenect.sync_set_autoexposure(False)\n # print(freenect.sync_set_whitebalance(False))\n freenect.sync_set_whitebalance(False)\n else:\n freenect.sync_get_video_with_res(\n resolution=freenect.RESOLUTION_HIGH)\n # print(freenect.sync_set_autoexposure(True))\n freenect.sync_set_autoexposure(True)\n # print(freenect.sync_set_whitebalance(True))\n freenect.sync_set_whitebalance(True)",
"def set_exposure(self, expo):\n if expo == 0:\n self.exposure = 0\n elif expo == 1:\n self.exposure = min(9, self.exposure+1)\n elif expo == -1:\n self.exposure = max(-9, self.exposure-1)\n self.drone.set_exposure(self.exposure)\n log.info(f\"EXPOSURE {self.exposure}\")",
"def __exp2_changed_callback(self, ndx):\n if self.recording_sequence:\n self.record_sequence()\n self.exp2_radio.setChecked(True)\n self.exp2_ifi_select.setCurrentIndex(0)\n self.camera.set_exposure(ndx, 0)\n self.rec_seq_button.setEnabled(False)\n et = np.int(np.round(self.camera.actual_exposure_time_ms))\n self.write_to_log('Exposure %d ms' % et)",
"def endexposureloop(self):\n self.max_exposures = self.current_exposure",
"def run_observation(self):\n\n self._generate_direct_image() # to calibrate x_ref and y_ref\n\n num_frames = len(self.exp_start_times)\n progress = Progress(num_frames)\n self.progess = progress\n\n progress_line = 'Generating frames 0/{} done'.format(num_frames)\n progress.print_status_line(progress_line)\n progress.progress_line = progress_line\n\n for i, start_time in enumerate(self.exp_start_times):\n filenum = i + 1\n self._generate_exposure(start_time, filenum)\n\n progress.increment()\n progress_line = 'Generating frames {}/{} done'.format(filenum,\n num_frames)\n progress.print_status_line(progress_line)\n\n # so it can be retreived by exposure_generator\n progress.progress_line = progress_line",
"def __exp1_changed_callback(self, ndx):\n if self.recording_sequence:\n self.record_sequence()\n self.exp1_radio.setChecked(True)\n self.exp1_ifi_select.setCurrentIndex(0)\n self.camera.set_exposure(ndx, 0)\n self.rec_seq_button.setEnabled(False)\n et = np.int(np.round(self.camera.actual_exposure_time_ms))\n self.write_to_log('Exposure %d ms' % et)",
"def _onOpen(self, event):\n self.openExperiment()",
"def testUpdatePhoto(self):\n photo_id = self._UploadEpisodeWithPhoto()\n\n self._tester.UpdatePhoto(self._cookie, photo_id, caption='An Updated Caption',\n placemark={'iso_country_code': 'US', 'country': 'United States',\n 'state': 'NY', 'locality': 'New York', 'sublocality': 'NoHo',\n 'thoroughfare': 'Broadway', 'subthoroughfare': '682'})",
"def Exposure(self, time):\r\n IS_EXPOSURE_CMD_SET_EXPOSURE = 12 #there is a whole list to implement\r\n TIME = DOUBLE(time)\r\n nSizeOfParam = 8\r\n CALL('Exposure', self, \r\n UINT(IS_EXPOSURE_CMD_SET_EXPOSURE), \r\n byref(TIME), \r\n UINT(nSizeOfParam))",
"def configure_exposure(cam,exposure):\n\n #print(\"*** CONFIGURING EXPOSURE ***\\n\")\n\n try:\n result = True\n\n # Turn off automatic exposure mode\n #\n # *** NOTES ***\n # Automatic exposure prevents the manual configuration of exposure\n # times and needs to be turned off for this example. Enumerations\n # representing entry nodes have been added to QuickSpin. This allows\n # for the much easier setting of enumeration nodes to new values.\n #\n # The naming convention of QuickSpin enums is the name of the\n # enumeration node followed by an underscore and the symbolic of\n # the entry node. Selecting \"Off\" on the \"ExposureAuto\" node is\n # thus named \"ExposureAuto_Off\".\n #\n # *** LATER ***\n # Exposure time can be set automatically or manually as needed. This\n # example turns automatic exposure off to set it manually and back\n # on to return the camera to its default state.\n\n \n\n # Set exposure time manually; exposure time recorded in microseconds\n #\n # *** NOTES ***\n # Notice that the node is checked for availability and writability\n # prior to the setting of the node. In QuickSpin, availability and\n # writability are ensured by checking the access mode.\n #\n # Further, it is ensured that the desired exposure time does not exceed\n # the maximum. Exposure time is counted in microseconds - this can be\n # found out either by retrieving the unit with the GetUnit() method or\n # by checking SpinView.\n\n if cam.ExposureTime.GetAccessMode() != PySpin.RW:\n print(\"Unable to set exposure time. Aborting...\")\n return False\n\n # Ensure desired exposure time does not exceed the maximum\n exposure_time_to_set = exposure\n exposure_time_to_set = min(cam.ExposureTime.GetMax(), exposure_time_to_set)\n cam.ExposureTime.SetValue(exposure_time_to_set)\n\n except PySpin.SpinnakerException as ex:\n print(\"Error: %s\" % ex)\n result = False\n\n return result",
"def insert_exposure(\n self, expid, night, telra=None, teldec=None,\n tile=None, dateobs=None, flavor=None, exptime=None\n ):\n\n # Check if expid is already registered\n if not Exposure.objects.filter(exposure_id=expid):\n exposure = Exposure(\n exposure_id=expid, night=night,\n telra=telra, teldec=teldec,\n tile=tile, dateobs=dateobs,\n flavor=flavor, exptime=exptime\n )\n exposure.save()\n\n # Save Process for this exposure\n return Exposure.objects.get(exposure_id=expid)",
"def exposure(frameType, expTime):\n\n blobEvent.clear() \n\n # set the specified frame type\n if frameType.lower() == 'light':\n ccd_frame[0].s = PyIndi.ISS_ON\n ccd_frame[1].s = PyIndi.ISS_OFF\n ccd_frame[2].s = PyIndi.ISS_OFF\n ccd_frame[3].s = PyIndi.ISS_OFF \n indiclient.sendNewSwitch(ccd_frame)\n elif frameType.lower() == 'bias':\n ccd_frame[0].s = PyIndi.ISS_OFF\n ccd_frame[1].s = PyIndi.ISS_ON\n ccd_frame[2].s = PyIndi.ISS_OFF\n ccd_frame[3].s = PyIndi.ISS_OFF \n indiclient.sendNewSwitch(ccd_frame)\n elif frameType.lower() == 'dark':\n ccd_frame[0].s = PyIndi.ISS_OFF\n ccd_frame[1].s = PyIndi.ISS_OFF\n ccd_frame[2].s = PyIndi.ISS_ON\n ccd_frame[3].s = PyIndi.ISS_OFF \n indiclient.sendNewSwitch(ccd_frame)\n elif frameType.lower() == 'flat':\n ccd_frame[0].s = PyIndi.ISS_OFF\n ccd_frame[1].s = PyIndi.ISS_OFF\n ccd_frame[2].s = PyIndi.ISS_OFF\n ccd_frame[3].s = PyIndi.ISS_ON \n indiclient.sendNewSwitch(ccd_frame)\n\n # set the value for the next exposure\n ccd_exposure[0].value=expTime\n\n indiclient.sendNewNumber(ccd_exposure)\n\n # wait for the exposure\n blobEvent.wait()\n\n for blob in ccd_ccd1:\n # pyindi-client adds a getblobdata() method to IBLOB item\n # for accessing the contents of the blob, which is a bytearray in Python\n image_data=blob.getblobdata()\n\n # write the byte array out to a FITS file\n global imgNum\n global imgName\n imgNum += 1\n fileName = fileDir+'raw-'+str(imgNum).zfill(8)+'.fits'\n f = open(fileName, 'wb')\n f.write(image_data)\n f.close()\n imgName = fileName\n \n return fileName",
"def _update_episode(self):\n self._publish_reward_topic(\n self.cumulated_episode_reward,\n self.episode_num\n )\n self.episode_num += 1\n self.cumulated_episode_reward = 0",
"def test_atomic_update_episode(self):\n episode = self._create_sample_episode()\n study_id, session_id, episode_id = (episode.study_id, episode.session_id,\n episode.id)\n\n def callback(read_episode):\n # Read episode should match the stored one.\n self.assertEqual(read_episode, episode)\n self.assertEqual(read_episode.num_steps, 100)\n # Make a change.\n read_episode.num_steps = 200\n return True\n\n self.assertTrue(\n self.storage.atomic_update_episode(study_id, session_id, episode_id,\n callback))\n # Check that the change was applied.\n episode.num_steps = 200\n self.assertEqual(\n self.storage.get_episode(study_id, session_id, episode_id), episode)",
"def setExposureTime(self, cmd, expTime):\n\n pass"
] | [
"0.62713146",
"0.61086863",
"0.5796227",
"0.56842786",
"0.56367266",
"0.55775315",
"0.5473165",
"0.5465806",
"0.54192114",
"0.5390392",
"0.5371606",
"0.53087795",
"0.5306276",
"0.52943015",
"0.5248691",
"0.5242781",
"0.52340454",
"0.52296704",
"0.5219299",
"0.5186737",
"0.51164466",
"0.50875056",
"0.5084654",
"0.50629973",
"0.5046862",
"0.504683",
"0.5037379",
"0.5013549",
"0.49925092",
"0.49903974"
] | 0.6274165 | 0 |
Retrieves an existing experiment for a skill. | def get_experiment_v1(self, skill_id, experiment_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, GetExperimentResponse_fcd92c35, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "get_experiment_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'experiment_id' is set
if ('experiment_id' not in params) or (params['experiment_id'] is None):
raise ValueError(
"Missing the required parameter `experiment_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'experiment_id' in params:
path_params['experimentId'] = params['experiment_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse", status_code=200, message="Returned skill experiment."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_experiment(self, experiment_name : str):\n return self._df[self._df.experiment == experiment_name]",
"def _get_experiment_sqa(experiment_name: str, decoder: Decoder) -> SQAExperiment:\n exp_sqa_class = decoder.config.class_to_sqa_class[Experiment]\n with session_scope() as session:\n sqa_experiment = (\n session.query(exp_sqa_class).filter_by(name=experiment_name).one_or_none()\n )\n if sqa_experiment is None:\n raise ValueError(f\"Experiment '{experiment_name}' not found.\")\n return sqa_experiment # pyre-ignore[7]",
"def Experiment(self, default=None):\n return self.data.get('experiment', default)",
"def create_experiment_v1(self, skill_id, create_experiment_request, **kwargs):\n # type: (str, CreateExperimentRequest_abced22d, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'create_experiment_request' is set\n if ('create_experiment_request' not in params) or (params['create_experiment_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_experiment_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_experiment_request' in params:\n body_params = params['create_experiment_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Experiment created. Returns the generated experiment identifier in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def retrieve(self, request, pk=None):\n exp = Experiment.objects.get(pk=pk)\n serializer = ExperimentSerializer(exp)\n return send_response(request.method, serializer)",
"def experiment(self) -> Run:\n if self._experiment is None:\n self._experiment = self.create_experiment()\n return self._experiment",
"def get_skill(skillpath):\n return Skill.query.filter_by(path=skillpath).first()",
"def delete_experiment_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def experiment(self):\n return self._experiment",
"def list_experiments_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, ListExperimentsResponse_c5b07ecb]\n operation_name = \"list_experiments_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.experiment.list_experiments_response.ListExperimentsResponse\", status_code=200, message=\"Returned skill experiments.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.experiment.list_experiments_response.ListExperimentsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def skill(self):\n return self._get(\"skill\")",
"def get_skill_from_id(skill_id):\n return Skill.query.filter_by(id=skill_id).first()",
"def get_experiment(self,\n experiment_id=None,\n experiment_name=None,\n namespace=None) -> kfp_server_api.V1Experiment:\n namespace = namespace or self.get_user_namespace()\n if experiment_id is None and experiment_name is None:\n raise ValueError(\n 'Either experiment_id or experiment_name is required')\n if experiment_id is not None:\n return self._experiment_api.get_experiment(id=experiment_id)\n experiment_filter = json.dumps({\n 'predicates': [{\n 'op': _FILTER_OPERATIONS['EQUALS'],\n 'key': 'name',\n 'stringValue': experiment_name,\n }]\n })\n if namespace:\n result = self._experiment_api.list_experiment(\n filter=experiment_filter,\n resource_reference_key_type=kfp_server_api.models\n .v1_resource_type.V1ResourceType.NAMESPACE,\n resource_reference_key_id=namespace)\n else:\n result = self._experiment_api.list_experiment(\n filter=experiment_filter)\n if not result.experiments:\n raise ValueError(\n 'No experiment is found with name {}.'.format(experiment_name))\n if len(result.experiments) > 1:\n raise ValueError(\n 'Multiple experiments is found with name {}.'.format(\n experiment_name))\n return result.experiments[0]",
"def create_experiment_if_needed(tr):\n exp = tr.getExperiment(EXPERIMENT_ID)\n if None == exp:\n create_project_if_needed(tr)\n exp = tr.createNewExperiment(EXPERIMENT_ID, 'DEFAULT_EXPERIMENT')\n \n return exp",
"def update_experiment_v1(self, skill_id, experiment_id, update_experiment_request, **kwargs):\n # type: (str, str, UpdateExperimentRequest_d8449813, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"update_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_experiment_request' is set\n if ('update_experiment_request' not in params) or (params['update_experiment_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_experiment_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/properties'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'update_experiment_request' in params:\n body_params = params['update_experiment_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def _load_experiment(\n experiment_name: str, decoder: Decoder, reduced_state: bool = False\n) -> Experiment:\n # Convert SQA to user-facing class outside of session scope to avoid timeouts\n return decoder.experiment_from_sqa(\n experiment_sqa=_get_experiment_sqa_reduced_state(\n experiment_name=experiment_name, decoder=decoder\n )\n if reduced_state\n else _get_experiment_sqa(experiment_name=experiment_name, decoder=decoder),\n reduced_state=reduced_state,\n )",
"def get(ctx, job):\n\n def get_experiment():\n try:\n response = PolyaxonClient().experiment.get_experiment(user, project_name, _experiment)\n cache.cache(config_manager=ExperimentManager, response=response)\n except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n Printer.print_error('Could not load experiment `{}` info.'.format(_experiment))\n Printer.print_error('Error message `{}`.'.format(e))\n sys.exit(1)\n\n get_experiment_details(response)\n\n def get_experiment_job():\n try:\n response = PolyaxonClient().experiment_job.get_job(user,\n project_name,\n _experiment,\n _job)\n cache.cache(config_manager=ExperimentJobManager, response=response)\n except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n Printer.print_error('Could not get job `{}`.'.format(_job))\n Printer.print_error('Error message `{}`.'.format(e))\n sys.exit(1)\n\n if response.resources:\n get_resources(response.resources.to_dict(), header=\"Job resources:\")\n\n response = Printer.add_status_color(response.to_light_dict(\n humanize_values=True,\n exclude_attrs=['uuid', 'definition', 'experiment', 'unique_name', 'resources']\n ))\n Printer.print_header(\"Job info:\")\n dict_tabulate(response)\n\n user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n ctx.obj.get('experiment'))\n\n if job:\n _job = get_experiment_job_or_local(job)\n get_experiment_job()\n else:\n get_experiment()",
"async def skill(self, ctx, *, skill: str):\n\n try:\n skill = self.get_entry('Skill', skill.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = skill['Name']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://skill.png')\n embed.add_field(name='Learned', value=skill['Class/Rank'], inline=False)\n embed.add_field(name='Effect', value=skill['Effect'])\n\n await ctx.send(file=discord.File(f'xenox/skills/{name}.png', 'skill.png'), embed=embed)",
"def load_experiment(\n experiment_name: str,\n config: Optional[SQAConfig] = None,\n reduced_state: bool = False,\n) -> Experiment:\n config = config or SQAConfig()\n decoder = Decoder(config=config)\n return _load_experiment(\n experiment_name=experiment_name, decoder=decoder, reduced_state=reduced_state\n )",
"def _create_or_get_experiment(self) -> tensorboard_experiment.TensorboardExperiment:\n logger.info(\"Creating experiment\")\n\n tb_experiment = tensorboard_experiment.TensorboardExperiment(\n description=self._description, display_name=self._experiment_display_name\n )\n\n try:\n experiment = self._api.create_tensorboard_experiment(\n parent=self._tensorboard_resource_name,\n tensorboard_experiment=tb_experiment,\n tensorboard_experiment_id=self._experiment_name,\n )\n self._is_brand_new_experiment = True\n except exceptions.AlreadyExists:\n logger.info(\"Creating experiment failed. Retrieving experiment.\")\n experiment_name = os.path.join(\n self._tensorboard_resource_name, \"experiments\", self._experiment_name\n )\n experiment = self._api.get_tensorboard_experiment(name=experiment_name)\n return experiment",
"def get_experience(uid, rid):\n experience = Experience.query.filter(Experience.uid == uid).filter(Experience.rid == rid).first()\n return experience",
"def get_skill(self, utterance, lang=\"en-us\"):\n intent = self.get_intent(utterance, lang)\n if not intent:\n return None\n # theoretically skill_id might be missing\n if intent.get(\"skill_id\"):\n return intent[\"skill_id\"]\n # retrieve skill from munged intent name\n if intent.get(\"intent_name\"): # padatious + adapt\n return intent[\"name\"].split(\":\")[0]\n if intent.get(\"intent_type\"): # adapt\n return intent[\"intent_type\"].split(\":\")[0]\n return None # raise some error here maybe? this should never happen",
"def getSkill(self, skillName):\r\n if self.__contains__(skillName):\r\n return self.skills[skillName]\r\n return None",
"def get_ability_skill(cursor, skill):\n cursor.execute('SELECT id FROM skills WHERE identifier = ?', (skill,))\n data = cursor.fetchone()\n try:\n return data[0]\n except TypeError:\n l.error(\"The Skill {} doesn't exists.\".format(skill))\n return 0",
"def one_experiment(monkeypatch, storage):\n monkeypatch.chdir(os.path.dirname(os.path.abspath(__file__)))\n name = \"test_single_exp\"\n orion.core.cli.main(\n [\"hunt\", \"--init-only\", \"-n\", name, \"./black_box.py\", \"--x~uniform(0,1)\"]\n )\n ensure_deterministic_id(name, storage)\n return storage.fetch_experiments({\"name\": name})[0]",
"def get_single_experience(self, time_step):\r\n assert self.n_experience - 1 > time_step, \"Sample time step must be less than number of experience minus one.\"\r\n return self.buffer_experience[time_step]",
"def __getitem__(self, skillName):\r\n return self.getSkill(skillName)",
"def test_get_skill_name(self):\n result = self.runner.invoke(\n cli,\n [*CLI_LOG_OPTION, \"config\", \"get\", \"skills.dummy.name\"],\n standalone_mode=False,\n )\n assert result.exit_code == 0\n assert result.output == \"dummy\\n\"",
"def with_experiment_using_python_api(storage, monkeypatch, one_experiment):\n experiment = experiment_builder.build(\n name=\"from-python-api\", space={\"x\": \"uniform(0, 10)\"}, storage=storage\n )\n\n return experiment",
"def view_experiment(request,id):\n\texp = Experiment.objects.get(id=id)\n\tpossibly_related = get_related(exp)\n\treturn list_detail.object_detail(request,\n\t\t\t\t\t\t\t\t\tqueryset=Experiment.objects.filter(id=id),\n\t\t\t\t\t\t\t\t\tobject_id=exp.id,\n\t\t\t\t\t\t\t\t\ttemplate_name='experiments/experiment.html',\n\t\t\t\t\t\t\t\t\textra_context= {\"possibly_related\" : possibly_related})"
] | [
"0.6250157",
"0.6212274",
"0.6107531",
"0.6012024",
"0.5999046",
"0.5978549",
"0.5974284",
"0.59668237",
"0.58823645",
"0.5868586",
"0.580707",
"0.5796458",
"0.5653181",
"0.5620087",
"0.561744",
"0.55910045",
"0.5584656",
"0.5543348",
"0.5502151",
"0.54974264",
"0.5459783",
"0.5458546",
"0.54368716",
"0.5433233",
"0.54209054",
"0.54188395",
"0.53703797",
"0.5329118",
"0.520249",
"0.51697"
] | 0.7118195 | 0 |
Gets a list of all metric snapshots associated with this experiment id. The metric snapshots represent the metric data available for a time range. | def list_experiment_metric_snapshots_v1(self, skill_id, experiment_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, ListExperimentMetricSnapshotsResponse_bb18308b]
operation_name = "list_experiment_metric_snapshots_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'experiment_id' is set
if ('experiment_id' not in params) or (params['experiment_id'] is None):
raise ValueError(
"Missing the required parameter `experiment_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/metricSnapshots'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'experiment_id' in params:
path_params['experimentId'] = params['experiment_id']
query_params = [] # type: List
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.experiment.list_experiment_metric_snapshots_response.ListExperimentMetricSnapshotsResponse", status_code=200, message="Returned experiment metric snapshots."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.experiment.list_experiment_metric_snapshots_response.ListExperimentMetricSnapshotsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_snapshots(self) -> SnapshotListing:\n return self.snapshots",
"def _list_snapshots(self):\n return self.resource.describe_snapshots(\n Filters=[\n {\n 'Name': 'tag:CreatedBy',\n 'Values': [\n 'AutomatedBackup{}'.format(INTERVAL_TYPE.capitalize())\n ]\n }\n ]\n )",
"def getSnapshots(self):\n snapshots = []\n for x in self.root.goto('CommonDataObjects/Attachments'):\n for y in x.getList():\n if y['name'] == 'Video Snapshot':\n self.f.seek(y['bidx'])\n blk = Block(self.f)\n sx = blk.goto('res_x').getLong()\n sy = blk.goto('res_y').getLong()\n raw = blk.goto(\"imagedata\").value\n data = zlib.decompress(raw)\n I = np.flipud(np.array(struct.unpack(\"<\" + str(3 * sx * sy) + \"B\", data)).reshape((sy, sx, 3)))\n snapshots.append(I)\n del blk\n return snapshots",
"def get_snapshots(self):\r\n ec2 = self.get_ec2_connection()\r\n rs = ec2.get_all_snapshots()\r\n all_vols = [self.volume_id] + self.past_volume_ids\r\n snaps = []\r\n for snapshot in rs:\r\n if snapshot.volume_id in all_vols:\r\n if snapshot.progress == '100%':\r\n snapshot.date = dateutil.parser.parse(snapshot.start_time)\r\n snapshot.keep = True\r\n snaps.append(snapshot)\r\n snaps.sort(cmp=lambda x,y: cmp(x.date, y.date))\r\n return snaps",
"def get_snapshots(self):\n _url = f\"{self.connector.base_url}/projects/{self.project_id}/snapshots\"\n\n response = self.connector.http_call(\"get\", _url)\n self.snapshots = response.json()",
"def get_exploration_snapshots_metadata(exploration_id, limit):\n exploration = get_exploration_by_id(exploration_id)\n oldest_version = max(exploration.version - limit, 0) + 1\n current_version = exploration.version\n version_nums = range(current_version, oldest_version - 1, -1)\n\n return [exp_models.ExplorationSnapshotModel.get_metadata(\n exploration_id, version_num\n ) for version_num in version_nums]",
"def GetVMSnapshotsList(self):\n try:\n current = self.vmInstance.get_current_snapshot_name()\n snapshots = self.vmInstance.get_snapshots()\n\n if current and snapshots:\n LOGGER.info('Name of current snapshot of virtual machine \"{}\": \"{}\"'.format(VM_NAME, current))\n LOGGER.info('List of all snapshots:')\n\n for i, snap in enumerate(snapshots):\n LOGGER.info(' {}. \"'.format(i + 1) + snap.get_name() + '\"')\n\n else:\n LOGGER.warning('No snapshots found for virtual machine \"{}\"!'.format(VM_NAME))\n\n except Exception as e:\n snapshots = None\n LOGGER.debug(e)\n LOGGER.error(traceback.format_exc())\n LOGGER.error('An error occured while getting list of snapshots of virtual machine \"{}\"!'.format(VM_NAME))\n\n return snapshots",
"def getContainerSnapshots(self,node,vmid):\n data = self.connect('get','nodes/%s/lxc/%s/snapshot' % (node,vmid),None)\n return data",
"def screenshots(self):\n return self._screenshots",
"def snapshots(self, owner=None, restorable_by=None):\r\n rs = self.connection.get_all_snapshots(owner=owner,\r\n restorable_by=restorable_by)\r\n mine = []\r\n for snap in rs:\r\n if snap.volume_id == self.id:\r\n mine.append(snap)\r\n return mine",
"def getSnapshotsOf(image):\n snapshotIds = []\n deviceMapping = image.block_device_mapping # dict of devices\n devices = deviceMapping.keys()\n for d in devices:\n snapshotId = deviceMapping[d].snapshot_id\n if snapshotId is not None:\n snapshotIds.append(snapshotId.encode())\n return snapshotIds",
"def history(self) -> List[SnapshotLogEntry]:\n return self.metadata.snapshot_log",
"def get_snapshots(self, region):\n try:\n conn = ec2.connect_to_region(region, **self.credentials)\n region_snapshots = conn.get_all_snapshots(owner='self')\n except boto.exception.EC2ResponseError:\n return []\n return region_snapshots",
"def derived_snapshots(self):\n start_time = time.time()\n log.debug(\"Getting snaps derived from volume {0}.\".format(self.volume_id))\n derived_snapshots = []\n for snap in self.app.cloud_interface.get_all_snapshots():\n try:\n if snap.volume_id == self.volume_id:\n derived_snapshots.append(snap)\n except EC2ResponseError, e:\n log.warning(\"EC2ResponseError getting snapshot status: {0} \"\n \"(code {1}; status {2})\"\n .format(e.message, e.error_code, e.status))\n log.debug(\"Got snaps derived from volume {0} in {1} seconds: {2}\"\n .format(self.volume_id, time.time() - start_time, derived_snapshots))\n return derived_snapshots",
"def list_snapshots(session, verbose):\n # type: (Session, bool) -> Union[List[str], List[Dict[str,str]]]\n if not session.network:\n raise ValueError(\"Network must be set to list snapshots\")\n url_tail = \"/{}/{}/{}\".format(\n CoordConstsV2.RSC_NETWORKS, session.network, CoordConstsV2.RSC_SNAPSHOTS\n )\n return _get_list(session, url_tail, {CoordConstsV2.QP_VERBOSE: verbose})",
"def list(self, detailed=True, search_opts=None):\n query_string = utils.build_query_param(search_opts, sort=True)\n\n detail = \"\"\n if detailed:\n detail = \"/detail\"\n\n return self._list(\"/group_snapshots%s%s\" % (detail, query_string),\n \"group_snapshots\")",
"def describe_snapshots(DirectoryId=None, SnapshotIds=None, NextToken=None, Limit=None):\n pass",
"def get_amis_of(snapshot_id):\n mes_amis = []\n # There has GOT to be a better way. Hmm... maybe not\n keys = Ims.spreadsheet.keys()\n for key in keys:\n if snapshot_id in Ims.spreadsheet[key]['associated_snapshots']:\n mes_amis.append(key)\n return mes_amis",
"def get_snap_list(mnode):\n\n ret, out, _ = g.run(mnode, \"gluster snapshot list --xml\")\n if ret != 0:\n g.log.error(\"Failed to execute 'snapshot list' on node %s. \"\n \"Hence failed to get the snapshot list.\", mnode)\n return None\n\n try:\n root = etree.XML(out)\n except etree.ParseError:\n g.log.error(\"Failed to parse the gluster snapshot \"\n \"list xml output.\")\n return None\n\n snap_list = []\n for snap in root.findall(\"snapList/snapshot\"):\n snap_list.append(snap.text)\n\n return snap_list",
"def get_snapshots_of(image):\n snapshot_ids = []\n device_mapping = image.block_device_mapping # dict of devices\n devices = device_mapping.keys()\n for device in devices:\n if device_mapping[device].snapshot_id is not None:\n snapshot_ids.append(device_mapping[device].snapshot_id.encode()) # do I need to have 'encode' here?\n return snapshot_ids",
"def get_experiment_metric_snapshot_v1(self, skill_id, experiment_id, metric_snapshot_id, **kwargs):\n # type: (str, str, str, **Any) -> Union[ApiResponse, object, GetExperimentMetricSnapshotResponse_b6905a35, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_experiment_metric_snapshot_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'metric_snapshot_id' is set\n if ('metric_snapshot_id' not in params) or (params['metric_snapshot_id'] is None):\n raise ValueError(\n \"Missing the required parameter `metric_snapshot_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/metricSnapshots/{metricSnapshotId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n if 'metric_snapshot_id' in params:\n path_params['metricSnapshotId'] = params['metric_snapshot_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_metric_snapshot_response.GetExperimentMetricSnapshotResponse\", status_code=200, message=\"Returned experiment metric data.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_metric_snapshot_response.GetExperimentMetricSnapshotResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def items(self):\n if self.__has_contents:\n return [dict(zip(['id', 'description', 'size', 'start_time', 'state'],\n [item['SnapshotId'], item['Description'], item['VolumeSize'],\n item['StartTime'], item['State']]))\n for item in self.__response['Snapshots']]\n else:\n return []",
"def ListSnapshots(self):\n file_names = sorted(\n [name[:-(len(Archive._SNAP_EXT))] for name in os.listdir(self._path)\n if name.endswith(Archive._SNAP_EXT)])\n timestamps = [datetime.datetime.strptime(x, Archive._TIME_FMT)\n for x in file_names]\n return timestamps",
"def vm_snapshotlist(args):\n snapshot = args.snapshot\n name = args.name\n config = Kconfig(client=args.client, debug=args.debug, region=args.region, zone=args.zone, namespace=args.namespace)\n k = config.k\n common.pprint(\"Listing snapshots of %s...\" % name)\n snapshots = k.snapshot(snapshot, name, listing=True)\n if isinstance(snapshots, dict):\n common.pprint(\"Vm %s not found\" % name, color='red')\n return\n else:\n for snapshot in snapshots:\n print(snapshot)\n return",
"def list_snapshots(self, detail=False, **params):\n url = 'snapshots'\n list_schema = schema.list_snapshots_no_detail\n if detail:\n url += '/detail'\n list_schema = schema.list_snapshots_with_detail\n if params:\n url += '?%s' % urllib.urlencode(params)\n\n resp, body = self.get(url)\n body = json.loads(body)\n self.validate_response(list_schema, resp, body)\n return rest_client.ResponseBody(resp, body)",
"def getSnapshotsD(region):\n # Can a snapshot belong to more than one AMI? Dunno, keep list just in case (so it never breaks due to it)\n snapshots = getSnapshots(region)\n snapshotsDicts = []\n ims = getImages(region)\n for s in snapshots:\n amis = getAmisOf(s, ims)\n amiIds = []\n amiKeeps = []\n\n if len(amis) == 1:\n amiIds = amis[0].id.encode()\n amiKeeps = getKeepTag(amis[0])\n\n elif len(amis) == 0:\n amiIds = \"-------no-AMI-found\"\n amiKeeps = \"-------no-AMI-found\"\n else:\n for a in amis:\n amiIds.append(a.id.encode())\n amiKeeps.append(getKeepTag(a))\n\n snapshotsDict = {\"id\": s.id,\n \"status\": s.status,\n \"region\": s.region.name,\n \"progress\": s.progress,\n \"start_time\": s.start_time,\n \"volume_id\": s.volume_id,\n \"volume_size\": s.volume_size,\n \"KEEP-tag\": getKeepTag(s),\n \"Name\": get_name_tag(s),\n \"AMI(s)\": amiIds,\n \"AMI_KEEP-tags\": amiKeeps,\n \"PROD\": isProduction(s),\n \"Description\": s.description\n }\n snapshotsDicts.append(snapshotsDict)\n return snapshotsDicts",
"def get_metric_history(\n self,\n metric_key: str,\n time_window: duration_pb2.Duration,\n min_timestamp: timestamp_pb2.Timestamp\n ) -> typing.List[float]:\n if not self._metric_store:\n raise ValueError('Metric history requested for {}, but no metric store '\n 'was provided to Collector.'.format(metric_key))\n\n if time_window.ToTimedelta():\n min_time = max(\n min_timestamp.ToDatetime(),\n self._event.start_time.ToDatetime() - time_window.ToTimedelta())\n else:\n min_time = min_timestamp.ToDatetime()\n\n history_rows = self._metric_store.get_metric_history(\n benchmark_id=(\n self._event.metric_collection_config.compare_to_benchmark_id or\n self._event.benchmark_id),\n metric_key=metric_key,\n min_time=min_time,\n )\n \n return [row.metric_value for row in history_rows]",
"def share_snapshot_access_get_all_for_snapshot_instance(\n context, snapshot_instance_id, filters=None,\n with_snapshot_access_data=True, session=None):\n session = session or get_session()\n filters = copy.deepcopy(filters) if filters else {}\n filters.update({'share_snapshot_instance_id': snapshot_instance_id})\n\n query = _share_snapshot_instance_access_get_query(context, session)\n\n legal_filter_keys = (\n 'id', 'share_snapshot_instance_id', 'access_id', 'state')\n\n query = exact_filter(\n query, models.ShareSnapshotInstanceAccessMapping, filters,\n legal_filter_keys)\n\n instance_accesses = query.all()\n\n if with_snapshot_access_data:\n instance_accesses = _set_instances_snapshot_access_data(\n context, instance_accesses, session)\n\n return instance_accesses",
"def database_volume_snapshot_get_list():\n db = database_get()\n\n session = db.session()\n query = session.query(model.VolumeSnapshot)\n\n volume_snapshot_objs = list()\n for volume_snapshot in query.all():\n nfvi_volume_snapshot_data = \\\n json.loads(volume_snapshot.nfvi_volume_snapshot_data)\n nfvi_volume_snapshot = nfvi.objects.v1.VolumeSnapshot(\n nfvi_volume_snapshot_data['uuid'],\n nfvi_volume_snapshot_data['name'],\n nfvi_volume_snapshot_data['description'],\n nfvi_volume_snapshot_data['size_gb'],\n nfvi_volume_snapshot_data['volume_uuid'])\n volume_snapshot_obj = objects.VolumeSnapshot(nfvi_volume_snapshot)\n volume_snapshot_objs.append(volume_snapshot_obj)\n return volume_snapshot_objs",
"def list_metrics(self):\n pass"
] | [
"0.6616442",
"0.6442018",
"0.62440395",
"0.6232199",
"0.6206233",
"0.61672056",
"0.6158984",
"0.6068512",
"0.60398465",
"0.6002138",
"0.59996754",
"0.595634",
"0.5944466",
"0.59274113",
"0.5893916",
"0.5795772",
"0.57936996",
"0.5766292",
"0.5766089",
"0.5755341",
"0.57362115",
"0.5721761",
"0.571658",
"0.5716263",
"0.5687674",
"0.5687035",
"0.5631748",
"0.56281936",
"0.56189317",
"0.5596446"
] | 0.68160546 | 0 |
Updates an existing experiment for a skill. Can only be called while the experiment is in CREATED state. | def update_experiment_v1(self, skill_id, experiment_id, update_experiment_request, **kwargs):
# type: (str, str, UpdateExperimentRequest_d8449813, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "update_experiment_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'experiment_id' is set
if ('experiment_id' not in params) or (params['experiment_id'] is None):
raise ValueError(
"Missing the required parameter `experiment_id` when calling `" + operation_name + "`")
# verify the required parameter 'update_experiment_request' is set
if ('update_experiment_request' not in params) or (params['update_experiment_request'] is None):
raise ValueError(
"Missing the required parameter `update_experiment_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/properties'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'experiment_id' in params:
path_params['experimentId'] = params['experiment_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'update_experiment_request' in params:
body_params = params['update_experiment_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update(self, request, pk=None):\n exp = Experiment.objects.get(pk=pk)\n serializer = ExperimentSerializer(exp, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return send_response(request.method, serializer)",
"def update(ctx, name, description, tags):\n user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'),\n ctx.obj.get('experiment'))\n update_dict = {}\n\n if name:\n update_dict['name'] = name\n\n if description:\n update_dict['description'] = description\n\n tags = validate_tags(tags)\n if tags:\n update_dict['tags'] = tags\n\n if not update_dict:\n Printer.print_warning('No argument was provided to update the experiment.')\n sys.exit(0)\n\n try:\n response = PolyaxonClient().experiment.update_experiment(\n user, project_name, _experiment, update_dict)\n except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n Printer.print_error('Could not update experiment `{}`.'.format(_experiment))\n Printer.print_error('Error message `{}`.'.format(e))\n sys.exit(1)\n\n Printer.print_success(\"Experiment updated.\")\n get_experiment_details(response)",
"def test_skills_updated(self):\n assert self.agent_config.skills == {self.new_skill_id}",
"def test_skills_updated(self):\n assert self.skill_config.skills == {self.new_skill_id}",
"def new_skill_interaction(self, skill):\n self.skill_interact[skill] = True",
"def get_experiment_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, GetExperimentResponse_fcd92c35, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\", status_code=200, message=\"Returned skill experiment.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def rename_experiment(self, experiment_id, new_name):\n return self.dbclient.update_by_id(Tables.EXPERIMENTS, experiment_id, {\n ExperimentAttr.NAME: new_name\n })",
"def create_experiment_v1(self, skill_id, create_experiment_request, **kwargs):\n # type: (str, CreateExperimentRequest_abced22d, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"create_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'create_experiment_request' is set\n if ('create_experiment_request' not in params) or (params['create_experiment_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_experiment_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_experiment_request' in params:\n body_params = params['create_experiment_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"Experiment created. Returns the generated experiment identifier in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def delete_experiment_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def refresh(self):\n connection = self._connection\n with self._refresh_lock:\n self._aiexperiment = connection.aiexperiments(self.id).fetch()",
"def addSkill(self, newskill):\n self.skills.append( newskill )",
"def update_experiment_description(self, experiment_id, description):\n return self.dbclient.update_by_id(Tables.EXPERIMENTS, experiment_id, {\n ExperimentAttr.DESC: description\n })",
"def skill(ctx: Context, public_id: PublicId):\n _eject_item(ctx, \"skill\", public_id)",
"def update(self, uuid, parameters):\n self._can_update(uuid)\n\n cur = self.conn.cursor()\n cur.execute(\n \"\"\"\n UPDATE experiments\n SET parameters = ?\n WHERE uuid = ?\n \"\"\", [json.dumps(parameters), uuid])\n cur.close()\n self.conn.commit()",
"def updateEMPStudy(self, study_id, study_name, investigation_type, miens_compliant, submit_to_insdc, \n portal_type, study_title, study_alias, pmid, study_abstract, study_description,\n number_samples_collected, number_samples_promised , lab_person,\n lab_person_contact, emp_person, first_contact, most_recent_contact, sample_type, \n has_physical_specimen, has_extracted_data, timeseries, spatial_series,\n principal_investigator, principal_investigator_contact, default_emp_status, funding,\n includes_timeseries):\n con = self.getMetadataDatabaseConnection()\n results = con.cursor().callproc('qiime_assets.emp_study_update', \n [study_id, study_name, investigation_type, miens_compliant, submit_to_insdc, portal_type, \n study_title, study_alias, pmid, study_abstract, study_description,\n number_samples_collected, number_samples_promised , lab_person,\n lab_person_contact, emp_person, first_contact, most_recent_contact, sample_type, \n has_physical_specimen, has_extracted_data, timeseries, spatial_series,\n principal_investigator, principal_investigator_contact, default_emp_status, funding,\n includes_timeseries])",
"def test_update(self):\n optimizer = \"RandomSearch\"\n name = \"test_init_experiment\"\n param_defs = {\n \"x\": MinMaxNumericParamDef(0, 1),\n \"name\": NominalParamDef([\"A\", \"B\", \"C\"])\n }\n minimization = True\n\n LAss = PrettyLabAssistant()\n LAss.init_experiment(name, optimizer, param_defs, minimization=minimization)\n cand = LAss.get_next_candidate(name)\n cand.result = 1\n LAss.update(name, cand)\n assert_items_equal(LAss.exp_assistants[name].experiment.candidates_finished, [cand])\n assert_equal(LAss.exp_assistants[name].experiment.candidates_finished[0].result, 1)",
"def modifySkill(skill, db, pwr):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if not skill_data:\n return colored(\"ERROR: Skill {S} is not in your skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n pwr = int(pwr)\n if pwr < 0:\n return colored(\"ERROR: Power value should alwasy be positive.\", \"red\", \"on_white\")\n db.execute(\n 'UPDATE mystatus SET power = ? WHERE skill = ?', (str(pwr), str(skill)))\n db.commit()\n return colored(\"{S}\\' power is modified from {OLD} -> {NEW}\".format(\n S=str(skill), OLD=str(skill_data['power']), NEW=str(pwr)), 'cyan')",
"def _can_update(self, uuid):\n cur = self.conn.cursor()\n\n cur.execute(\n \"\"\"\n SELECT parameters\n FROM experiments\n WHERE uuid = ?\n \"\"\", [uuid])\n\n row = cur.fetchone()\n\n exists = row is not None\n\n if exists:\n empty = row[0] is None\n\n if not empty:\n raise ValueError('Cannot update non-empty experiment with '\n 'uuid \"{}\"'.format(uuid))\n else:\n raise ValueError('Cannot update experiment with '\n 'uuid \"{}\" because it does '\n 'not exist'.format(uuid))",
"def upgrade_skill(self, skill_string):\r\n skill = self.__skills[skill_string]\r\n skill.skill_level += 1\r\n\r\n # Downgrading enabled the first time a skill is upgraded.\r\n if skill.skill_level == 1:\r\n self.skill_down_enable(skill_string)\r\n\r\n # Updates the UI and skill point value\r\n self.update_skill_level_info(skill_string)\r\n self.deduct_skill_points(skill.points_to_up)\r\n self.update_skill_info_box(skill_string)\r\n\r\n # Checks other requirements.\r\n for skill_string2 in self.__skills:\r\n self.check_skill_requirements(skill_string2)",
"def test_update(self):\n payload = {\n 'name': 'Pecho inclinado',\n 'description': \"New description\",\n 'muscle_group': \"pecho\"\n }\n response = self.client.put(\n '/exercises/{}/'.format(self.exer1.id), data=payload)\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(\n Exercise.objects.get(id=self.exer1.id).name, payload['name'])",
"def _saveExperiment(self, experiment, path):\n Experiment.save(experiment, path);",
"def update_in_process(self, experiment_id, experiment_name):\n self.cur.execute(\n \"\"\"\n INSERT INTO in_process\n VALUES\n (%(experiment_id)s, %(experiment_name)s)\n \"\"\",\n {\n 'experiment_id': experiment_id,\n 'experiment_name': experiment_name\n }\n )\n if self.status_message:\n self.return_status('INSERT')",
"def update(self, model: GenerativeDesignExecution) -> GenerativeDesignExecution:\n raise NotImplementedError(\"Cannot update a GenerativeDesignExecution.\")",
"def update_experience(uid, rid, increment):\n errmsg = []\n\n experience = Experience.query.filter(Experience.uid == uid).filter(Experience.rid == rid).first()\n if not experience:\n errmsg.append(\"Experience entry does not exist for the given user ID and restaurant ID.\")\n elif increment < 0:\n errmsg.append(\"Experience cannot be incremented by a negative number.\")\n\n if not errmsg:\n old_level = convert_experience_to_level(experience.experience)\n milestone = get_milestone(uid, rid)\n Experience.query.filter(Experience.uid == uid).filter(Experience.rid == rid).update(dict(experience=experience.experience + increment))\n db.session.commit()\n if milestone:\n new_level = convert_experience_to_level(experience.experience)\n if old_level < new_level and new_level == int(milestone[\"level\"]):\n update_points(uid, rid, milestone[\"reward\"])\n return None\n\n return errmsg",
"def update(self, expectation_suite: es.ExpectationSuite) -> es.ExpectationSuite:\n _client = client.get_instance()\n path_params = [\n \"project\",\n _client._project_id,\n \"featurestores\",\n self._feature_store_id,\n \"featuregroups\",\n self._feature_group_id,\n \"expectationsuite\",\n expectation_suite.id,\n ]\n\n headers = {\"content-type\": \"application/json\"}\n payload = expectation_suite.json()\n\n major, minor = self._variable_api.parse_major_and_minor(\n self._variable_api.get_version(\"hopsworks\")\n )\n method = \"PUT\"\n if major == \"3\" and minor == \"0\":\n method = \"POST\"\n del path_params[-1]\n\n return es.ExpectationSuite.from_response_json(\n _client._send_request(method, path_params, headers=headers, data=payload)\n )",
"async def skill(self, ctx, *, skill: str):\n\n try:\n skill = self.get_entry('Skill', skill.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = skill['Name']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://skill.png')\n embed.add_field(name='Learned', value=skill['Class/Rank'], inline=False)\n embed.add_field(name='Effect', value=skill['Effect'])\n\n await ctx.send(file=discord.File(f'xenox/skills/{name}.png', 'skill.png'), embed=embed)",
"def test_update_study(self):\n study_spec = sample_study_spec()\n study_id = self.storage.create_study(study_spec)\n self.assertEqual(study_pb2.StudySpec.STATE_ENABLED, study_spec.state)\n self.assertEqual('test', study_spec.name)\n creation_time = study_spec.creation_time.ToDatetime()\n\n study_spec.name = 'changed test'\n study_spec.state = study_pb2.StudySpec.STATE_DISABLED\n study_spec.creation_time.GetCurrentTime()\n self.storage.update_study(study_spec)\n\n study_spec = self.storage.get_study(study_id)\n self.assertIsNotNone(study_spec)\n assert study_spec # To disable attribute-error\n self.assertEqual('changed test', study_spec.name)\n # Creation time and status should not change.\n self.assertEqual(study_pb2.StudySpec.STATE_ENABLED, study_spec.state)\n self.assertEqual(creation_time, study_spec.creation_time.ToDatetime())",
"def _set_skill(caller, _, **kwargs):\n pool = _skill_pool(caller, kwargs.get(\"skill\"))\n caller.db.d1_skills[kwargs.get(\"skill\")][\"rank\"] += 1\n caller.ndb.pregen[\"skills\"] = pool\n\n return \"node_skills\"",
"def updateEMPSampleData(self, sample_id, sample_score, emp_status, web_app_user_id):\n con = self.getMetadataDatabaseConnection()\n con.cursor().callproc('qiime_assets.update_emp_sample_data', [sample_id, sample_score, emp_status, web_app_user_id])",
"def updateEMPStudyData(self, study_id, study_score, web_app_user_id):\n con = self.getMetadataDatabaseConnection()\n con.cursor().callproc('qiime_assets.update_emp_study_data', [study_id, study_score, web_app_user_id])"
] | [
"0.68745476",
"0.6748701",
"0.67074144",
"0.6631993",
"0.6051414",
"0.58201027",
"0.57306343",
"0.5718586",
"0.5717914",
"0.5670553",
"0.5647306",
"0.5542362",
"0.5484",
"0.54711837",
"0.5465292",
"0.54574466",
"0.54118466",
"0.54024833",
"0.5390156",
"0.5381335",
"0.53402597",
"0.53074956",
"0.5294385",
"0.52938926",
"0.52603734",
"0.52518785",
"0.5203088",
"0.5159602",
"0.51537544",
"0.5116757"
] | 0.70709527 | 0 |
Retrieves the current user's customer treatment override for an existing A/B Test experiment. The current user must be under the same skill vendor of the requested skill id to have access to the resource. | def get_customer_treatment_override_v1(self, skill_id, experiment_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, GetCustomerTreatmentOverrideResponse_f64f689f, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "get_customer_treatment_override_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'experiment_id' is set
if ('experiment_id' not in params) or (params['experiment_id'] is None):
raise ValueError(
"Missing the required parameter `experiment_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/treatmentOverrides/~current'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'experiment_id' in params:
path_params['experimentId'] = params['experiment_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.experiment.get_customer_treatment_override_response.GetCustomerTreatmentOverrideResponse", status_code=200, message="Returned customer treatment override details."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.experiment.get_customer_treatment_override_response.GetCustomerTreatmentOverrideResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_customer_treatment_override_v1(self, skill_id, experiment_id, set_customer_treatment_override_request, **kwargs):\n # type: (str, str, SetCustomerTreatmentOverrideRequest_94022e79, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"set_customer_treatment_override_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'set_customer_treatment_override_request' is set\n if ('set_customer_treatment_override_request' not in params) or (params['set_customer_treatment_override_request'] is None):\n raise ValueError(\n \"Missing the required parameter `set_customer_treatment_override_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/treatmentOverrides/~current'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'set_customer_treatment_override_request' in params:\n body_params = params['set_customer_treatment_override_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def adjustment(self, uuid):\r\n return ads.Adjustment(self, uuid)",
"def treatment(self):\n return self.get_treatment(self.context)",
"def user_data_override(self) -> Optional[str]:\n return pulumi.get(self, \"user_data_override\")",
"def tax_override(self):\n return self._tax_override",
"def get_entity(self):\n if self.override_entity and not self.override_entity.abstract_entity:\n return self.override_entity\n elif self.get_role():\n return self.get_role().entity\n return None",
"def _set_OPTION_beneficiary_customer(self):\n getter_name = ''\n if self.use_operations_xml:\n beneficiary_customer_option = FSwiftWriterUtils.get_value_from_xml_tag(self.swift_metadata_xml_dom,\n ['SWIFT',\n 'BENEFICIARY_CUSTOMER_OPTION'])\n else:\n beneficiary_customer_option = self.get_beneficiary_customer_option()\n if beneficiary_customer_option == \"A\":\n getter_name = 'beneficiary_customer_59A'\n elif beneficiary_customer_option == \"NO OPTION\":\n getter_name = 'beneficiary_customer_no_option_59'\n elif beneficiary_customer_option == \"F\":\n getter_name = 'beneficiary_customer_59F'\n else:\n notifier.WARN(\"%s Option %s is not supported for tag %s. Mapping default option.\" % (\n self.swift_message_type, str(beneficiary_customer_option), 'BeneficiaryCustomer_59a'))\n getter_name = 'beneficiary_customer_59A' # default\n return getter_name",
"def getDiseaseToTreatWith(self, disease):\r\n if disease is None:\r\n disease = self.city.disease\r\n return disease",
"def get_experiment(self, experiment_name : str):\n return self._df[self._df.experiment == experiment_name]",
"def getManualOverride(self, ins):\n if self.actionsForTrades:\n for t in ins.trades():\n if t.trdnbr in self.actionsForTrades:\n action = self.actionsForTrades[t.trdnbr]\n msg = ('Found {0}: {1}.'.format(t.trdnbr, action))\n Logme()(msg, 'DEBUG')\n if action == 'Exercise' or action == 'Abandon':\n return action\n return None",
"def get_effective_agent(self):\n raise Unimplemented()",
"def get_beneficiary_customer_option(self):\n option = 'A'\n bic = ''\n counterparty_reference = self.acm_obj.CounterpartyAccountRef()\n if counterparty_reference and counterparty_reference.NetworkAlias():\n bic = counterparty_reference.NetworkAlias().Alias()\n if not bic and self.acm_obj.Counterparty():\n bic = self.acm_obj.Counterparty().Swift()\n if not bic:\n option = 'NO OPTION'\n return option",
"def get_customer(self):\n return self._customer",
"def get_customer(self):\n return self._customer",
"def get_taste(self):\n\n try:\n taste = Taste.objects.get(user_id=self.id)\n except DoesNotExist:\n print \"No taste object found. Creating one now.\"\n taste = Taste(user_id=self.id)\n taste.save()\n\n return taste",
"def get_intervention(self):\n return self.PotTax_intervention",
"def test_get_overrides(self):\n # FormOverrideMixIn.get_overrides\n pass",
"def getCustomer(self):\n return self._Customer",
"def customer(self):\n return Customer(self._dict.get('customer'))",
"def get_attestation(self, witness, vu):\n return self.all_attestations()[witness].get(vu)",
"def filter_contiguity_overrides(self):\n return self.filter_nodes('//ContiguityOverrides/ContiguityOverride')",
"def Agency(self, default=None):\n return self.data.get('agency', default)",
"def get_merchant(self):\n\n merchant_model = {\n \"name\": self.fake.company()\n }\n\n return self.client.merchants.create(merchant_model)",
"def _setbeneficiary_customer_59A(self, val):\n self.swift_obj.BeneficiaryCustomer_A = val\n self.swift_obj.BeneficiaryCustomer_A.swiftTag = '59A'",
"def conditional_overrides(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['GoogleCloudChannelV1ConditionalOverrideArgs']]]]:\n return pulumi.get(self, \"conditional_overrides\")",
"def getCustomer(self):\n return self.base.get(\"customer\", [])",
"def get_current_customer(self):\n def _random_string():\n random_string = u''.join(random.choice(\n string.ascii_uppercase + string.ascii_uppercase)\n for _ in range(20))\n return random_string\n\n id = _random_string()\n owner_id = _random_string()\n\n current_customer = {\n u'can_edit_matches': u'0',\n u'can_read_public_ip_list': u'0',\n u'can_upload_vcl': u'1',\n u'updated_at': u'2014-11-03T23:37:44+00:00',\n u'has_config_panel': u'1',\n u'has_improved_ssl_config': False,\n u'id': id,\n u'has_historical_stats': u'1',\n u'has_openstack_logging': u'0',\n u'can_configure_wordpress': u'0',\n u'has_improved_logging': u'1',\n u'readonly': '',\n u'ip_whitelist': u'0.0.0.0/0',\n u'owner_id': owner_id,\n u'phone_number': u'770-123-1749',\n u'postal_address': None,\n u'billing_ref': None,\n u'can_reset_passwords': True,\n u'has_improved_security': u'1',\n u'stripe_account': None,\n u'name': u'Poppy - Test',\n u'created_at': u'2014-11-03T23:37:43+00:00',\n u'can_stream_syslog': u'1',\n u'pricing_plan': u'developer',\n u'billing_contact_id': None,\n u'has_streaming': u'1'}\n return current_customer",
"def customer(self):\n return self.__customer",
"def can_override_user(request):\n if not hasattr(request, \"can_override_user\"):\n request.can_override_user = can_override()\n return request.can_override_user",
"def getCustomerAccount(self):\n return self._CustomerAccount"
] | [
"0.6317194",
"0.4652294",
"0.4624771",
"0.46243167",
"0.4533612",
"0.44541585",
"0.44269043",
"0.4356287",
"0.43488264",
"0.4329361",
"0.43277022",
"0.4321323",
"0.43182027",
"0.43182027",
"0.42814377",
"0.42804077",
"0.42282712",
"0.4195337",
"0.41915858",
"0.4162887",
"0.41407326",
"0.41353628",
"0.41342816",
"0.4126272",
"0.41237262",
"0.4121272",
"0.411542",
"0.40999553",
"0.40959895",
"0.40473908"
] | 0.7399519 | 0 |
Adds the requesting user's customer treatment override to an existing experiment. The current user must be under the same skill vendor of the requested skill id to have access to the resource. Only the current user can attempt to add the override of their own customer account to an experiment. Can only be called before the experiment is enabled. | def set_customer_treatment_override_v1(self, skill_id, experiment_id, set_customer_treatment_override_request, **kwargs):
# type: (str, str, SetCustomerTreatmentOverrideRequest_94022e79, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "set_customer_treatment_override_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'experiment_id' is set
if ('experiment_id' not in params) or (params['experiment_id'] is None):
raise ValueError(
"Missing the required parameter `experiment_id` when calling `" + operation_name + "`")
# verify the required parameter 'set_customer_treatment_override_request' is set
if ('set_customer_treatment_override_request' not in params) or (params['set_customer_treatment_override_request'] is None):
raise ValueError(
"Missing the required parameter `set_customer_treatment_override_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/treatmentOverrides/~current'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'experiment_id' in params:
path_params['experimentId'] = params['experiment_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'set_customer_treatment_override_request' in params:
body_params = params['set_customer_treatment_override_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Success. No content."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="PUT",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_customer_treatment_override_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, GetCustomerTreatmentOverrideResponse_f64f689f, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_customer_treatment_override_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}/treatmentOverrides/~current'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.experiment.get_customer_treatment_override_response.GetCustomerTreatmentOverrideResponse\", status_code=200, message=\"Returned customer treatment override details.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.experiment.get_customer_treatment_override_response.GetCustomerTreatmentOverrideResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def _set_override_role_called(self):\n self.__override_role_called = True",
"def set_override(self, charger, override_time,\n energy_at_plugin, energy_to_add):\n data = {\n \"device_id\": self.uuid,\n \"cmd\": \"set_override\",\n \"token\": charger.token(),\n \"account_token\": self.api_token,\n \"override_time\": override_time,\n \"energy_at_plugin\": energy_at_plugin,\n \"energy_to_add\": energy_to_add\n }\n\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n response = requests.post(\"{}/box_api_secure\".format(self.BASE_URL),\n data=json.dumps(data),\n headers=headers)\n response_json = response.json()\n return response_json",
"def set_override(self, name, override, group=None):\n opt_info = self._get_opt_info(name, group)\n opt_info['override'] = self._get_enforced_type_value(\n opt_info['opt'], override)\n opt_info['location'] = LocationInfo(\n Locations.set_override,\n _get_caller_detail(3), # this function has a decorator to skip\n )",
"def can_override_user(request):\n if not hasattr(request, \"can_override_user\"):\n request.can_override_user = can_override()\n return request.can_override_user",
"def add_over(self: CorridorGroup, override: CorridorGroup) -> None:\n for key, corr_over in override.corridors.items():\n try:\n corr_base = self.corridors[key]\n except KeyError:\n self.corridors[key] = corr_over\n else:\n corr_base.extend(corr_over)",
"def _setbeneficiary_customer_59A(self, val):\n self.swift_obj.BeneficiaryCustomer_A = val\n self.swift_obj.BeneficiaryCustomer_A.swiftTag = '59A'",
"def add_override_argument(parser, *names, **kwargs):\r\n if not names:\r\n names = DEFAULT_OVERRIDE_OPTION_NAMES\r\n dest = kwargs.pop('dest', None)\r\n required = kwargs.pop('required', False)\r\n help = kwargs.pop('help', 'extra overrides to apply to the config')\r\n if kwargs:\r\n raise TypeError('add_override_argument() got an invalid keyword argument: %s' %\r\n list(kwargs)[0])\r\n\r\n ov_container = ConfigContainer()\r\n ov_container.get_metadata().is_override_set = True\r\n parser.add_argument(\r\n *names,\r\n dest=dest,\r\n default=ov_container,\r\n required=required,\r\n action=_add_to_override_set,\r\n type=_dict_from_string,\r\n help=help\r\n )",
"def _setbeneficiary_customer_no_option_59(self, val):\n self.swift_obj.BeneficiaryCustomer = val\n self.swift_obj.BeneficiaryCustomer.swiftTag = '59'",
"def setup_ec2_launch_override_to_emulate_ice(\n cluster, single_instance_type_ice_cr=\"\", multi_instance_types_ice_cr=\"\", multi_instance_types_exp_cr=\"\"\n):\n remote_command_executor = RemoteCommandExecutor(cluster)\n\n # fmt: off\n remote_command_executor.run_remote_script(\n script_file=str(SCALING_COMMON_DATADIR / \"overrides.sh\"),\n args=[\n f\"--single-instance-type-ice-cr \\\"{single_instance_type_ice_cr}\\\"\",\n f\"--multi-instance-types-ice-cr \\\"{multi_instance_types_ice_cr}\\\"\",\n f\"--multi-instance-types-exp-cr \\\"{multi_instance_types_exp_cr}\\\"\",\n ],\n run_as_root=True,\n )\n # fmt: on",
"def patch(self, account=None, user=None, account_id=None):\n return super().patch()",
"def applyEffect(self, user, target, environment):\n pkmn = self.getEffectedPokemon(user, target)\n self.affectPkmn(pkmn)",
"def process_overrides(self, db, dest, kvargs, lines):\n logging.info(\"process_overrides db:{} dest:{} kvargs:{} \".format(db.name,dest,kvargs))\n keyword = kvargs['keyword']\n db.create_overrides(keyword)\n return True",
"def override(overridden):\n def decorator(overriding):\n overridden.override(overriding)\n return overriding\n return decorator",
"def _set_override_role_caught_exc(self):\n self.__override_role_caught_exc = True",
"def add_override_flags(parser):\n override_group = parser.add_mutually_exclusive_group(required=False)\n override_group.add_argument('--override', action='store_true', dest='override',\n help='Allow overriding values in input file with values from CLI arguments. '\n 'Overriding values is disallowed by default. '\n 'Adding the --no-override flag explicitly disallows overriding values.')\n override_group.add_argument('--no-override', action='store_false', dest='override', help=argparse.SUPPRESS)",
"def add_customer(self, Customer):\n self._customer_repo.add_customer(Customer)",
"def service_set_override(call):\n entity_id = call.data.get(ATTR_ENTITY_ID)\n temperature = call.data.get(ATTR_TEMPERATURE)\n until = call.data.get(\n ATTR_UNTIL, (datetime.now() + timedelta(hours=1)).strftime(\"%H:%M\")\n )\n target_devices = [\n dev for dev in hass.data[DOMAIN][\"entities\"] if dev.entity_id in entity_id\n ]\n target_device: WarmupThermostat\n for target_device in target_devices:\n target_device.set_override(temperature, until)\n target_device.schedule_update_ha_state(True)",
"def addCustomEffect(self, effect, override):\n effectId = effect.getType().getId()\n existing = None\n for mobEffect in getHandle().effects:\n if MobEffectList.getId(mobEffect.getMobEffect()) == effectId:\n existing = mobEffect\n if existing != None:\n if not override:\n return False\n self.getHandle().effects.remove(existing)\n self.getHandle().a(CraftPotionUtil.fromBukkit(effect))\n self.getHandle().refreshEffects()\n return True",
"def makeOverrides(self):\n\t\tself.overridesWithValues = self.dataOverrides",
"def inject_overrides(self, overrides):\n for run in self.benchmarks:\n _ = [run.update_spec(key, value) for key, value in overrides.items()]",
"def tax_override(self, tax_override):\n\n self._tax_override = tax_override",
"def assign_client_to_experiment(self, client_id, experiment_id):\n experimentgroups = Experiment.get(experiment_id).experimentgroups\n if len(experimentgroups) == 1:\n experimentgroup = experimentgroups[0]\n else:\n experimentgroup = experimentgroups[random.randint(0, len(experimentgroups) - 1)]\n self.dbsession.query(Client)\\\n .filter_by(id=client_id).first()\\\n .experimentgroups.append(experimentgroup)",
"def cassette(self, request, recorder, cassette_name):\n global used_cassettes\n kwargs = {}\n for marker in request.node.iter_markers(\"add_placeholder\"):\n for key, value in marker.kwargs.items():\n recorder.config.default_cassette_options[\"placeholders\"].append(\n {\"placeholder\": f\"<{key.upper()}>\", \"replace\": value}\n )\n for marker in request.node.iter_markers(\"recorder_kwargs\"):\n for key, value in marker.kwargs.items():\n # Don't overwrite existing values since function markers are provided\n # before class markers.\n kwargs.setdefault(key, value)\n with recorder.use_cassette(cassette_name, **kwargs) as recorder:\n cassette = recorder.current_cassette\n if cassette.is_recording():\n ensure_environment_variables()\n yield recorder\n ensure_integration_test(cassette)\n used_cassettes.add(cassette_name)",
"def review_requested_by(self, review_requested_by):\n\n self._review_requested_by = review_requested_by",
"def override_account_fields(self,\n settled_cash=not_overridden,\n accrued_interest=not_overridden,\n buying_power=not_overridden,\n equity_with_loan=not_overridden,\n total_positions_value=not_overridden,\n total_positions_exposure=not_overridden,\n regt_equity=not_overridden,\n regt_margin=not_overridden,\n initial_margin_requirement=not_overridden,\n maintenance_margin_requirement=not_overridden,\n available_funds=not_overridden,\n excess_liquidity=not_overridden,\n cushion=not_overridden,\n day_trades_remaining=not_overridden,\n leverage=not_overridden,\n net_leverage=not_overridden,\n net_liquidation=not_overridden):\n # mark that the portfolio is dirty to override the fields again\n self._dirty_account = True\n self._account_overrides = kwargs = {\n k: v for k, v in locals().items() if v is not not_overridden\n }\n del kwargs['self']",
"def _AddAddUpgradeSoakingOverrideFlag(\n self, group: parser_arguments.ArgumentInterceptor\n ):\n group.add_argument(\n '--add-upgrade-soaking-override',\n type=arg_parsers.Duration(),\n required=True,\n help=\"\"\"\\\n Overrides the soaking time for a particular upgrade name and version\n propagating through the current fleet. Set soaking to 0 days to bypass\n soaking and fast-forward the upgrade to the downstream fleet.\n\n See `$ gcloud topic datetimes` for information on duration formats.\n \"\"\",\n )",
"def test_adv_w_customer_ad_rep(self):\n ad_rep = AdRep.objects.get(id=1000)\n ad_rep.rank = 'CUSTOMER'\n ad_rep.save()\n self.prep_ad_rep(ad_rep)\n UnqualifiedConsumerEmailTask().run(test_mode=self.consumer)\n self.common_asserts()",
"def invoice_pay_customer(self, cr, uid, ids, context=None):\n res = super(account_invoice, self).invoice_pay_customer(cr, uid, ids, context=context)\n print \"IN CUSTOM INVOICE_PAY_CUSTOMER\"\n partner_obj = self.pool.get('res.partner')\n br = partner_obj.browse(cr, uid, res['context']['default_partner_id'], context=None)\n res['context'].update({'default_check_owner' : br.name})\n return res",
"def mitigated_by(self, mitigated_by):\n\n self._mitigated_by = mitigated_by"
] | [
"0.62492144",
"0.5331574",
"0.5301613",
"0.50894016",
"0.5034513",
"0.48581028",
"0.48009104",
"0.4797571",
"0.47946864",
"0.4712951",
"0.46884036",
"0.46781746",
"0.4669593",
"0.46669433",
"0.4658773",
"0.46532044",
"0.46474367",
"0.46420807",
"0.4633251",
"0.46285444",
"0.46192428",
"0.46187475",
"0.4591158",
"0.45500395",
"0.45396632",
"0.45366403",
"0.45333195",
"0.4526847",
"0.4513028",
"0.44920608"
] | 0.67168695 | 0 |
Gets a list of all experiments associated with this skill id. | def list_experiments_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, ListExperimentsResponse_c5b07ecb]
operation_name = "list_experiments_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.experiment.list_experiments_response.ListExperimentsResponse", status_code=200, message="Returned skill experiments."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.experiment.list_experiments_response.ListExperimentsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_client_experiments_list(self, id):\n experimentgroups = self.get_experimentgroups_for_client(id)\n experiments = []\n for experimentgroup in experimentgroups:\n experiments.append(experimentgroup.experiment)\n return experiments",
"def list(self, request):\n exp = Experiment.objects.all()\n serializer = ExperimentSerializer(exp, many=True)\n return send_response(request.method, serializer)",
"def list_experiments(self):\n subfolders = self.um.list_subfolders(\"data/*/\")\n experiment_folders = self.um.list_experiments(subfolders)\n experiments = list()\n for exp in experiment_folders:\n try:\n date = self.um.timestamp_to_date(int(exp) / 1000)\n exp_class = experiment.experiment(new_experiment=False, ts=exp)\n\n if \"label\" in exp_class.metadata:\n label = exp_class.metadata[\"label\"]\n else:\n label = None\n\n exp_dict = {\"date\": date,\n \"ts\": exp,\n \"label\": label\n }\n experiments.append(exp_dict)\n except:\n print \"Skipped\"\n\n return render_template('experiments.html', user=experiments)",
"def get_all_of_experiment(self, experiment_name: str):\n query = (\n f\"SELECT * FROM {self.table_name} WHERE experiment_name='{experiment_name}'\"\n )\n c = self.db.cursor()\n c.execute(query)\n queries = c.fetchall()\n return queries",
"def experiments(self, key, value):\n experiments = self.get('experiments', [])\n\n name = value.get('e')\n recid = value.get('0')\n record = get_record_ref(recid, 'experiments')\n\n experiments.append({\n 'curated_relation': record is not None,\n 'name': name,\n 'record': record\n })\n\n return experiments",
"def all_present_experiments(self):\n return _yield_subdir_names(self.exp_configs)",
"def experiments(ctx, **kw):\n if not ctx.invoked_subcommand:\n ctx.invoke(list_experiments, **kw)\n else:\n if _params_specified(kw):\n print(\n \"options cannot be listed before command ('%s')\"\n % ctx.invoked_subcommand)",
"def export_experiments(self, included_statuses=None):\n\t\texperiment_list = []\n\n\t\tif included_statuses is not None:\n\t\t\tfor run in self.discover_all_runs():\n\t\t\t\tstatus = run.get_status()\n\t\t\t\tif status in included_statuses:\n\t\t\t\t\texperiment_list.append((\n\t\t\t\t\t\trun.experiment.name,\n\t\t\t\t\t\ttuple(variant.name for variant in run.experiment.variation),\n\t\t\t\t\t\trun.instance.shortname,\n\t\t\t\t\t\tstr(status)\n\t\t\t\t\t))\n\t\tself.writeback_status_cache()\n\t\treturn experiment_list",
"def get_all_running_experiments(self):\n date_time_now = datetime.datetime.now()\n return self.dbsession.query(Experiment).filter(\n and_(Experiment.startDatetime <= date_time_now,\n date_time_now <= Experiment.endDatetime)).all()",
"def experiences(self):\n return self.client.call('GET',\n self.name + 'experiences')",
"def get_dataitems_for_experiment(self, id):\n experiment = Experiment.get(id)\n dataitems = []\n for expgroup in experiment.experimentgroups:\n dataitems.extend(self.get_dataitems_for_experimentgroup(expgroup.id))\n return dataitems",
"def get_experiment_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, GetExperimentResponse_fcd92c35, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\", status_code=200, message=\"Returned skill experiment.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def _build_experiment_tsaseq_embedded_list():\n antibody_embeds = DependencyEmbedder.embed_defaults_for_type(\n base_path='antibody',\n t='antibody')\n secondary_antibody_embeds = DependencyEmbedder.embed_defaults_for_type(\n base_path='secondary_antibody',\n t='antibody')\n return (\n Experiment.embedded_list + antibody_embeds + secondary_antibody_embeds\n )",
"def AcceleratorExperiments(self, default=[{}]):\n tmp = self.data.get('metadata', {}).get('accelerator_experiments', default)\n return [HEP.AcceleratorExperimentObject(i) for i in tmp]",
"def _build_experiment_seq_embedded_list():\n antibody_embeds = DependencyEmbedder.embed_defaults_for_type(\n base_path='antibody',\n t='antibody')\n return (\n Experiment.embedded_list + antibody_embeds\n )",
"def _build_experiment_chiapet_embedded_list():\n antibody_embeds = DependencyEmbedder.embed_defaults_for_type(\n base_path='antibody',\n t='antibody')\n return (\n Experiment.embedded_list + antibody_embeds\n )",
"def get_experience(self):\n return self.experience_set.all()",
"def _build_experiment_repliseq_embedded_list():\n antibody_embeds = DependencyEmbedder.embed_defaults_for_type(\n base_path='antibody',\n t='antibody')\n return (\n Experiment.embedded_list + antibody_embeds\n )",
"def get_all_experiments(name, path):\n folder_contents = get_folders_content(path) # dict of lists of content\n experiment = dict_of_lists_to_list_of_dicts(folder_contents)\n\n return {(get_name_from_experiment(name, ex)): ex for ex in experiment}",
"def experiments(ctx, metrics, params, query, sort, page):\n user, project_name, _group = get_project_group_or_local(ctx.obj.get('project'),\n ctx.obj.get('group'))\n page = page or 1\n try:\n response = PolyaxonClient().experiment_group.list_experiments(username=user,\n project_name=project_name,\n group_id=_group,\n metrics=metrics,\n params=params,\n query=query,\n sort=sort,\n page=page)\n except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:\n Printer.print_error('Could not get experiments for group `{}`.'.format(_group))\n Printer.print_error('Error message `{}`.'.format(e))\n sys.exit(1)\n\n meta = get_meta_response(response)\n if meta:\n Printer.print_header('Experiments for experiment group `{}`.'.format(_group))\n Printer.print_header('Navigation:')\n dict_tabulate(meta)\n else:\n Printer.print_header('No experiments found for experiment group `{}`.'.format(_group))\n\n if metrics:\n objects = get_experiments_with_metrics(response)\n elif params:\n objects = get_experiments_with_params(response)\n else:\n objects = [Printer.add_status_color(o.to_light_dict(humanize_values=True))\n for o in response['results']]\n objects = list_dicts_to_tabulate(objects)\n if objects:\n Printer.print_header(\"Experiments:\")\n objects.pop('experiment_group', None)\n objects.pop('experiment_group_name', None)\n objects.pop('project_name', None)\n dict_tabulate(objects, is_list_dict=True)",
"def get_experiments(redis, active=True):\n\n key = ACTIVE_EXPERIMENTS_REDIS_KEY if active else ARCHIVED_EXPERIMENTS_REDIS_KEY\n return [Experiment(redis, escape.to_unicode(name)) for name in redis.smembers(key)]",
"def all_experiments():\n elo_explain_experiments()\n alpha_beta_experiments()\n mtcs_experiments()",
"def get_clients_for_experiment(self, id):\n experiment = Experiment.get(id)\n if experiment is None:\n return None\n clients = []\n for experimentgroup in experiment.experimentgroups:\n clients.extend(experimentgroup.clients)\n return clients",
"def get_all_explorations():\n return [exp_domain.Exploration(e) for e in\n exp_models.ExplorationModel.get_all()]",
"def measurements(self):\n exp_type = 'Q_MS_MEASUREMENT'\n path = \"/%s/%s\" % (space, project)\n search = self.transaction.getSearchService()\n exps = search.listExperiments(path)\n return [exp for exp in exps if exp.getExperimentType() == exp_type]",
"def getEMPStudyList(self):\n try:\n studies = []\n con = self.getMetadataDatabaseConnection()\n results = con.cursor()\n con.cursor().callproc('qiime_assets.get_emp_study_list', [results])\n for row in results:\n # study_id, sample_id, sample_name, project_name, study_title, email, sample_count, metadata_complete,\n # study_score, sample_score, s.number_samples_promised, s.number_samples_in_freezer, \n # s.principal_investigator\n studies.append((row[0], row[1], row[2], row[3], row[4], row[5],\n row[6], row[7], row[8], row[9], row[10], row[11], row[12]))\n return studies\n except Exception, e:\n print 'Exception caught: %s.\\nThe error is: %s' % (type(e), e)",
"def experiment_runs (ins, exp) :\n return experiment_info.experiment_runs(ins, exp)",
"def get_exercises(self):\n exercises = set()\n for er in self.exercise_recordings:\n if er.exercise not in exercises:\n exercises.add(er.exercise)\n return list(exercises)",
"def get_finished_experiments(self, session):\n from expfactory.database.models import Participant, Result\n\n finished = []\n subid = session.get(\"subid\")\n\n if subid is not None:\n p = Participant.query.filter(\n Participant.id == subid\n ).first() # better query here\n\n # Get results for the participant\n for result in Result.query.filter(participant_id=p.id):\n finished.append(result.exp_id)\n return finished",
"def experiment(self):\n return self._experiment"
] | [
"0.7401268",
"0.66809076",
"0.66416746",
"0.64918095",
"0.64363277",
"0.6410691",
"0.63436115",
"0.6262714",
"0.62536496",
"0.6202606",
"0.6166123",
"0.6165092",
"0.61640954",
"0.6128164",
"0.61054105",
"0.60725933",
"0.6006383",
"0.5996345",
"0.59678626",
"0.5933828",
"0.5855665",
"0.58186793",
"0.5814614",
"0.5809746",
"0.5771974",
"0.57714444",
"0.5752721",
"0.5725505",
"0.57231754",
"0.5716302"
] | 0.7309211 | 1 |
Create a new experiment for a skill. | def create_experiment_v1(self, skill_id, create_experiment_request, **kwargs):
# type: (str, CreateExperimentRequest_abced22d, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "create_experiment_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'create_experiment_request' is set
if ('create_experiment_request' not in params) or (params['create_experiment_request'] is None):
raise ValueError(
"Missing the required parameter `create_experiment_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/experiments'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_experiment_request' in params:
body_params = params['create_experiment_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message="Experiment created. Returns the generated experiment identifier in 'Location' header."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def newExperiment(self):\n experiment = Experiment()\n newtitle = 'Untitled ' + self.getNextUntitled()\n experimentFrame = SequenceFrame(self, experiment, True, newtitle)\n experiment.setInteractionParameters(parentFrame=experimentFrame,\n graphManagerClass=StandardGraphManager)\n self.frames.append(experimentFrame)\n self.names.append(newtitle)\n log.info('Created experiment ' + newtitle)\n experimentFrame.Show()\n testFrame = tf.TestingFrame(experimentFrame, experiment)\n testFrame.Show()\n self.Show(False)",
"def create_experiment_if_needed(tr):\n exp = tr.getExperiment(EXPERIMENT_ID)\n if None == exp:\n create_project_if_needed(tr)\n exp = tr.createNewExperiment(EXPERIMENT_ID, 'DEFAULT_EXPERIMENT')\n \n return exp",
"def create(self, request):\n serializer = ExperimentSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n\n return send_response(request.method, serializer)",
"def create_experiment(self):\n experiment = wandb.init(\n name=self._name, dir=self._dir, project=self._project,\n anonymous=self._anonymous, reinit=True, id=self._id,\n resume='allow', tags=self._tags, entity=self._entity\n )\n wandb.run.save()\n return experiment",
"def create(self):\n # type: () -> AbstractSkill\n raise NotImplementedError",
"def new_skill_interaction(self, skill):\n self.skill_interact[skill] = True",
"def _create_or_get_experiment(self) -> tensorboard_experiment.TensorboardExperiment:\n logger.info(\"Creating experiment\")\n\n tb_experiment = tensorboard_experiment.TensorboardExperiment(\n description=self._description, display_name=self._experiment_display_name\n )\n\n try:\n experiment = self._api.create_tensorboard_experiment(\n parent=self._tensorboard_resource_name,\n tensorboard_experiment=tb_experiment,\n tensorboard_experiment_id=self._experiment_name,\n )\n self._is_brand_new_experiment = True\n except exceptions.AlreadyExists:\n logger.info(\"Creating experiment failed. Retrieving experiment.\")\n experiment_name = os.path.join(\n self._tensorboard_resource_name, \"experiments\", self._experiment_name\n )\n experiment = self._api.get_tensorboard_experiment(name=experiment_name)\n return experiment",
"def make_experiment(\n path, experiment_name, experiment_info, verbosity, log_dir, output_path\n):\n experiment_dir = output_path / experiment_name\n if experiment_dir.is_dir():\n return\n experiment_dir.mkdir(parents=True)\n\n experiment_params = get_experiment_params(experiment_name, verbosity, log_dir)\n with (experiment_dir / \"experiment_params.json\").open(\"w\") as f:\n json.dump(experiment_params, f)\n\n for filename, filepath in experiment_info.items():\n filename += \".json\"\n new_path = experiment_dir / filename\n shutil.copy(filepath, new_path)",
"def create_experiment(\n self,\n name: str,\n description: str = None,\n namespace: str = None) -> kfp_server_api.V1Experiment:\n namespace = namespace or self.get_user_namespace()\n experiment = None\n try:\n experiment = self.get_experiment(\n experiment_name=name, namespace=namespace)\n except ValueError as error:\n # Ignore error if the experiment does not exist.\n if not str(error).startswith('No experiment is found with name'):\n raise error\n\n if not experiment:\n logging.info('Creating experiment {}.'.format(name))\n\n resource_references = []\n if namespace:\n key = kfp_server_api.models.V1ResourceKey(\n id=namespace,\n type=kfp_server_api.models.V1ResourceType.NAMESPACE)\n reference = kfp_server_api.models.V1ResourceReference(\n key=key,\n relationship=kfp_server_api.models.V1Relationship.OWNER)\n resource_references.append(reference)\n\n experiment = kfp_server_api.models.V1Experiment(\n name=name,\n description=description,\n resource_references=resource_references)\n experiment = self._experiment_api.create_experiment(body=experiment)\n\n if self._is_ipython():\n import IPython\n html = \\\n ('<a href=\"%s/#/experiments/details/%s\" target=\"_blank\" >Experiment details</a>.'\n % (self._get_url_prefix(), experiment.id))\n IPython.display.display(IPython.display.HTML(html))\n return experiment",
"def _onNew(self, event):\n self.newExperiment()",
"def addSkill(self, newskill):\n self.skills.append( newskill )",
"def create_and_exercise(\n self,\n __template_id,\n __payload,\n __choice_name,\n __argument=None,\n *,\n workflow_id=None,\n command_id=None,\n read_as=None,\n act_as=None,\n ):\n raise NotImplementedError",
"async def skill(self, ctx, *, skill: str):\n\n try:\n skill = self.get_entry('Skill', skill.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = skill['Name']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://skill.png')\n embed.add_field(name='Learned', value=skill['Class/Rank'], inline=False)\n embed.add_field(name='Effect', value=skill['Effect'])\n\n await ctx.send(file=discord.File(f'xenox/skills/{name}.png', 'skill.png'), embed=embed)",
"def get_experiment_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, GetExperimentResponse_fcd92c35, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\", status_code=200, message=\"Returned skill experiment.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def addSkill(skill, db, **kwargs):\n skill_data = db.execute(\n 'SELECT * FROM mystatus WHERE skill = ?', (str(skill), )).fetchone()\n if skill_data:\n return colored(\"ERROR: Skill {S} is already in the skill set!\".format(S=str(skill)), \"red\", \"on_white\")\n db.execute(\n 'INSERT INTO mystatus (skill, power, points)'\n 'VALUES (?, ?, ?)', (str(skill), str(kwargs['power']), \"0\"))\n db.commit()\n return colored(\"Add new skill: \" + str(skill), 'cyan')",
"def test_skill_created(self):\n\t\tself.skill.save()\n\t\tskill_instance = Skill.objects.get(pk=1)\n\t\tself.assertEqual(\n\t\t\tskill_instance.user,\n\t\t\tself.skill.user,\n\t\t\t'User don\\'t match.'\n\t\t)\n\t\tself.assertEqual(\n\t\t\tskill_instance.tag,\n\t\t\tself.tag,\n\t\t\t'Skill tag\\'s don\\'t match.'\n\t\t)",
"def add_experiment(redis, name):\n\n if not ALLOWED_NAMES.match(name):\n raise ExperimentException(name, \"Illegal name\")\n if redis.exists(EXPERIMENT_REDIS_KEY_TEMPLATE % name):\n raise ExperimentException(name, \"Already exists\")\n\n json = dict(creation_date=util.unicode_type(datetime.datetime.now()))\n pipe = redis.pipeline(transaction=True)\n pipe.sadd(ACTIVE_EXPERIMENTS_REDIS_KEY, name)\n pipe.hset(EXPERIMENT_REDIS_KEY_TEMPLATE % name, \"metadata\", escape.json_encode(json))\n pipe.execute()\n return Experiment(redis, name)",
"def test_create_experiment_new_no_space(self):\n with OrionState() as cfg:\n name = \"oopsie_forgot_a_space\"\n with pytest.raises(NoConfigurationError) as exc:\n create_experiment(name=name, storage=cfg.storage_config)\n\n assert f\"Experiment {name} does not exist in DB\" in str(exc.value)",
"def create_new_trial(\n self, study_id: int, template_trial: Optional[\"FrozenTrial\"] = None\n ) -> int:\n raise NotImplementedError",
"def addSkill(self, skillName, maxLevel, creditStart, creditIncrement):\r\n self.skills[skillName] = SkillObject(skillName, maxLevel, creditStart, creditIncrement)\r\n self.orderedSkills.append(skillName)",
"def add_experiment(self, experiment, trial_runner):\n generator = generate_trials(experiment.spec, experiment.name)\n while True:\n try:\n trial_runner.add_trial(next(generator))\n except StopIteration:\n break",
"def create_skill(skillname, skillpath, category):\n if Skill.query.filter_by(path=skillpath).first():\n raise AttributeError\n new_skill = Skill(name=skillname, path=skillpath)\n if not category:\n new_skill.root = True\n db.session.add(new_skill)\n db.session.commit()\n database_controller.create_hierarchy(category, skillpath)",
"def delete_experiment_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def create_experiment(self):\n\n experiment = self._create_or_get_experiment()\n self._experiment = experiment\n self._one_platform_resource_manager = uploader_utils.OnePlatformResourceManager(\n self._experiment.name, self._api\n )\n\n self._request_sender = _BatchedRequestSender(\n self._experiment.name,\n self._api,\n allowed_plugins=self._allowed_plugins,\n upload_limits=self._upload_limits,\n rpc_rate_limiter=self._rpc_rate_limiter,\n tensor_rpc_rate_limiter=self._tensor_rpc_rate_limiter,\n blob_rpc_rate_limiter=self._blob_rpc_rate_limiter,\n blob_storage_bucket=self._blob_storage_bucket,\n blob_storage_folder=self._blob_storage_folder,\n one_platform_resource_manager=self._one_platform_resource_manager,\n tracker=self._tracker,\n )\n\n # Update partials with experiment name\n for sender in self._additional_senders.keys():\n self._additional_senders[sender] = self._additional_senders[sender](\n experiment_resource_name=self._experiment.name,\n )\n\n self._dispatcher = _Dispatcher(\n request_sender=self._request_sender,\n additional_senders=self._additional_senders,\n )",
"def create_sample(i):\n return Sample(**{\n 'name': f'Sample{i}',\n 'metadata': {'foobar': f'baz{i}'},\n KrakenResultModule.name(): create_kraken(),\n KrakenHLLResultModule.name(): create_krakenhll(),\n Metaphlan2ResultModule.name(): create_metaphlan2(),\n }).save()",
"def create_experience(cls, state, action, reward, done, next_state) -> 'Experience':\n return cls(\n state=state,\n action=action,\n reward=reward,\n done=done,\n next_state=next_state,\n )",
"def create_embedding(skills):\n corpus = list(skills[\"description\"].values)\n embedder = SentenceTransformer(config[\"sentence_transformer\"][\"model\"])\n embedding = embedder.encode(corpus, show_progress_bar=True)\n return embedding",
"def add_exercise(self):\r\n\r\n # Take the exercise entires from TOML file\r\n entries = self.cfg.get(\"payload\",{}).get(\"exercise\")\r\n # Check for valid entires\r\n if entries:\r\n # Construct payload \r\n for payload in entries:\r\n # Check the entry vs a json schema\r\n check.check_entry(path='schemas/exercise.json', test=payload)\r\n # Post request\r\n requests.post(API.url_exercise, data = payload, headers = self.headers, timeout = 2)",
"def create_mlflow_experiment(experiment_name: Text, mode: oct = 0o777) -> int:\n\n mlflow.set_experiment(experiment_name)\n experiment = mlflow.get_experiment_by_name(experiment_name)\n artifact_location = experiment.artifact_location.replace('file://', '')\n\n if not os.path.exists(artifact_location):\n os.mkdir(artifact_location)\n os.chmod(artifact_location, mode) # Change the access permissions\n\n return experiment.experiment_id",
"def createMakingTest(tx, query, personId, testId, date, hour, result):\n tx.run(query, personId=personId, testId=testId, date=date, hour=hour, result=result)"
] | [
"0.6853624",
"0.67841476",
"0.6585161",
"0.6519753",
"0.64360976",
"0.6318494",
"0.60392636",
"0.60172176",
"0.5932382",
"0.58842826",
"0.58458304",
"0.5842862",
"0.5791528",
"0.5756243",
"0.57560414",
"0.57440305",
"0.5707029",
"0.5682392",
"0.56699604",
"0.5654442",
"0.56010664",
"0.55724496",
"0.556916",
"0.5567575",
"0.55402803",
"0.55337435",
"0.55282146",
"0.54305625",
"0.54195136",
"0.54090005"
] | 0.7103403 | 0 |
This is a synchronous API that invokes the Lambda or third party HTTPS endpoint for a given skill. A successful response will contain information related to what endpoint was called, payload sent to and received from the endpoint. In cases where requests to this API results in an error, the response will contain an error code and a description of the problem. In cases where invoking the skill endpoint specifically fails, the response will contain a status attribute indicating that a failure occurred and details about what was sent to the endpoint. The skill must belong to and be enabled by the user of this API. Also, note that calls to the skill endpoint will timeout after 10 seconds. | def invoke_skill_v1(self, skill_id, invoke_skill_request, **kwargs):
# type: (str, InvokeSkillRequest_8cf8aff9, **Any) -> Union[ApiResponse, object, InvokeSkillResponse_6f32f451, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "invoke_skill_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'invoke_skill_request' is set
if ('invoke_skill_request' not in params) or (params['invoke_skill_request'] is None):
raise ValueError(
"Missing the required parameter `invoke_skill_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/invocations'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'invoke_skill_request' in params:
body_params = params['invoke_skill_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.invocations.invoke_skill_response.InvokeSkillResponse", status_code=200, message="Skill was invoked."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request due to invalid or missing data."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="API user does not have permission to call this API or is currently in a state that does not allow invocation of this skill. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The specified skill does not exist."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="API user has exceeded the permitted request rate."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.invocations.invoke_skill_response.InvokeSkillResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def skill_information():\r\n\r\n client = boto3.client('iot-data', region_name='us-west-2')\r\n\r\n session_attributes = {}\r\n card_title = \"Welcome\"\r\n should_end_session = True\r\n reprompt_text = None\r\n\r\n if(is_online()):\r\n speech_output = \"The coffee machine is offline.\"\r\n else:\r\n client.publish(topic=TOPIC_TURN_ON_OFF, qos=1, payload=json.dumps({\"state\": \"1\"}))\r\n speech_output = \"The coffee machine is on\"\r\n save_on_off_status(1)\r\n\r\n return build_response(session_attributes,\r\n build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))",
"def invoke_skill_end_point_v2(self, skill_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, BadRequestError_765e0ac6, InvocationsApiResponse_3d7e3234, Error_ea6c1a5a]\n operation_name = \"invoke_skill_end_point_v2\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v2/skills/{skillId}/stages/{stage}/invocations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'invocations_api_request' in params:\n body_params = params['invocations_api_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.skill.invocations.invocations_api_response.InvocationsApiResponse\", status_code=200, message=\"Skill was invoked.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request due to invalid or missing data.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission to call this API or is currently in a state that does not allow invocation of this skill. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=404, message=\"The specified skill does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=429, message=\"API user has exceeded the permitted request rate.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=500, message=\"Internal service error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v2.skill.invocations.invocations_api_response.InvocationsApiResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def simulate_skill_v1(self, skill_id, simulations_api_request, **kwargs):\n # type: (str, SimulationsApiRequest_606eed02, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, SimulationsApiResponse_328955bc]\n operation_name = \"simulate_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'simulations_api_request' is set\n if ('simulations_api_request' not in params) or (params['simulations_api_request'] is None):\n raise ValueError(\n \"Missing the required parameter `simulations_api_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/simulations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'simulations_api_request' in params:\n body_params = params['simulations_api_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.simulations.simulations_api_response.SimulationsApiResponse\", status_code=200, message=\"Skill simulation has successfully began.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request due to invalid or missing data.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission to call this API or is currently in a state that does not allow simulation of this skill. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The specified skill does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"This requests conflicts with another one currently being processed. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"API user has exceeded the permitted request rate.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal service error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.simulations.simulations_api_response.SimulationsApiResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def lambda_handler(event, context):\n logger.info(\"event.session.application.applicationId=\" +\n event['session']['application']['applicationId'])\n\n \"\"\"Check that this is being called by our skill\"\"\"\n logger.info(\"Calling app: \"+str(event['session']['application']['applicationId']))\n if (event['session']['application']['applicationId'] !=\n \"amzn1.ask.skill.\"+skill_id):\n logger.error(\"Invalid application ID\")\n raise ValueError(\"Invalid Application ID\")\n\n if event['session']['new']:\n on_session_started(event, {'requestId': event['request']['requestId']},\n event['session'])\n\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event, event['request'], event['session'])\n elif event['request']['type'] == \"IntentRequest\":\n return on_intent(event, event['request'], event['session'])\n elif event['request']['type'] == \"SessionEndedRequest\":\n return on_session_ended(event, event['request'], event['session'])\n\n # Otherwise deal with it gracefully\n logger.info(\"Unexpected request type:\")\n logger.info(json.dumps(event))\n return build_response({}, build_speechlet_response(\"Leeds Bins\", \"Welcome to Leeds Bins. Now you can find out which waste bins to take out when. Try asking: what's my next collection.\", None, False))",
"def skills():\n with app.app_context():\n results = Skill.query.all()\n return SkillsResponse(skills=results).json(), 200",
"def delete_skill_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def handler(event, context):\n\n \"\"\"\n Uncomment this if statement and populate with your skill's application ID to\n prevent someone else from configuring a skill that sends requests to this\n function.\n \"\"\"\n\n # if (event['session']['application']['applicationId'] !=\n # \"amzn1.echo-sdk-ams.app.[unique-value-here]\"):\n # raise ValueError(\"Invalid Application ID\")\n\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == \"IntentRequest\":\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == \"SessionEndedRequest\":\n return on_session_ended(event['request'], event['session'])",
"def submit_skill_for_certification_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"submit_skill_for_certification_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/submit'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'submit_skill_for_certification_request' in params:\n body_params = params['submit_skill_for_certification_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Success. There is no content but returns Location in the header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def simulate_skill_v2(self, skill_id, stage, simulations_api_request, **kwargs):\n # type: (str, str, SimulationsApiRequest_ae2e6503, **Any) -> Union[ApiResponse, object, SimulationsApiResponse_e4ad17d, BadRequestError_765e0ac6, Error_ea6c1a5a]\n operation_name = \"simulate_skill_v2\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'simulations_api_request' is set\n if ('simulations_api_request' not in params) or (params['simulations_api_request'] is None):\n raise ValueError(\n \"Missing the required parameter `simulations_api_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v2/skills/{skillId}/stages/{stage}/simulations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'simulations_api_request' in params:\n body_params = params['simulations_api_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.skill.simulations.simulations_api_response.SimulationsApiResponse\", status_code=200, message=\"Skill simulation has successfully began.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request due to invalid or missing data.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission to call this API or is currently in a state that does not allow simulation of this skill. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=404, message=\"The specified skill does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=409, message=\"This requests conflicts with another one currently being processed. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=429, message=\"API user has exceeded the permitted request rate.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=500, message=\"Internal service error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v2.skill.simulations.simulations_api_response.SimulationsApiResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def on_intent(intent_request, session):\n\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n\n # Dispatch to your skill's intent handlers\n if intent_name == \"<YOUR INTENT NAME HERE>\":\n # Update the wordsmith_data variable with your data. Use key, value\n # pairs where the key is the column name in Wordsmith and the value is\n # the value contained in that column\n wordsmith_data = { 'column1': 'value1', 'column2': 'value2' }\n narrative = wordsmith.generate(WORDSMITH_API_KEY, WORDSMITH_PROJECT_SLUG, WORDSMITH_TEMPLATE_SLUG, wordsmith_data)\n if 'errors' not in narrative:\n return build_response(session.get('attributes', {}), build_speechlet_response('Wordsmith Generated Response', narrative['data']['content'],\n '<REPROMPT TEXT HERE>', True))\n else:\n if not isinstance(narrative['errors'], list) :\n return build_response(session.get('attributes', {}), build_speechlet_response('Wordsmith Generation Error', 'Wordsmith reported the following error: {}'.format(narrative['errors']['detail']),\n '<REPROMPT TEXT HERE>', True))\n else:\n details = ', '.join([e['details'] for e in narrative['errors']])\n return build_response(session.get('attributes', {}), build_speechlet_response('Wordsmith Generation Error', 'Wordsmith reported the following error: {}'.format(details),\n '<REPROMPT TEXT HERE>', True))\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_welcome_response()\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return handle_session_end_request()\n else:\n raise ValueError(\"Invalid intent\")",
"async def skill(self, ctx, *, skill: str):\n\n try:\n skill = self.get_entry('Skill', skill.lower())\n except RuntimeError as e:\n return await ctx.send(e)\n\n name = skill['Name']\n\n embed = discord.Embed(title=name)\n embed.set_thumbnail(url='attachment://skill.png')\n embed.add_field(name='Learned', value=skill['Class/Rank'], inline=False)\n embed.add_field(name='Effect', value=skill['Effect'])\n\n await ctx.send(file=discord.File(f'xenox/skills/{name}.png', 'skill.png'), embed=embed)",
"def get_skill_status_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, SkillStatus_4fdd647b, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_skill_status_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/status'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'resource' in params:\n query_params.append(('resource', params['resource']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.skill_status.SkillStatus\", status_code=200, message=\"Returns status for skill resource and sub-resources.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.skill_status.SkillStatus\")\n\n if full_response:\n return api_response\n return api_response.body",
"def default_answer(intent_request):\n\n #product_type = get_slots(intent_request)[\"ProductStyle\"]\n #itemid = get_slots(intent_request)[\"ItemId\"]\n #itemid='5391020'\n\n return close(intent_request['sessionAttributes'],\n 'Fulfilled',\n {'contentType': 'PlainText',\n 'content': 'Sample Response from default answer Lambda function'})",
"def test_dispatch_intent(self):\n @self.skill.intent('test_intent')\n def sample_func():\n \"\"\"Decorated function.\"\"\"\n self.skill.response.sessionAttributes['run'] = True\n self.skill.request.request.type = 'IntentRequest'\n self.skill.request.request.intent = interface.Intent()\n self.skill.request.request.intent.name = 'test_intent'\n self.skill.dispatch()\n self.assertTrue(self.skill.response.sessionAttributes['run'])",
"def lambda_handler(event, context):\r\n if 'session' in event:\r\n print(\"event.session.application.applicationId=\" +\r\n event['session']['application']['applicationId'])\r\n\r\n \"\"\"\r\n Uncomment this if statement and populate with your skill's application ID to\r\n prevent someone else from configuring a skill that sends requests to this\r\n function.\r\n \"\"\"\r\n if ('session' in event and (event['session']['application']['applicationId'] !=\r\n \"amzn1.ask.skill.57119d91-fb3c-487f-be53-4e7fac12fb83\")):\r\n raise ValueError(\"Invalid Application ID\")\r\n\r\n \"\"\"if event['session']['new']:\r\n on_session_started({'requestId': event['request']['requestId']},\r\n event['session'])\"\"\"\r\n\r\n if event['request']['type'] == \"LaunchRequest\":\r\n return on_launch(event['request'], event['session'])\r\n elif event['request']['type'] == \"IntentRequest\":\r\n return on_intent(event['request'], event['session'])\r\n elif event['request']['type'] == \"SessionEndedRequest\":\r\n return on_session_ended(event['request'], event['session'])\r\n elif event['request']['type'] == 'UPDATE':\r\n return saveCoffeeMachineStatus(event['request'])\r\n elif event['request']['type'] == \"GLASS\":\r\n return glassStatus(event['request'])\r\n elif event['request']['type'] == \"WATER\":\r\n return waterStatus(event['request'])\r\n elif event['request']['type'] == \"COFFEE\":\r\n return coffeeStatus(event['request'])\r\n elif event['request']['type'] == \"ON_OFF\":\r\n return on_off_status(event['request'])\r\n elif event['request']['type'] == \"ONLINE\":\r\n return online_status_f(event['request'])\r\n elif event['request']['type'] == 'BUSY':\r\n return busyStatus(event['request'])",
"def test_get_response(self):\n skill = create_skill()\n skill._wait_response = mock.Mock()\n skill.speak_dialog = mock.Mock()\n\n expected_response = 'ice creamr please'\n skill._wait_response.return_value = expected_response\n response = skill.get_response('what do you want')\n self.assertEqual(response, expected_response)\n self.assertTrue(skill.speak_dialog.called)",
"def lambda_handler(event, context):\n print(\"Incoming request...\")\n\n \"\"\"\n Uncomment this if statement and populate with your skill's application ID to\n prevent someone else from configuring a skill that sends requests to this\n function.\n \"\"\"\n if (event['session']['application']['applicationId'] !=\n \"amzn1.ask.skill.2994421a-75ef-4502-9d4a-bf83f20a7ade\"):\n raise ValueError(\"Invalid Application ID\")\n\n if event['session']['new']:\n on_session_started({'requestId': event['request']['requestId']},\n event['session'])\n\n if event['request']['type'] == \"LaunchRequest\":\n return on_launch(event['request'], event['session'])\n elif event['request']['type'] == \"IntentRequest\":\n return on_intent(event['request'], event['session'])\n elif event['request']['type'] == \"SessionEndedRequest\":\n return on_session_ended(event['request'], event['session'])",
"def skill(self):\n return self._get(\"skill\")",
"def _call(self, method: str, endpoint: str, **kwargs: Any) -> requests.Response:\n url = self._http_url + endpoint\n logging.info(f'Request – {method.upper()} {url} {kwargs if kwargs else \"\"}')\n resp = self._session.request(method, self._http_url + endpoint, **kwargs)\n logging.info(\n f'Response – <{resp.status_code} {resp.reason}> {resp.text} ({resp.elapsed.microseconds / 10 ** 6} sec)'\n )\n return resp",
"def on_intent(intent_request, session):\n\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n\n print(\"---INTENT: \" + intent_name)\n\n # Dispatch to your skill's intent handlers\n try:\n if intent_name == \"GetSynonymIntent\":\n return get_synonym(intent, session)\n elif intent_name == \"GetRandomSynonymIntent\":\n return get_random_synonym(intent, session)\n elif intent_name == \"GetAllSynonymsIntent\":\n return get_all_synonyms(intent, session)\n elif intent_name == \"GetAntonymIntent\":\n return get_antonym(intent, session)\n elif intent_name == \"GetRandomAntonymIntent\":\n return get_random_antonym(intent, session)\n elif intent_name == \"GetAllAntonymsIntent\":\n return get_all_antonyms(intent, session)\n elif intent_name == \"GetPOSIntent\":\n return get_pos(intent, session)\n elif intent_name == \"GetRhymeIntent\":\n return get_rhyme(intent, session)\n elif intent_name == \"GetRandomRhymeIntent\":\n return get_random_rhyme(intent, session)\n elif intent_name == \"GetDefinitionIntent\":\n return get_definition(intent, session)\n elif intent_name == \"GetRandomDefinitionIntent\":\n return get_random_definition(intent, session)\n elif intent_name == \"GetAllDefinitionsIntent\":\n return get_all_definitions(intent, session)\n elif intent_name == \"GetSyllablesIntent\":\n return get_syllables(intent, session)\n elif intent_name == \"GetFrequencyIntent\":\n return get_frequency(intent, session)\n elif intent_name == \"GetPronunciationIntent\":\n return get_pronunciation(intent, session)\n elif intent_name == \"GetAllCommandsIntent\":\n return get_all_commands()\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_welcome_response()\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return handle_session_end_request()\n else:\n response = build_speechlet_response(\"Error\", \"Sorry, I don't know that command. I can find definitions, synonyms, antonyms, and more if you say something like 'a synonym for happy'.\", None, True)\n return build_response({}, response)\n\n except:\n response = build_speechlet_response(\"Error\", \"Sorry, I don't know that word!\", None, True)\n return build_response({}, response)",
"def lambda_handler(event, context):\n print(\"event.session.application.applicationId=\" +\n event['session']['application']['applicationId'])\n\n \"\"\"\n Uncomment this if statement and populate with your skill's application ID to\n prevent someone else from configuring a skill that sends requests to this\n function.\n \"\"\"\n #if (event['session']['application']['applicationId'] != \"<APPLICATION_ID>\"):\n # raise ValueError(\"Invalid Application ID\")\n\n\n if event['request']['type'] == \"IntentRequest\":\n return on_intent(event['request'], event['session'])",
"def lambda_handler(event, context):\n\n # S3 resource invocation\n s3_resource = boto3.resource('s3')\n # S3 bucket selection\n data_bucket_name = \"put_here_data_bucket_name\"\n # The SageMaker runtime is what allows us to invoke the endpoint that we've created.\n runtime = boto3.Session().client('sagemaker-runtime')\n\n request_body_dict = json.loads(event['body'])\n\n # Now we use the SageMaker runtime to invoke our endpoint, sending both ticker and start date if given\n if request_body_dict['start_date'] != \"\":\n response = runtime.invoke_endpoint(EndpointName='DeepAR-ml-spp', # The name of the endpoint we created\n ContentType='application/json', # The data format that is expected\n Body=encode_future_request(request_body=request_body_dict,\n s3_resource=s3_resource,\n s3_bucket=data_bucket_name, prefix='valid'))\n # or only ticker name if no start date has been provided\n elif request_body_dict['ticker_name'] != \"\":\n response = runtime.invoke_endpoint(EndpointName='DeepAR-ml-spp', # The name of the endpoint we created\n ContentType='application/json', # The data format that is expected\n Body=encode_request(ticker_name=request_body_dict['ticker_name'],\n s3_resource=s3_resource, s3_bucket=data_bucket_name,\n prefix='train'))\n\n # The response is an HTTP response whose body contains the result of our inference\n result = response['Body'].read().decode('utf-8')\n\n # print data for debug purposes\n print(result)\n\n return {\n 'statusCode': 200,\n 'headers': {'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*'},\n 'body': str(result)\n }",
"def lambda_handler(event, context):\n return {\n 'statusCode': 200,\n 'body': say_hello()\n }",
"def test_ask_yesno_yes(self):\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'yes'\n\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'yes')",
"def start_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"start_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/start'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def associate_isp_with_skill_v1(self, product_id, skill_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"associate_isp_with_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'product_id' is set\n if ('product_id' not in params) or (params['product_id'] is None):\n raise ValueError(\n \"Missing the required parameter `product_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/inSkillProducts/{productId}/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'product_id' in params:\n path_params['productId'] = params['product_id']\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request. Returned when a required parameter is not present, badly formatted. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"Request is forbidden.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"Requested resource not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Too many requests received.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def on_intent(intent_request, session):\n\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n intent_name = \"\"\n if 'intent' in intent_request:\n intent = intent_request['intent']\n if 'name' in intent:\n intent_name = intent['name']\n\n # Dispatch to your skill's intent handlers\n if not intent_name:\n return get_help_response()\n elif intent_name == \"Hello\":\n return say_hello()\n elif intent_name == \"Brandon\":\n return say_brandon()\n elif intent_name == \"Warning\":\n return say_warning()\n elif intent_name == \"Dance\":\n return say_dance_lights()\n elif intent_name == \"Spot\":\n return say_spot_light()\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_help_response()\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return handle_session_end_request()\n else:\n return say_hello()\n return get_help_response()",
"def on_intent(intent_request, session):\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n # intents_object = get_custom_intents()\n print (\"************\")\n print (intent_request)\n # fall_back = True\n # final_function = ''\n # for temp_intent in intents_object:\n # if temp_intent == intent_name:\n # fall_back = False\n # final_function = temp_intent[1]\n # break\n # if(fall_back):\n # return custom_handlers.get_fallback_msg()\n # else:\n # return final_function(intent, session)\n \n # Dispatch to your skill's intent handlers\n if intent_name == \"welcome_intent\":\n return custom_handlers.get_welcome_msg(intent, session)\n elif intent_name == \"search_intent\":\n return custom_handlers.get_search_msg(intent, session)\n elif intent_name == \"architecture\":\n return custom_handlers.get_architecture_msg(intent, session)\n elif intent_name == \"saybye\":\n return custom_handlers.get_saybye_response(intent, session)\n elif intent_name == \"myname\":\n return custom_handlers.get_myname_response(intent, session)\n elif intent_name == \"ask\":\n return custom_handlers.get_ask_response(intent, session)\n elif intent_name == \"AMAZON.HelpIntent\":\n return custom_handlers.get_welcome_response(intent, session)\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return custom_handlers.handle_session_end_request(intent, session)\n else:\n return custom_handlers.get_fallback_msg(intent, session)",
"def on_intent(intent_request, session):\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n\n # Dispatch to your skill's intent handlers\n\n if intent_name not in skillmap:\n intent_name = \"NullSkill\"\n\n if intent_name in skillmap:\n try:\n return skillmap[intent_name].execute(intent, session)\n except Exception as e:\n traceback.print_exc()\n return SkillBase().respond(\"Sorry I missed that\", \"Error\", str(e))\n else:\n raise ValueError(\"Invalid intent\")",
"def test_ask_yesno_no(self):\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'nope'\n\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'no')"
] | [
"0.5912909",
"0.5896748",
"0.57591367",
"0.57437086",
"0.57308966",
"0.5649424",
"0.56391555",
"0.5612456",
"0.55630434",
"0.55491686",
"0.54284877",
"0.5363396",
"0.53060114",
"0.5269332",
"0.5248049",
"0.5243671",
"0.52119356",
"0.5210129",
"0.5205348",
"0.5204494",
"0.51950014",
"0.51945627",
"0.5187752",
"0.5182164",
"0.51790226",
"0.5176293",
"0.5172411",
"0.5170453",
"0.51481503",
"0.5142392"
] | 0.6131731 | 0 |
Get the properties of an NLU annotation set Return the properties for an NLU annotation set. | def get_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUAnnotationSetPropertiesResponse_731f20d3, BadRequestError_f854b05]
operation_name = "get_properties_for_nlu_annotation_sets_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'annotation_id' is set
if ('annotation_id' not in params) or (params['annotation_id'] is None):
raise ValueError(
"Missing the required parameter `annotation_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'annotation_id' in params:
path_params['annotationId'] = params['annotation_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse", status_code=200, message="The NLU annotation set exists."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_properties():",
"def getProperties():",
"def getPropertiesAll():",
"def get_properties(self):\n return self.properties",
"def get_properties(self):\n return self.properties",
"def annotations(self) -> Mapping[str, str]:\n return pulumi.get(self, \"annotations\")",
"def annotations(self) -> Mapping[str, str]:\n return pulumi.get(self, \"annotations\")",
"def properties(self):\n return self.properties_with_uid[1:]",
"def update_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, update_nlu_annotation_set_properties_request, **kwargs):\n # type: (str, str, UpdateNLUAnnotationSetPropertiesRequest_b569f485, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_nlu_annotation_set_properties_request' is set\n if ('update_nlu_annotation_set_properties_request' not in params) or (params['update_nlu_annotation_set_properties_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_nlu_annotation_set_properties_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'update_nlu_annotation_set_properties_request' in params:\n body_params = params['update_nlu_annotation_set_properties_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"NLU annotation set exists and properties are updated successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def properties_get(self):\n return self._get('properties')",
"def annotations(self):\n return self._annotations",
"def getProperties(self):\n return self.properties",
"def annotations(self) -> pulumi.Output[Mapping[str, Any]]:\n return pulumi.get(self, \"annotations\")",
"def _get_properties(config: argparse.Namespace) -> tuple[set[str], set[str]]:\n property_classes = {BUILTIN_PROPERTY}\n property_names: set[str] = set() # Not returning 'property', it has its own check.\n if config is not None:\n property_classes.update(config.property_classes)\n property_names.update(\n prop.rsplit(\".\", 1)[-1] for prop in config.property_classes\n )\n return property_classes, property_names",
"def properties(self) -> Any:\n return pulumi.get(self, \"properties\")",
"def properties(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"properties\")",
"def properties(self) -> Optional[Mapping[str, str]]:\n return pulumi.get(self, \"properties\")",
"def annotations(self):\n\n return self._annotations",
"def detected_properties(self) -> pulumi.Output[Mapping[str, str]]:\n return pulumi.get(self, \"detected_properties\")",
"def getProperties(self, owner: unicode) -> List[ghidra.program.model.util.PropertyMap]:\n ...",
"def get_annotations(self):\n entity = self.get_object()\n serializer = AnnotationValueSerializer(entity.annotations.all(), many=True)\n return Response(serializer.data)",
"def __properties__(self) -> dict:\r\n parameters = [\r\n d for d in dir(self) if (d[0] != \"_\") and (d.count(\"set\") == 0)\r\n and (d.count(\"_c\") == 0) and (d.count(\"_f\") == 0)\r\n ]\r\n\r\n return self.__as_json__(parameters)",
"def getProperties(self):\n return _libsbml.SBMLConverter_getProperties(self)",
"def properties(self):\n return self._properties",
"def properties(self):\n return self._properties",
"def getProperties(targets):",
"def readProperties(self):\r\n print('not yet implemented')",
"def properties(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:\n return pulumi.get(self, \"properties\")",
"def properties(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:\n return pulumi.get(self, \"properties\")",
"def get_annotations(graph):\n return set(_annotation_iter_helper(graph))"
] | [
"0.61178017",
"0.58980346",
"0.5858715",
"0.5701817",
"0.5688754",
"0.56876403",
"0.56876403",
"0.5672441",
"0.56317395",
"0.5604513",
"0.5543352",
"0.5476837",
"0.5442199",
"0.54398817",
"0.54222673",
"0.53711796",
"0.53711796",
"0.5347019",
"0.52881587",
"0.52827",
"0.5241049",
"0.5237365",
"0.5225832",
"0.5180164",
"0.5180164",
"0.5143102",
"0.51254004",
"0.5122027",
"0.5122027",
"0.5115383"
] | 0.65365875 | 0 |
update the NLU annotation set properties. API which updates the NLU annotation set properties. Currently, the only data can be updated is annotation set name. | def update_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, update_nlu_annotation_set_properties_request, **kwargs):
# type: (str, str, UpdateNLUAnnotationSetPropertiesRequest_b569f485, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]
operation_name = "update_properties_for_nlu_annotation_sets_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'annotation_id' is set
if ('annotation_id' not in params) or (params['annotation_id'] is None):
raise ValueError(
"Missing the required parameter `annotation_id` when calling `" + operation_name + "`")
# verify the required parameter 'update_nlu_annotation_set_properties_request' is set
if ('update_nlu_annotation_set_properties_request' not in params) or (params['update_nlu_annotation_set_properties_request'] is None):
raise ValueError(
"Missing the required parameter `update_nlu_annotation_set_properties_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'annotation_id' in params:
path_params['annotationId'] = params['annotation_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'update_nlu_annotation_set_properties_request' in params:
body_params = params['update_nlu_annotation_set_properties_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message="NLU annotation set exists and properties are updated successfully."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="PUT",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_annotations_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, content_type, update_nlu_annotation_set_annotations_request, **kwargs):\n # type: (str, str, str, UpdateNLUAnnotationSetAnnotationsRequest_b336fe43, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_annotations_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'content_type' is set\n if ('content_type' not in params) or (params['content_type'] is None):\n raise ValueError(\n \"Missing the required parameter `content_type` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_nlu_annotation_set_annotations_request' is set\n if ('update_nlu_annotation_set_annotations_request' not in params) or (params['update_nlu_annotation_set_annotations_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_nlu_annotation_set_annotations_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/annotations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n if 'content_type' in params:\n header_params.append(('Content-Type', params['content_type']))\n\n body_params = None\n if 'update_nlu_annotation_set_annotations_request' in params:\n body_params = params['update_nlu_annotation_set_annotations_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=200, message=\"NLU annotation set exists and starts the update.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUAnnotationSetPropertiesResponse_731f20d3, BadRequestError_f854b05]\n operation_name = \"get_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse\", status_code=200, message=\"The NLU annotation set exists.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def delete_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"delete_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"NLU annotation set exists and is deleted successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def _update_parameter_set_names(self):\n self._create_parameter_set_names()\n new_set_names = set(self._parameter_set_names.values()) - set(self.parameter_study.coords[_set_coordinate_key].values)\n null_set_names = self.parameter_study.coords[_set_coordinate_key].isnull()\n if any(null_set_names):\n self.parameter_study.coords[_set_coordinate_key][null_set_names] = list(new_set_names)\n self._parameter_set_names = self.parameter_study[_set_coordinate_key].squeeze().to_series().to_dict()",
"def update_annot(ind):\n # update text annotation\n pos = sc.get_offsets()[ind[\"ind\"][0]]\n annot.xy = pos\n idxlist = []\n for element in PC:\n idxlist.append(np.allclose(element, pos))\n idx = idxlist.index(True)\n annotation_string = f'{idx + 1}\\n'\n if display_parameter_values:\n for i, label in enumerate(parameterList):\n annotation_string += (f'{parameters[i, idx]: 10.2f} '\n f'+/- {errors[i, idx]:8.2f} '\n f'({label})\\n')\n annot.set_text(annotation_string[:-1])\n annot.get_bbox_patch().set_alpha(0.4)\n\n # update immage annotation\n label = mapp.listOfFiles[idx].split(os.sep)[-1].split('.')[0]\n image = get_image(mapp.pltdir, label)\n ab.xy = pos\n ab.offsetbox = OffsetImage(image)\n ax.add_artist(ab)\n if show_both_images:\n additional_image = get_image(additional_fitplot_folder, label)\n ac.xy = pos + shift_second_image\n ac.offsetbox = OffsetImage(additional_image)\n ax.add_artist(ac)",
"def updateAnnotations(self):\n self.backupDatafiles()\n print(\"Updating annotation files \", self.field(\"trainDir\"))\n listOfDataFiles = QDir(self.field(\"trainDir\")).entryList(['*.data'])\n for file in listOfDataFiles:\n # Read the annotation\n segments = Segment.SegmentList()\n newsegments = Segment.SegmentList()\n segments.parseJSON(os.path.join(self.field(\"trainDir\"), file))\n allSpSegs = np.arange(len(segments)).tolist()\n newsegments.metadata = segments.metadata\n for segix in allSpSegs:\n seg = segments[segix]\n if self.field(\"species\") not in [fil[\"species\"] for fil in seg[4]]:\n newsegments.addSegment(seg) # leave non-target segments unchanged\n else:\n for seg2 in self.segments:\n if seg2[1] == seg:\n # find the index of target sp and update call type\n seg[4][[fil[\"species\"] for fil in seg[4]].index(self.field(\"species\"))][\"calltype\"] = self.clusters[seg2[-1]]\n newsegments.addSegment(seg)\n newsegments.saveJSON(os.path.join(self.field(\"trainDir\"), file))",
"def setAnnotation(self, *args):\n return _libsbml.SBase_setAnnotation(self, *args)",
"def setAnnotation(self, *args):\n return _libsbml.Model_setAnnotation(self, *args)",
"def annotations(self, annotations):\n self._annotations = annotations",
"def set(self, property_dict):\r\n self.metadata = self.db.update(self.path, property_dict).json()",
"def _set_property(self, name, prop_name, prop_value, ignore_items=False):\n prop_update = {prop_name: prop_value}\n for n in name:\n collection = 'masks' if self.is_array(n) else 'columns'\n if not 'properties' in self._meta[collection][n]:\n self._meta[collection][n]['properties'] = {}\n self._meta[collection][n]['properties'].update(prop_update)\n if ignore_items: continue\n for s in self.sources(n):\n self._set_property(s, prop_name, prop_value)\n return None",
"def _update_from_feature_set(self, feature_set):\n\n self.name = feature_set.name\n self.project = feature_set.project\n self.source = feature_set.source\n self.max_age = feature_set.max_age\n self.features = feature_set.features\n self.entities = feature_set.entities\n self.source = feature_set.source\n self.status = feature_set.status\n self.created_timestamp = feature_set.created_timestamp",
"def updateResonanceSetAnnotation(resonanceSet):\n \n for resonance in resonanceSet.resonances:\n if not resonance.isDeleted: \n getBoundResonances(resonance, recalculate=True, contribs=None)\n updateResonanceAnnotation(resonance)",
"def set(self, properties):\n raise NotImplementedError",
"def create_nlu_annotation_set_v1(self, skill_id, create_nlu_annotation_set_request, **kwargs):\n # type: (str, CreateNLUAnnotationSetRequest_16b1430c, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, CreateNLUAnnotationSetResponse_b069cada]\n operation_name = \"create_nlu_annotation_set_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'create_nlu_annotation_set_request' is set\n if ('create_nlu_annotation_set_request' not in params) or (params['create_nlu_annotation_set_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_nlu_annotation_set_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_nlu_annotation_set_request' in params:\n body_params = params['create_nlu_annotation_set_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.create_nlu_annotation_set_response.CreateNLUAnnotationSetResponse\", status_code=201, message=\"NLU annotation set created successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.create_nlu_annotation_set_response.CreateNLUAnnotationSetResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def updateData(self, *args):\n # if self.move_next_option == \"R\":\n # self.restSampling()\n # elif self.move_next_option == \"A\":\n # self.addExtra()\n # else:\n # self.continueReview()\n for name, value in self.parameter_inputs.items():\n self.parameters[name] = value.value\n # directly change the value of class variables\n logMsg((\"update settings: \", self.ml_classifier_cls, name, value.value))\n setattr(self.ml_classifier_cls, name, value.value)\n\n pass",
"def update_set(self):\n for field in self.children:\n if issubclass(field.__class__, MyTextField):\n val = field.get_field().value\n setattr(self.set, field.get_field().name, val if val != \"\" else None)",
"def update_property(self, property_info):\n SchemaValidator(self.schema_extension_only, self.full_schema_graph).validate_property_schema(property_info)\n self.schema[\"@graph\"].append(property_info)\n self.load_schema(self.schema)\n print(\"Updated the property {} successfully!\".format(property_info[\"rdfs:label\"]))",
"def fusion_api_edit_uplink_set(self, body, uri, api=None, headers=None):\n return self.uplink_set.update(body, uri, api, headers)",
"def annotate(self, **annotations):\n _check_annotations(annotations)\n self.annotations.update(annotations)",
"def SetAnnotation(self, r, name, value):\n self.__context.builder.DocumentAnnotationSet(self._blip_data.wave_id,\n self._blip_data.wavelet_id,\n self._blip_data.blip_id,\n r.start, r.end,\n name, value)\n self._blip_data.annotations.append(document.Annotation(name, value, r))",
"def DocumentAnnotationSet(self, wave_id, wavelet_id, blip_id, start, end,\n name, value):\n annotation = document.Annotation(name, value, document.Range(start, end))\n op = Operation(DOCUMENT_ANNOTATION_SET, wave_id, wavelet_id,\n blip_id=blip_id,\n prop=annotation)\n self.__context.AddOperation(op)",
"def updateAnnoByIdDictFromMeta(syn,idDict,metaDf,refCol,fileExts):\n for key in idDict:\n print \"updating annotaion values for key: %s\" % key\n for synId in idDict[key]:\n print \"> %s\" %synId\n temp = syn.get(synId, downloadFile = False)\n exts = ')|('.join(fileExts)\n exts = r'(' + exts + ')'\n tempName = re.sub(exts,\"\",temp.name)\n row = df.loc[df[refCol] == tempName]\n temp[key] = map(str,row[key])[0]\n temp = syn.store(temp,forceVersion = False)\n print \"\"",
"def adjust_properties (self, prop_set):\n assert isinstance(prop_set, property_set.PropertySet)\n s = self.targets () [0].creating_subvariant ()\n\n return prop_set.add_raw (s.implicit_includes ('include', 'H'))",
"def set_location(self, location_set):",
"def set_annotations(self, request, pk=None):\n # No need to check for permissions, since post requires edit by default.\n entity = self.get_object()\n # Read and validate the request data.\n serializer = AnnotationsSerializer(data=request.data, many=True)\n serializer.is_valid(raise_exception=True)\n annotations = [\n (entry[\"field\"], entry[\"value\"]) for entry in serializer.validated_data\n ]\n annotation_fields = [e[0] for e in annotations]\n # The following dict is a mapping from annotation field id to the annotation\n # value id.\n existing_annotations = dict(\n entity.annotations.filter(field__in=annotation_fields).values_list(\n \"field_id\", \"id\"\n )\n )\n\n validation_errors = []\n to_create = []\n to_update = []\n for field, value in annotations:\n annotation_id = existing_annotations.get(field.id)\n append_to = to_create if annotation_id is None else to_update\n annotation = AnnotationValue(\n entity_id=entity.id, field_id=field.id, value=value, id=annotation_id\n )\n try:\n annotation.validate()\n except DjangoValidationError as e:\n validation_errors += e\n append_to.append(annotation)\n\n if validation_errors:\n raise DjangoValidationError(validation_errors)\n\n with transaction.atomic():\n AnnotationValue.objects.bulk_create(to_create)\n AnnotationValue.objects.bulk_update(to_update, [\"_value\"])\n return Response()",
"def setAnnotation(self, *args):\n return _libsbml.SpeciesReference_setAnnotation(self, *args)",
"def updateAnnotations(self, annotator=None):\n plt = self.plt\n updated = False\n if annotator is None:\n for annotator in self.annotators.values():\n if annotator.update():\n updated = True\n elif annotator.update(): updated = True\n if updated:\n # This raises a warning with newer matplotlib\n #plt.pause(0.0001)\n plt.draw()",
"def reset_annotations(self):\n # FIXME: this state does not make sense\n self.annotation_date_set = False\n self.annotation_comment_set = False\n self.annotation_type_set = False\n self.annotation_spdx_id_set = False",
"def set(self, package='', name='', uid='', params={}):\n return self.__post('set-nat-section', package, name, uid, params)"
] | [
"0.570468",
"0.54506195",
"0.54102653",
"0.5356329",
"0.5263346",
"0.5201627",
"0.51824445",
"0.51057756",
"0.5028012",
"0.4990469",
"0.49601716",
"0.49266067",
"0.49085695",
"0.48879135",
"0.48741606",
"0.4791256",
"0.4790395",
"0.47720513",
"0.4767837",
"0.47672677",
"0.47668418",
"0.47601667",
"0.47327483",
"0.47280496",
"0.4701383",
"0.46981138",
"0.46920443",
"0.46883047",
"0.46846405",
"0.46702236"
] | 0.67326057 | 0 |
List NLU annotation sets for a given skill. API which requests all the NLU annotation sets for a skill. Returns the annotationId and properties for each NLU annotation set. Developers can filter the results using locale. Supports paging of results. | def list_nlu_annotation_sets_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListNLUAnnotationSetsResponse_5b1b0b6a, BadRequestError_f854b05]
operation_name = "list_nlu_annotation_sets_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/nluAnnotationSets'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'locale' in params:
query_params.append(('locale', params['locale']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.nlu.annotation_sets.list_nlu_annotation_sets_response.ListNLUAnnotationSetsResponse", status_code=200, message="NLU annotation sets are returned."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.nlu.annotation_sets.list_nlu_annotation_sets_response.ListNLUAnnotationSetsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_annotations_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, accept, **kwargs):\n # type: (str, str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"get_annotations_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'accept' is set\n if ('accept' not in params) or (params['accept'] is None):\n raise ValueError(\n \"Missing the required parameter `accept` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/annotations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n if 'accept' in params:\n header_params.append(('Accept', params['accept']))\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=200, message=\"The specific version of a NLU annotation set has the content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUAnnotationSetPropertiesResponse_731f20d3, BadRequestError_f854b05]\n operation_name = \"get_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse\", status_code=200, message=\"The NLU annotation set exists.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def delete_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"delete_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"NLU annotation set exists and is deleted successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def create_nlu_annotation_set_v1(self, skill_id, create_nlu_annotation_set_request, **kwargs):\n # type: (str, CreateNLUAnnotationSetRequest_16b1430c, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, CreateNLUAnnotationSetResponse_b069cada]\n operation_name = \"create_nlu_annotation_set_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'create_nlu_annotation_set_request' is set\n if ('create_nlu_annotation_set_request' not in params) or (params['create_nlu_annotation_set_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_nlu_annotation_set_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_nlu_annotation_set_request' in params:\n body_params = params['create_nlu_annotation_set_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.create_nlu_annotation_set_response.CreateNLUAnnotationSetResponse\", status_code=201, message=\"NLU annotation set created successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.create_nlu_annotation_set_response.CreateNLUAnnotationSetResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def update_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, update_nlu_annotation_set_properties_request, **kwargs):\n # type: (str, str, UpdateNLUAnnotationSetPropertiesRequest_b569f485, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_nlu_annotation_set_properties_request' is set\n if ('update_nlu_annotation_set_properties_request' not in params) or (params['update_nlu_annotation_set_properties_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_nlu_annotation_set_properties_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'update_nlu_annotation_set_properties_request' in params:\n body_params = params['update_nlu_annotation_set_properties_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"NLU annotation set exists and properties are updated successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def update_annotations_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, content_type, update_nlu_annotation_set_annotations_request, **kwargs):\n # type: (str, str, str, UpdateNLUAnnotationSetAnnotationsRequest_b336fe43, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_annotations_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'content_type' is set\n if ('content_type' not in params) or (params['content_type'] is None):\n raise ValueError(\n \"Missing the required parameter `content_type` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_nlu_annotation_set_annotations_request' is set\n if ('update_nlu_annotation_set_annotations_request' not in params) or (params['update_nlu_annotation_set_annotations_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_nlu_annotation_set_annotations_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/annotations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n if 'content_type' in params:\n header_params.append(('Content-Type', params['content_type']))\n\n body_params = None\n if 'update_nlu_annotation_set_annotations_request' in params:\n body_params = params['update_nlu_annotation_set_annotations_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=200, message=\"NLU annotation set exists and starts the update.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def get_all(nitro):\r\n __url = nitro.get_url() + NSPatset.get_resourcetype()\r\n __json_policypatsets = nitro.get(__url).get_response_field(NSPatset.get_resourcetype())\r\n __policypatsets = []\r\n for json_policypatset in __json_policypatsets:\r\n __policypatsets.append(NSPatset(json_policypatset))\r\n return __policypatsets",
"def fetch_skills(self):\r\n\r\n noun_chunks = self.doc.noun_chunks\r\n nlp_text = self.doc\r\n\r\n # removing stop words and implementing word tokenization\r\n tokens = [token.text for token in nlp_text if not token.is_stop]\r\n\r\n data = pd.read_csv(\"skills.csv\") # reading the csv file\r\n skills = list(data.columns.values) # extract values into a lis\r\n skillset = [] # store final skills here\r\n\r\n # check for one-grams (example: python)\r\n for token in tokens:\r\n if token.lower() in skills:\r\n skillset.append(token)\r\n\r\n # check for bi-grams and tri-grams (example: machine learning)\r\n for token in noun_chunks:\r\n token = token.text.lower().strip()\r\n if token in skills:\r\n skillset.append(token)\r\n\r\n return [i.capitalize() for i in set([i.lower() for i in skillset])]",
"def get_annotations(self):\n entity = self.get_object()\n serializer = AnnotationValueSerializer(entity.annotations.all(), many=True)\n return Response(serializer.data)",
"def listSets(*args, allSets: bool=True, extendToShape: bool=True, object: name=None, type:\n int=0, **kwargs)->List[AnyStr]:\n pass",
"def _annotations(request):\n result = Search(request).run(MultiDict(request.params))\n\n return request.find_service(AnnotationReadService).get_annotations_by_id(\n ids=result.annotation_ids\n )",
"def list_rulesets(command):\n namespace = app.main(command)\n assert namespace.command == 'lr' or namespace.command == \"listrulesets\"",
"def get_all(session: Session, tamr_project: Project) -> List[AttributeMapping]:\n url = str(tamr_project.url) + \"/attributeMappings\"\n r = session.get(url=url)\n\n data = response.successful(r).json()\n mapping_list = []\n attribute_memo: Dict[URL, Attribute] = {}\n for mapping_data in data:\n mapping, attribute_memo = _get(\n session,\n tamr_project.url.instance,\n mapping_data,\n attribute_memo=attribute_memo,\n )\n mapping_list.append(mapping)\n return mapping_list",
"def load_annos(self):\n data = None\n with open(self.anno_path, 'r') as file:\n if self.ext == '.json':\n data = json.load(file)\n\n # Label start at index 0\n if data is not None:\n for anno in data['annotations']:\n anno['category_id'] -= 1\n\n for anno in data['categories']:\n anno['id'] -= 1\n\n return data",
"def list(username, verbose, token=None, indent=None):\n mapbox_api = _get_api()\n mapbox_token = _get_token(token)\n url = \"{0}/tilesets/v1/{1}?access_token={2}\".format(\n mapbox_api, username, mapbox_token\n )\n r = requests.get(url)\n if r.status_code == 200:\n if verbose:\n for tileset in r.json():\n click.echo(json.dumps(tileset, indent=indent))\n else:\n for tileset in r.json():\n click.echo(tileset[\"id\"])\n else:\n raise errors.TilesetsError(r.text)",
"def annotation_all_stats(request):\n\n id_report = request.GET.get('report',None)\n language = request.GET.get('language',None)\n\n json_dict = get_annotations_count(id_report,language)\n\n # print('annotations',json_dict)\n return JsonResponse(json_dict)",
"def load_annotations(self):\n # get keys\n with open(self.ann_file, 'r') as fin:\n keys = [line.strip().split(' ')[0] for line in fin]\n # get frame index list for LQ frames\n frame_index_list = []\n for i in range(self.num_input_frames):\n # Each clip of Vimeo90K has 7 frames starting from 1. So we use 9\n # for generating frame_index_list:\n # N | frame_index_list\n # 1 | 4\n # 3 | 3,4,5\n # 5 | 2,3,4,5,6\n # 7 | 1,2,3,4,5,6,7\n frame_index_list.append(i + (9 - self.num_input_frames) // 2)\n\n data_infos = []\n for key in keys:\n folder, subfolder = key.split('/')\n lq_paths = []\n for i in frame_index_list:\n lq_paths.append(\n osp.join(self.lq_folder, folder, subfolder, f'im{i}.png'))\n gt_paths = [osp.join(self.gt_folder, folder, subfolder, 'im4.png')]\n\n data_infos.append(\n dict(lq_path=lq_paths, gt_path=gt_paths, key=key))\n\n return data_infos",
"def ListAnnotations(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def getMappingSets(self,name:str=None,prop:str=None,limit:int=100)->list:\n params ={\"limit\":limit}\n if name is not None:\n params['name'] = name\n if prop is not None:\n params['property'] = prop\n path = \"/mappingSets\"\n res = self.connector.getData(self.endpoint+path,params=params)\n data = res[\"data\"]\n return data",
"def skills():\n with app.app_context():\n results = Skill.query.all()\n return SkillsResponse(skills=results).json(), 200",
"def labelset_list(request):\n\n publicSources = Source.objects.filter(visibility=Source.VisibilityTypes.PUBLIC)\n publicSourcesWithLabelsets = publicSources.exclude(labelset=LabelSet.getEmptyLabelset())\n\n return render_to_response('annotations/labelset_list.html', {\n 'publicSourcesWithLabelsets': publicSourcesWithLabelsets,\n },\n context_instance=RequestContext(request)\n )",
"def record_sets_fetcher(record):\n return record.get(\"_oai\", {}).get(\"sets\", [])",
"def load_annotations(self, index):\n anns_file = open(os.path.join(self.folder_path, self.image_ids[index] + '.json'))\n labels = json.load(anns_file)\n labels = labels[\"shapes\"]\n anns_file.close()\n return labels.copy()",
"def get_analysis_annotations():\n sample_id = demisto.getArg('id')\n r = req('GET', SUB_API + 'samples/' + sample_id + '/analysis/annotations')\n\n annotations = []\n context_path = 'ThreatGrid.AnalysisResults.Sample.Id.Annotations'\n ec = {context_path: []} # type: ignore\n ips = demisto.get(r.json(), 'data.items.network') # type: ignore\n if ips:\n for k in ips:\n annotation = {\n 'IP': k,\n 'IP.Asn': ips[k].get('asn'),\n 'IP.City': ips[k].get('city'),\n 'IP.Country': ips[k].get('country'),\n 'IP.Org': ips[k].get('org'),\n 'IP.Region': ips[k].get('region'),\n 'IP.Timestamp': ips[k].get('ts')\n }\n annotations.append(annotation)\n ec[context_path].append(annotation)\n\n demisto.results({\n 'Type': entryTypes['note'],\n 'ContentsFormat': formats['json'],\n 'Contents': r.json(),\n 'EntryContext': ec,\n 'HumanReadable': tableToMarkdown('ThreatGrid - Analysis Annotations', annotations, [\n 'IP', 'IP.Asn', 'IP.City', 'IP.Country', 'IP.Org', 'IP.Region', 'IP.Timestamp'\n ])\n })",
"def get_annotation_list(\n self,\n project_id: int,\n doc_id: int\n ) -> requests.models.Response:\n return self.get(\n 'v1/projects/{project_id}/docs/{doc_id}/annotations'.format(\n project_id=project_id,\n doc_id=doc_id\n )\n )",
"def __gen_annoset_file(self):\n paula_id = '{}.{}.anno'.format(self.corpus_name, self.name)\n E, tree = gen_paula_etree(paula_id)\n\n slist = E('structList', {'type': 'annoSet'})\n # NOTE: we could group all the annotations into different structs\n # but I don't see the point. We're already using namespaces, after all\n struct = E('struct', {'id': 'anno_all_annotations'})\n for i, file_id in enumerate(self.files):\n struct.append(E('rel',\n {'id': 'rel_{}'.format(i),\n XLINKHREF: file_id+'.xml'}))\n slist.append(struct)\n tree.append(slist)\n self.files[paula_id] = tree\n self.file2dtd[paula_id] = PaulaDTDs.struct\n return paula_id",
"def get_filtered_dataset_annotations(config):\n\n images_filenames = net.data.get_dataset_filenames(\n config[\"voc\"][\"data_directory\"], config[\"voc\"][\"validation_set_path\"])\n\n annotations_paths = [os.path.join(config[\"voc\"][\"data_directory\"], \"Annotations\", image_filename + \".xml\")\n for image_filename in images_filenames]\n\n labels_to_categories_index_map = {label: index for (index, label) in enumerate(config[\"categories\"])}\n\n all_annotations = []\n\n for annotations_path in tqdm.tqdm(annotations_paths):\n\n with open(annotations_path) as file:\n\n image_annotations_xml = xmltodict.parse(file.read())\n\n image_size = \\\n int(image_annotations_xml[\"annotation\"][\"size\"][\"height\"]), \\\n int(image_annotations_xml[\"annotation\"][\"size\"][\"width\"])\n\n # Read annotations\n annotations = net.data.get_objects_annotations(\n image_annotations=image_annotations_xml,\n labels_to_categories_index_map=labels_to_categories_index_map)\n\n # Resize annotations in line with how we would resize the image\n annotations = [annotation.resize(image_size, config[\"size_factor\"]) for annotation in annotations]\n\n # Discard odd sized annotations\n annotations = \\\n [annotation for annotation in annotations\n if not net.utilities.is_annotation_size_unusual(annotation, **config[\"objects_filtering\"])]\n\n all_annotations.extend(annotations)\n\n return all_annotations",
"def get_all(self, cube_name: str, **kwargs) -> List[Annotation]:\n url = format_url(\"/api/v1/Cubes('{}')/Annotations?$expand=DimensionalContext($select=Name)\", cube_name)\n response = self._rest.GET(url, **kwargs)\n\n annotations_as_dict = response.json()['value']\n annotations = [Annotation.from_json(json.dumps(element)) for element in annotations_as_dict]\n return annotations",
"def dataset_list(self):\n\n response = self.send(root_url=self.session.dm_url + self.root_url,\n verb=GenericClient.VERB.GET,\n template=TEMPLATES['get_data_set_list'])\n\n results = []\n\n try:\n # Keep only the necessary fields from the request\n for content in response.json:\n results.append({'name': content['name'], 'description': content['description']})\n except IndexError:\n # Return emtpy results if parsing error\n pass\n return results",
"def list_roles(self, startIndex=0, pageSize=10):\n uURL = self._url + \"/roles/getRoles\"\n params = {\n \"f\" : \"json\",\n \"startIndex\" : startIndex,\n \"pageSize\" : pageSize\n }\n return self._con.post(path=uURL, postdata=params)"
] | [
"0.6487683",
"0.6477073",
"0.6375824",
"0.57720244",
"0.54939544",
"0.54250336",
"0.48604977",
"0.4719252",
"0.4695324",
"0.4684262",
"0.46787098",
"0.4673763",
"0.44869906",
"0.44823048",
"0.44784552",
"0.44707522",
"0.446004",
"0.44433045",
"0.44333726",
"0.4365424",
"0.43390915",
"0.4295629",
"0.42867845",
"0.42763722",
"0.4261605",
"0.42464238",
"0.4237043",
"0.42323086",
"0.42147815",
"0.4203733"
] | 0.76015735 | 0 |
Create a new NLU annotation set for a skill which will generate a new annotationId. This is an API that creates a new NLU annotation set with properties and returns the annotationId. | def create_nlu_annotation_set_v1(self, skill_id, create_nlu_annotation_set_request, **kwargs):
# type: (str, CreateNLUAnnotationSetRequest_16b1430c, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, CreateNLUAnnotationSetResponse_b069cada]
operation_name = "create_nlu_annotation_set_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'create_nlu_annotation_set_request' is set
if ('create_nlu_annotation_set_request' not in params) or (params['create_nlu_annotation_set_request'] is None):
raise ValueError(
"Missing the required parameter `create_nlu_annotation_set_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/nluAnnotationSets'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_nlu_annotation_set_request' in params:
body_params = params['create_nlu_annotation_set_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.nlu.annotation_sets.create_nlu_annotation_set_response.CreateNLUAnnotationSetResponse", status_code=201, message="NLU annotation set created successfully."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.nlu.annotation_sets.create_nlu_annotation_set_response.CreateNLUAnnotationSetResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_annotations_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, accept, **kwargs):\n # type: (str, str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"get_annotations_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'accept' is set\n if ('accept' not in params) or (params['accept'] is None):\n raise ValueError(\n \"Missing the required parameter `accept` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/annotations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n if 'accept' in params:\n header_params.append(('Accept', params['accept']))\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=200, message=\"The specific version of a NLU annotation set has the content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def __gen_annoset_file(self):\n paula_id = '{}.{}.anno'.format(self.corpus_name, self.name)\n E, tree = gen_paula_etree(paula_id)\n\n slist = E('structList', {'type': 'annoSet'})\n # NOTE: we could group all the annotations into different structs\n # but I don't see the point. We're already using namespaces, after all\n struct = E('struct', {'id': 'anno_all_annotations'})\n for i, file_id in enumerate(self.files):\n struct.append(E('rel',\n {'id': 'rel_{}'.format(i),\n XLINKHREF: file_id+'.xml'}))\n slist.append(struct)\n tree.append(slist)\n self.files[paula_id] = tree\n self.file2dtd[paula_id] = PaulaDTDs.struct\n return paula_id",
"def list_nlu_annotation_sets_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListNLUAnnotationSetsResponse_5b1b0b6a, BadRequestError_f854b05]\n operation_name = \"list_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'locale' in params:\n query_params.append(('locale', params['locale']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.list_nlu_annotation_sets_response.ListNLUAnnotationSetsResponse\", status_code=200, message=\"NLU annotation sets are returned.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.list_nlu_annotation_sets_response.ListNLUAnnotationSetsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def delete_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"delete_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"NLU annotation set exists and is deleted successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def RDFAnnotationParser_createAnnotation():\n return _libsbml.RDFAnnotationParser_createAnnotation()",
"def get_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUAnnotationSetPropertiesResponse_731f20d3, BadRequestError_f854b05]\n operation_name = \"get_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse\", status_code=200, message=\"The NLU annotation set exists.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.annotation_sets.get_nlu_annotation_set_properties_response.GetNLUAnnotationSetPropertiesResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def update_annotations_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, content_type, update_nlu_annotation_set_annotations_request, **kwargs):\n # type: (str, str, str, UpdateNLUAnnotationSetAnnotationsRequest_b336fe43, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_annotations_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'content_type' is set\n if ('content_type' not in params) or (params['content_type'] is None):\n raise ValueError(\n \"Missing the required parameter `content_type` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_nlu_annotation_set_annotations_request' is set\n if ('update_nlu_annotation_set_annotations_request' not in params) or (params['update_nlu_annotation_set_annotations_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_nlu_annotation_set_annotations_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/annotations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n if 'content_type' in params:\n header_params.append(('Content-Type', params['content_type']))\n\n body_params = None\n if 'update_nlu_annotation_set_annotations_request' in params:\n body_params = params['update_nlu_annotation_set_annotations_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=200, message=\"NLU annotation set exists and starts the update.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def update_properties_for_nlu_annotation_sets_v1(self, skill_id, annotation_id, update_nlu_annotation_set_properties_request, **kwargs):\n # type: (str, str, UpdateNLUAnnotationSetPropertiesRequest_b569f485, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"update_properties_for_nlu_annotation_sets_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'annotation_id' is set\n if ('annotation_id' not in params) or (params['annotation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `annotation_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'update_nlu_annotation_set_properties_request' is set\n if ('update_nlu_annotation_set_properties_request' not in params) or (params['update_nlu_annotation_set_properties_request'] is None):\n raise ValueError(\n \"Missing the required parameter `update_nlu_annotation_set_properties_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluAnnotationSets/{annotationId}/properties'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'annotation_id' in params:\n path_params['annotationId'] = params['annotation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'update_nlu_annotation_set_properties_request' in params:\n body_params = params['update_nlu_annotation_set_properties_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=201, message=\"NLU annotation set exists and properties are updated successfully.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"PUT\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def createAnnotation():\n return _libsbml.RDFAnnotationParser_createAnnotation()",
"def test_01_add_ms_annotation(self):\n self.addAnnotation(\"mgmt-server-annotation1\", self.mgmt_server.id, \"MANAGEMENT_SERVER\")\n self.assertEqual(self.added_annotations[-1].annotation.annotation, \"mgmt-server-annotation1\")",
"def _mint_trna_annotation(data):\n trna_lookup = op.join(dd.get_srna_mint_lookup(data))\n trna_space = op.join(dd.get_srna_mint_space(data))\n trna_other = op.join(dd.get_srna_mint_other(data))\n name = dd.get_sample_name(data)\n work_dir = utils.safe_makedir(os.path.join(dd.get_work_dir(data), \"trna_mint\", name))\n in_file = op.basename(data[\"clean_fastq\"])\n mintmap = os.path.realpath(os.path.join(os.path.dirname(sys.executable), \"MINTmap.pl\"))\n perl_export = utils.get_perl_exports()\n if not file_exists(trna_lookup) or not file_exists(mintmap):\n logger.info(\"There is no tRNA annotation to run MINTmap.\")\n return work_dir\n jar_folder = os.path.join(os.path.dirname(mintmap), \"MINTplates\")\n out_file = op.join(work_dir, name + \"-MINTmap_v1-exclusive-tRFs.expression.txt\")\n if not file_exists(out_file):\n with tx_tmpdir(data) as txdir:\n with utils.chdir(txdir):\n utils.symlink_plus(data[\"clean_fastq\"], op.join(txdir, in_file))\n cmd = (\"{perl_export} && {mintmap} -f {in_file} -p {name} \"\n \"-l {trna_lookup} -s {trna_space} -j {jar_folder} \"\n \"-o {trna_other}\").format(**locals())\n do.run(cmd, \"tRNA for %s\" % name)\n for filename in glob.glob(\"*MINTmap*\"):\n shutil.move(filename, work_dir)\n return work_dir",
"def DocumentAnnotationSet(self, wave_id, wavelet_id, blip_id, start, end,\n name, value):\n annotation = document.Annotation(name, value, document.Range(start, end))\n op = Operation(DOCUMENT_ANNOTATION_SET, wave_id, wavelet_id,\n blip_id=blip_id,\n prop=annotation)\n self.__context.AddOperation(op)",
"def prepare_set(text, max_length=64):\n global tokenizer\n\n text = [ preprocess_text(t) if set_id != \"gr\" else strip_accents_and_lowercase(preprocess_text(t)) for t in text ]\n t = tokenizer.batch_encode_plus(text,\n pad_to_max_length=True,\n add_special_tokens=True,\n max_length=max_length,\n return_tensors='pt')\n\n return t[\"input_ids\"], t[\"attention_mask\"], t[\"token_type_ids\"]",
"def _create_examples_id(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n # if i == 0:\n # continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[1]\n text_b = None\n label = line[2]\n ID=line[3]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label,ID=ID))\n return examples",
"def _create_examples_id(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n # if i == 0:\n # continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[1]\n text_b = None\n label = line[2]\n ID=line[3]\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label,ID=ID))\n return examples",
"def _build_ID_sets(self):\n raise NotImplementedError",
"def add_annotations(self, annotations, categories):\n annotations_id = COCOTools.get_annotations_id(self.coco[\"annotations\"])\n categories_id = COCOTools.get_categories_id(self.coco[\"categories\"])\n # cat_name = categories_id.keys()\n # cat_id = categories_id.values()\n max_id = 0\n if annotations_id:\n max_id = max(annotations_id)\n add_categories_id = COCOTools.get_categories_id(categories)\n add_id_categories = {v: k for k, v in add_categories_id.items()}\n\n for item in annotations:\n category_id = item[\"category_id\"]\n name = add_id_categories[category_id]\n item[\"category_id\"] = categories_id[name]\n max_id += 1\n item[\"id\"] = max_id\n self.coco['annotations'].append(item)\n # annotations_id__ = self.get_annotations_id(self.coco[\"annotations\"])\n # self.check_uniqueness(annotations_id, title=\"annotations_id\")",
"def create_mapset(self, mapset, dbase=None, location=None):\n module = 'g.mapset'\n gs.run_command(module, flags='c', mapset=mapset, dbase=dbase, location=location)",
"def perform_create(self, serializer):\n try:\n\n # Create the document object\n long_url = serializer.validated_data['long_url']\n document, _ = Document.objects.get_or_create(long_url=long_url)\n serializer.instance = document\n\n # Create the annotation object\n annotate, _ = Annotation.objects.get_or_create(\n user = self.request.user, document = document\n )\n\n except CorpusException as e:\n raise ValidationError(str(e))",
"def addAnnotation(self, token, title, text, start, end = None):\n\t\tif end is None:\n\t\t\tpayload = \"{\\\"title\\\":\\\"\" + title + \"\\\", \\\"start\\\": \\\"\" + str(start) + \"\\\", \\\"text\\\":\\\"\" + text + \"\\\"}\"\n\t\telse:\n\t\t\tpayload = \"{\\\"title\\\":\\\"\" + title + \"\\\", \\\"start\\\": \\\"\" + str(start) + \"\\\", \\\"end\\\":\\\"\" + str(end) + \"\\\", \\\"text\\\":\\\"\" + text + \"\\\"}\"\n\t\tif self.simulate:\n\t\t\tself.logger.info(\"[SIMULATE] adding new annotation: \" + payload)\t\n\t\t\treturn\n\t\tself.logger.info(\"adding new annotation: \" + payload)\t\n\n\t\t#self.logger.info(\"WARNING: mpulse API handler disabled!\")\n\t\t#return\n\t\turl = \"https://mpulse.soasta.com/concerto/mpulse/api/annotations/v1\"\n\t\tresult = requests.post(url, data = payload, headers={'Content-Type':'application/json', 'X-Auth-Token': token })\n\t\tif (result.status_code == 200):\n\t\t\tjson_data = result.json()\n\t\t\tself.logger.info('annotation successfully added')\n\t\telse:\n\t\t\tself.logger.error('Error ' + str(result.status_code) + ': annotation not added!')",
"def _set_skill(caller, _, **kwargs):\n pool = _skill_pool(caller, kwargs.get(\"skill\"))\n caller.db.d1_skills[kwargs.get(\"skill\")][\"rank\"] += 1\n caller.ndb.pregen[\"skills\"] = pool\n\n return \"node_skills\"",
"def new_set(*, ctx: context.ContextLevel, **kwargs) -> irast.Set:\n ir_set = irast.Set(**kwargs)\n ctx.all_sets.append(ir_set)\n return ir_set",
"def _get_ann_file(self):\n prefix = 'instances' if 'test' not in self.image_set else 'image_info'\n return os.path.join(self.data_path, 'annotations',\n prefix + '_' + self.image_set + '.json')",
"def add_annotations(annot_tuples, ref_data, annot_type):\n\n for annot in ref_data.annotations.select_type(annot_type):\n annot_begin, annot_end = annot.spans[0]\n annot_tuples.append((annot_begin, annot_end, annot.id))",
"def create_mapset(self, mapset, dbase=None, location=None):\n module = 'g.c.mapset'\n gs.run_command(module, mapset=mapset, dbase=dbase, location=location)",
"def create_auto_annotations(request): # post\n\n request_body_json = json.loads(request.body)\n usecase_list = request_body_json['usecase']\n fields_list = request_body_json['selected']\n report_key = request_body_json['report_type']\n batch = request_body_json['batch']\n\n # check existence of examode labels and concepts\n\n if report_key == 'reports':\n for usecase in usecase_list:\n fields = []\n if fields_list != {}:\n if usecase in fields_list.keys():\n fields = list(set(fields_list[usecase]))\n workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in\n with open(os.path.join(workpath, './automatic_annotation/auto_fields/auto_fields.json'),\n 'r') as use_outfile:\n json_to_ret = json.load(use_outfile)\n json_to_ret['extract_fields'][usecase] = fields\n # print(json_to_ret)\n with open(os.path.join(workpath, './automatic_annotation/auto_fields/auto_fields.json'), 'w') as use_outfile:\n json.dump(json_to_ret,use_outfile)\n\n # print(fields)\n\n workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in\n # output_concepts_dir = os.path.join(workpath, './sket/outputs')\n # for root, dirs, files in os.walk(output_concepts_dir):\n # for f in files:\n # os.unlink(os.path.join(root, f))\n # for d in dirs:\n # shutil.rmtree(os.path.join(root, d))\n\n bool_val,error = create_auto_gt_1(usecase,fields,report_key,batch)\n if bool_val == False:\n with open(os.path.join(workpath, './automatic_annotation/auto_fields/auto_fields.json'),\n 'r') as use_outfile:\n json_to_ret = json.load(use_outfile)\n json_to_ret['extract_fields'][usecase] = []\n # print(json_to_ret)\n with open(os.path.join(workpath, './automatic_annotation/auto_fields/auto_fields.json'),\n 'w') as use_outfile:\n json.dump(json_to_ret, use_outfile)\n json_resp = {'error': error}\n return JsonResponse(json_resp)\n\n elif report_key == 'pubmed':\n for usecase in usecase_list:\n fields = ['title','abstract']\n # workpath = os.path.dirname(os.path.abspath(__file__)) # Returns the Path your .py file is in\n # output_concepts_dir = os.path.join(workpath, './sket/outputs')\n # for root, dirs, files in os.walk(output_concepts_dir):\n # for f in files:\n # os.unlink(os.path.join(root, f))\n # for d in dirs:\n # shutil.rmtree(os.path.join(root, d))\n\n bool_val, error = create_auto_gt_1(usecase, fields, report_key, batch)\n if bool_val == False:\n json_resp = {'error': error}\n return JsonResponse(json_resp)\n\n json_resp = {'msg':'ok'}\n return JsonResponse(json_resp)",
"def set_or_create_dataset(conn: BlitzGateway, project_id: Union[int, None],\n dataset: Union[str, int],\n across_groups: Optional[bool] = True\n ) -> Union[int, None]:\n if isinstance(dataset, str):\n if project_id:\n dataset_id = post_dataset(conn, dataset, project_id=project_id)\n else:\n dataset_id = post_dataset(conn, dataset)\n print(f'Created new Dataset:{dataset_id}')\n elif (isinstance(dataset, int)):\n dataset_id = dataset\n else:\n raise TypeError(\"'dataset' must be str or int\")\n return dataset_id",
"def add_input_set(name, my_session):\n iset = InputSet(name=name)\n my_session.add(iset)\n my_session.commit()\n log.info('Added input set \"%s\"' % name, 'input.py')\n return iset.id",
"def create(data):\n \n return Setlist(\n list_id = data['id'],\n name = data['name'],\n items = data['num_sets'])",
"def create_intrusion_set(\n name: str,\n created_by: Optional[stix2.Identity] = None,\n created: Optional[datetime] = None,\n modified: Optional[datetime] = None,\n description: Optional[str] = None,\n aliases: Optional[List[str]] = None,\n first_seen: Optional[datetime] = None,\n last_seen: Optional[datetime] = None,\n goals: Optional[List[str]] = None,\n resource_level: Optional[str] = None,\n primary_motivation: Optional[str] = None,\n secondary_motivations: Optional[List[str]] = None,\n labels: Optional[List[str]] = None,\n confidence: Optional[int] = None,\n external_references: Optional[List[stix2.ExternalReference]] = None,\n object_markings: Optional[List[stix2.MarkingDefinition]] = None,\n) -> stix2.IntrusionSet:\n return stix2.IntrusionSet(\n id=IntrusionSet.generate_id(name),\n created_by_ref=created_by,\n created=created,\n modified=modified,\n name=name,\n description=description,\n aliases=aliases,\n first_seen=first_seen,\n last_seen=last_seen,\n goals=goals,\n resource_level=resource_level,\n primary_motivation=primary_motivation,\n secondary_motivations=secondary_motivations,\n labels=labels,\n confidence=confidence,\n external_references=external_references,\n object_marking_refs=object_markings,\n )"
] | [
"0.5991934",
"0.58785355",
"0.5876992",
"0.5777781",
"0.52043295",
"0.5172357",
"0.51515406",
"0.5148755",
"0.51152873",
"0.5086618",
"0.4977804",
"0.48819813",
"0.48653534",
"0.4863833",
"0.4863833",
"0.47762877",
"0.47746676",
"0.47074908",
"0.4689013",
"0.46825206",
"0.46769276",
"0.46754062",
"0.46644634",
"0.46580663",
"0.4656621",
"0.46515295",
"0.464007",
"0.46227834",
"0.4607714",
"0.45912123"
] | 0.7526162 | 0 |
Get top level information and status of a nlu evaluation. API which requests top level information about the evaluation like the current state of the job, status of the evaluation (if complete). Also returns data used to start the job, like the number of test cases, stage, locale, and start time. This should be considered the 'cheap' operation while getResultForNLUEvaluations is 'expensive'. | def get_nlu_evaluation_v1(self, skill_id, evaluation_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUEvaluationResponse_2fb5e6ed, BadRequestError_f854b05]
operation_name = "get_nlu_evaluation_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'evaluation_id' is set
if ('evaluation_id' not in params) or (params['evaluation_id'] is None):
raise ValueError(
"Missing the required parameter `evaluation_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/nluEvaluations/{evaluationId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'evaluation_id' in params:
path_params['evaluationId'] = params['evaluation_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_response.GetNLUEvaluationResponse", status_code=200, message="Evaluation exists and its status is queryable."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_response.GetNLUEvaluationResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_result_for_nlu_evaluations_v1(self, skill_id, evaluation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUEvaluationResultsResponse_5ca1fa54, BadRequestError_f854b05]\n operation_name = \"get_result_for_nlu_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'evaluation_id' is set\n if ('evaluation_id' not in params) or (params['evaluation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluEvaluations/{evaluationId}/results'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'evaluation_id' in params:\n path_params['evaluationId'] = params['evaluation_id']\n\n query_params = [] # type: List\n if 'sort_field' in params:\n query_params.append(('sort.field', params['sort_field']))\n if 'test_case_status' in params:\n query_params.append(('testCaseStatus', params['test_case_status']))\n if 'actual_intent_name' in params:\n query_params.append(('actualIntentName', params['actual_intent_name']))\n if 'expected_intent_name' in params:\n query_params.append(('expectedIntentName', params['expected_intent_name']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_results_response.GetNLUEvaluationResultsResponse\", status_code=200, message=\"Evaluation exists and its status is queryable.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_results_response.GetNLUEvaluationResultsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_test_case_info():\n m = NNMatrixTrainer()\n return m.get_evaluations()",
"def list_nlu_evaluations_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListNLUEvaluationsResponse_7ef8d08f, BadRequestError_f854b05]\n operation_name = \"list_nlu_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'locale' in params:\n query_params.append(('locale', params['locale']))\n if 'stage' in params:\n query_params.append(('stage', params['stage']))\n if 'annotation_id' in params:\n query_params.append(('annotationId', params['annotation_id']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.list_nlu_evaluations_response.ListNLUEvaluationsResponse\", status_code=200, message=\"Evaluations are returned.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.list_nlu_evaluations_response.ListNLUEvaluationsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def __get_evaluation_summary(self):\n self.logger.debug(\n f\"Getting summary for assignment {self.assignment_id}, eval_id {self.eval_id}\"\n )\n result = self.interactor.get_policy_eval_summary(self.assignment_id)\n\n if result.status_code != 200:\n self.logger.debug(\n f\"Could not get summary for assignment {self.assignment_id} for eval_id {self.eval_id} - {result.text}\"\n )\n raise Exception(\n f\"Summary could not be retrived: {result.status_code} - {result.text}\"\n )\n\n return result.json()[\"value\"][0][\"results\"]",
"def get_model_evaluation(self):\n\n self.log(f\"{self.cur_file_path}\\t\\tInfo: model_evaluation method invoked for {self.model.__class__.__name__}!\")\n\n evaluation = ModelEvaluation(self.model, (self.trainX, self.trainY), (self.testX, self.testY))\n return evaluation.get_evaluation_report()",
"def create_nlu_evaluations_v1(self, evaluate_nlu_request, skill_id, **kwargs):\n # type: (EvaluateNLURequest_7a358f6a, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, EvaluateResponse_640ae5b5, BadRequestError_f854b05]\n operation_name = \"create_nlu_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'evaluate_nlu_request' is set\n if ('evaluate_nlu_request' not in params) or (params['evaluate_nlu_request'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluate_nlu_request` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'evaluate_nlu_request' in params:\n body_params = params['evaluate_nlu_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.evaluate_response.EvaluateResponse\", status_code=200, message=\"Evaluation has successfully begun.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.evaluate_response.EvaluateResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def evaluation_status(self):\n return self._evaluation_status",
"def evaluation(self):\n return self._evaluation",
"def test_ne():\n if not PRODUCTION_ENVIRONMENT:\n remove_all_articles()\n\n eval = 'data_resources/ned/evaluation/large_eval_checked.json'\n output = process_evaluation_input(eval)\n eval_output = json.load(open(eval))\n evaluate_ned(output, eval_output)",
"def evaluate(self) -> Dict[str, float]:\n eval_dataloader = self.get_eval_dataloader()\n\n output = self._prediction_loop(eval_dataloader, description=\"Evaluation\")\n return output.metrics",
"def getResults(self):\n if self.__jobInfo.results is not None:\n return json.loads(self.__jobInfo.results)\n else:\n return None",
"def evaluate():\n log.info('Loading dev data...')\n if args.version_2:\n dev_data = SQuAD('dev', version='2.0')\n else:\n dev_data = SQuAD('dev', version='1.1')\n (_, _), (data_file_name, _) \\\n = dev_data._data_file[dev_data._version][dev_data._segment]\n dev_data_path = os.path.join(dev_data._root, data_file_name)\n\n if args.debug:\n sampled_data = [dev_data[0], dev_data[1], dev_data[2]]\n dev_data = mx.gluon.data.SimpleDataset(sampled_data)\n log.info('Number of records in dev data: %d', len(dev_data))\n\n dev_data_features = preprocess_dataset(\n tokenizer, dev_data, vocab=vocab, max_seq_length=args.max_seq_length,\n doc_stride=args.doc_stride, num_workers=args.num_workers,\n max_query_length=args.max_query_length, load_from_pickle=args.load_pickle,\n feature_file=args.dev_dataset_file)\n\n dev_data_input = convert_full_features_to_input_features(dev_data_features)\n log.info('The number of examples after preprocessing: %d', len(dev_data_input))\n\n dev_dataloader = mx.gluon.data.DataLoader(dev_data_input, batchify_fn=batchify_fn,\n num_workers=4, batch_size=args.test_batch_size,\n shuffle=False, last_batch='keep')\n\n log.info('start prediction')\n\n all_results = collections.defaultdict(list)\n\n epoch_tic = time.time()\n total_num = 0\n for (batch_id, data) in enumerate(dev_dataloader):\n data_list = list(split_and_load(data, ctx))\n for splited_data in data_list:\n example_ids, inputs, token_types, valid_length, p_mask, _, _, _ = splited_data\n total_num += len(inputs)\n outputs = net_eval(inputs, token_types, valid_length, p_mask=p_mask)\n example_ids = example_ids.asnumpy().tolist()\n for c, example_ids in enumerate(example_ids):\n result = RawResultExtended(start_top_log_probs=outputs[0][c].asnumpy().tolist(),\n start_top_index=outputs[1][c].asnumpy().tolist(),\n end_top_log_probs=outputs[2][c].asnumpy().tolist(),\n end_top_index=outputs[3][c].asnumpy().tolist(),\n cls_logits=outputs[4][c].asnumpy().tolist())\n all_results[example_ids].append(result)\n if batch_id % args.log_interval == 0:\n log.info('Batch: %d/%d', batch_id + 1, len(dev_dataloader))\n\n epoch_toc = time.time()\n log.info('Time cost=%2f s, Thoughput=%.2f samples/s', epoch_toc - epoch_tic,\n total_num / (epoch_toc - epoch_tic))\n\n log.info('Get prediction results...')\n\n all_predictions = collections.OrderedDict()\n all_nbest_json = collections.OrderedDict()\n scores_diff_json = collections.OrderedDict()\n for features in dev_data_features:\n results = all_results[features[0].example_id]\n example_qas_id = features[0].qas_id\n score_diff, best_non_null_entry, nbest_json = predict_extended(\n features=features, results=results, n_best_size=args.n_best_size,\n max_answer_length=args.max_answer_length, start_n_top=args.start_top_n,\n end_n_top=args.end_top_n)\n scores_diff_json[example_qas_id] = score_diff\n all_predictions[example_qas_id] = best_non_null_entry\n all_nbest_json[example_qas_id] = nbest_json\n\n output_prediction_file = os.path.join(args.output_dir, 'predictions.json')\n output_nbest_file = os.path.join(args.output_dir, 'nbest_predictions.json')\n output_null_log_odds_file = os.path.join(args.output_dir, 'null_odds.json')\n\n with open(output_prediction_file, 'w') as writer:\n writer.write(json.dumps(all_predictions, indent=4) + '\\n')\n with open(output_nbest_file, 'w') as writer:\n writer.write(json.dumps(all_nbest_json, indent=4) + '\\n')\n with open(output_null_log_odds_file, 'w') as writer:\n writer.write(json.dumps(scores_diff_json, indent=4) + '\\n')\n\n if os.path.exists(sys.path[0] + '/evaluate-v2.0.py'):\n arguments = [\n dev_data_path, output_prediction_file, '--na-prob-thresh',\n str(args.null_score_diff_threshold)\n ]\n if args.version_2:\n arguments += ['--na-prob-file', output_null_log_odds_file]\n subprocess.call([sys.executable, sys.path[0] + '/evaluate-v2.0.py'] + arguments)\n else:\n log.info('Please download evaluate-v2.0.py to get evaluation results for SQuAD. '\n 'Check index.rst for the detail.')",
"def get_results(self):\n self.report('Checking finished evaluations.')\n outputs = {}\n while self.indices_to_retrieve:\n idx = self.indices_to_retrieve.pop(0)\n key = self.eval_key(idx)\n self.report('Retrieving output for evaluation {}'.format(idx))\n eval_proc = self.ctx[key]\n if not eval_proc.is_finished_ok:\n return self.exit_codes.ERROR_EVALUATE_PROCESS_FAILED\n outputs[idx] = get_outputs_dict(eval_proc)\n\n with self.optimizer() as opt:\n opt.update(outputs)",
"def getEngStatus(self):\n return self.__jobInfo.engStatus",
"def GetEvaluations(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def evaluation( self ) :\n\n return( self.__evaluation )",
"def _evaluation():\n return {\n 'type' : 'class',\n 'name' : 'evaluation',\n 'base' : None,\n 'is_abstract' : False,\n 'doc' : None,\n 'properties' : [\n ('date', 'datetime', '0.1', None),\n ('description', 'str', '0.1', None),\n ('did_pass', 'bool', '0.1', None),\n ('explanation', 'str', '0.1', None),\n ('specification', 'str', '0.1', None),\n ('specification_hyperlink', 'str', '0.1', None),\n ('type', 'str', '0.1', None),\n ('type_hyperlink', 'str', '0.1', None),\n ('title', 'str', '0.1', None),\n ],\n 'decodings' : [\n ('date', 'child::gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:date/gmd:CI_Date/gmd:date/gco:Date'),\n ('description', 'gmd:evaluationMethodDescription/gco:CharacterString'),\n ('did_pass', 'child::gmd:result/gmd:DQ_ConformanceResult/gmd:pass/gco:Boolean'),\n ('explanation', 'child::gmd:result/gmd:DQ_ConformanceResult/gmd:explanation/gco:CharacterString'),\n ('type', 'child::gmd:result/@xlink:title'),\n ('type_hyperlink', 'child::gmd:result/@xlink:href'),\n ('specification', 'child::gmd:result/gmd:DQ_ConformanceResult/gmd:specification/@xlink:title'),\n ('specification_hyperlink', 'child::gmd:result/gmd:DQ_ConformanceResult/gmd:specification/@xlink:href'),\n ('title', 'child::gmd:result/gmd:DQ_ConformanceResult/gmd:specification/gmd:CI_Citation/gmd:title/gco:CharacterString'),\n ]\n }",
"def get_status(request):\n ecc_server_status_list = get_ecc_server_statuses(request)\n data_router_status_list = get_data_router_statuses(request)\n overall_state, overall_state_name = calculate_overall_state(request)\n\n current_run = request.experiment.latest_run\n if current_run is not None:\n run_number = current_run.run_number\n start_time = current_run.start_datetime.strftime('%b %d %Y, %H:%M:%S')\n duration_str = current_run.duration_string\n run_title = current_run.title\n run_class = current_run.get_run_class_display()\n else:\n run_number = None\n start_time = None\n duration_str = None\n run_title = None\n run_class = None\n\n output = {\n 'overall_state': overall_state,\n 'overall_state_name': overall_state_name,\n 'ecc_server_status_list': ecc_server_status_list,\n 'data_router_status_list': data_router_status_list,\n 'run_number': run_number,\n 'start_time': start_time,\n 'run_duration': duration_str,\n 'run_title': run_title,\n 'run_class': run_class,\n }\n\n return output",
"def evaluate_data():\n try:\n # General system related info\n ram = psutil.virtual_memory()\n total_ram = round((ram.total / 1024 / 1024),2)\n free_ram = round((ram.available / 1024 / 1024),2)\n used_ram = round((ram.used / 1024 / 1024),2)\n cpu_total = psutil.cpu_count(logical=True)\n cpu_loadavg = round([x / cpu_total * 100 for x in psutil.getloadavg()][0],2)\n acs_8080 = sp.getoutput(\"netstat -an|grep -c 8080\")\n acs_8181 = sp.getoutput(\"netstat -an|grep -c 8181\")\n acs_8443 = sp.getoutput(\"netstat -an|grep -c 8443\")\n mysql = sp.getoutput(\"netstat -an|grep -c 3306\")\n oracle = sp.getoutput(\"netstat -an|grep -c 1521\")\n logging.info('General system info obtained')\n except Exception as e:\n logging.exception(f\"EXCEPTION: {e} \\n Full stack trace: \\n\", exc_info=1)\n # Process specific details\n try:\n iis_pid = SystemInformation.get_pid(\"w3wp.exe\")\n iis_ram = SystemInformation.get_ram_usage(iis_pid)\n iis_cpu = SystemInformation.get_cpu_usage(iis_pid)\n java_pid = SystemInformation.get_pid(\"java.exe\")\n java_ram = SystemInformation.get_ram_usage(java_pid)\n java_cpu = SystemInformation.get_cpu_usage(java_pid)\n mysqld_pid = SystemInformation.get_pid(\"mysqld.exe\")\n mysqld_ram = SystemInformation.get_ram_usage(mysqld_pid) \n mysqld_cpu = SystemInformation.get_cpu_usage(mysqld_pid)\n except Exception as e:\n logging.exception(f\"EXCEPTION: {e} \\n Full stack trace: \\n\", exc_info=1)\n\n try:\n dictionary = {}\n now = datetime.datetime.now()\n timestampt = now.strftime(\"%Y-%m-%d-%H:%M:%S\")\n fieldnames = ['timestampt','total_ram','free_ram','used_ram','cpu_total','cpu_loadavg','acs_8080','acs_8181','acs_8443','mysql','oracle','iis_ram','iis_cpu','java_ram','java_cpu','mysqld_ram','mysqld_cpu']\n for var in fieldnames:\n dictionary[var] = eval(var)\n \n logging.info('Data for report generated')\n return dictionary\n except Exception as e:\n logging.exception(f\"EXCEPTION: {e} \\n Full stack trace: \\n\", exc_info=1)",
"def get_status(self):\n url = \"data_request?id=jobstatus&job=%d&plugin=zwave\" % self.id\n return self.vera.get(url)",
"def get_result(self):\n config = self.bisect_config\n results_confidence = 0\n if self.culprit:\n results_confidence = self.api.m.math_utils.confidence_score(\n self.lkgr.values, self.fkbr.values)\n\n if self.failed:\n status = 'failed'\n elif self.bisect_over:\n status = 'completed'\n else:\n status = 'started'\n\n aborted_reason = None\n if self.failed_initial_confidence:\n aborted_reason = _FAILED_INITIAL_CONFIDENCE_ABORT_REASON\n elif self.failed_direction:\n aborted_reason = _DIRECTION_OF_IMPROVEMENT_ABORT_REASON\n return {\n 'try_job_id': config.get('try_job_id'),\n 'bug_id': config.get('bug_id'),\n 'status': status,\n 'buildbot_log_url': self._get_build_url(),\n 'bisect_bot': self.get_perf_tester_name(),\n 'command': config['command'],\n 'test_type': config['test_type'],\n 'metric': config['metric'],\n 'change': self.relative_change,\n 'score': results_confidence,\n 'good_revision': self.good_rev.commit_hash,\n 'bad_revision': self.bad_rev.commit_hash,\n 'warnings': self.warnings,\n 'aborted_reason': aborted_reason,\n 'culprit_data': self._culprit_data(),\n 'revision_data': self._revision_data()\n }",
"async def get_evaluation(\n self,\n request: Optional[\n Union[data_labeling_service.GetEvaluationRequest, dict]\n ] = None,\n *,\n name: Optional[str] = None,\n retry: OptionalRetry = gapic_v1.method.DEFAULT,\n timeout: Union[float, object] = gapic_v1.method.DEFAULT,\n metadata: Sequence[Tuple[str, str]] = (),\n ) -> evaluation.Evaluation:\n # Create or coerce a protobuf request object.\n # Quick check: If we got a request object, we should *not* have\n # gotten any keyword arguments that map to the request.\n has_flattened_params = any([name])\n if request is not None and has_flattened_params:\n raise ValueError(\n \"If the `request` argument is set, then none of \"\n \"the individual field arguments should be set.\"\n )\n\n request = data_labeling_service.GetEvaluationRequest(request)\n\n # If we have keyword arguments corresponding to fields on the\n # request, apply these.\n if name is not None:\n request.name = name\n\n # Wrap the RPC method; this adds retry and timeout information,\n # and friendly error handling.\n rpc = gapic_v1.method_async.wrap_method(\n self._client._transport.get_evaluation,\n default_retry=retries.Retry(\n initial=0.1,\n maximum=30.0,\n multiplier=1.3,\n predicate=retries.if_exception_type(\n core_exceptions.DeadlineExceeded,\n core_exceptions.ServiceUnavailable,\n ),\n deadline=30.0,\n ),\n default_timeout=30.0,\n client_info=DEFAULT_CLIENT_INFO,\n )\n\n # Certain fields should be provided within the metadata header;\n # add these here.\n metadata = tuple(metadata) + (\n gapic_v1.routing_header.to_grpc_metadata(((\"name\", request.name),)),\n )\n\n # Send the request.\n response = await rpc(\n request,\n retry=retry,\n timeout=timeout,\n metadata=metadata,\n )\n\n # Done; return the response.\n return response",
"def evaluate():\n tf.compat.v1.enable_eager_execution()\n\n candidate_checkpoint = None\n uflow = uflow_main.create_uflow()\n evaluate_fn, _ = uflow_data.make_eval_function(\n FLAGS.eval_on,\n FLAGS.height,\n FLAGS.width,\n progress_bar=True,\n plot_dir=FLAGS.plot_dir,\n num_plots=50)\n\n latest_checkpoint = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)\n while 1:\n # Wait for a new checkpoint\n while candidate_checkpoint == latest_checkpoint:\n logging.log_every_n(logging.INFO,\n 'Waiting for a new checkpoint, at %s, latest is %s',\n 20, FLAGS.checkpoint_dir, latest_checkpoint)\n time.sleep(0.5)\n candidate_checkpoint = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)\n candidate_checkpoint = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)\n latest_checkpoint = candidate_checkpoint\n logging.info('New checkpoint found: %s', candidate_checkpoint)\n # This forces the checkpoint manager to reexamine the checkpoint directory\n # and become aware of the new checkpoint.\n uflow.update_checkpoint_dir(FLAGS.checkpoint_dir)\n uflow.restore()\n eval_results = evaluate_fn(uflow)\n uflow_plotting.print_eval(eval_results)\n step = tf.compat.v1.train.get_global_step().numpy()\n if step >= FLAGS.num_train_steps:\n logging.info('Evaluator terminating - completed evaluation of checkpoint '\n 'from step %d', step)\n return",
"def evaluate(self):\n scores = []\n scores.append(self.word_analogy())\n print(\"Word Analogy (acc): \", scores[0])\n scores.append(self.word_similarity())\n print(\"Word Similarity (MSE): \", scores[1])\n scores.append(self.concept_categorization())\n print(\"Concept Categorization (purity): \", scores[2])\n scores.append(self.sentiment_analysis())\n print(\"Sentiment Analysis (acc): \", scores[3])\n return scores",
"def get_statistics(self):\n\t\treturn Job(SDK.PrlSrv_GetStatistics(self.handle)[0])",
"def evaluate_golden_run_layer(self):\n return self._get_predictions_from_layer()",
"def get_scnlist_usr_analysis(self):\n scns2runusranalysis = list()\n if self.calc_scn_usr_analysis():\n logger.debug(\"Creating Database Engine and Session.\")\n db_engine = sqlalchemy.create_engine(self.db_info_obj.dbConn)\n session_sqlalc = sqlalchemy.orm.sessionmaker(bind=db_engine)\n ses = session_sqlalc()\n\n usr_analysis_keys = self.get_usr_analysis_keys()\n\n query_result = ses.query(EDDSentinel1ASF).filter(EDDSentinel1ASF.Invalid == False,\n EDDSentinel1ASF.ARDProduct == True).order_by(\n EDDSentinel1ASF.Acquisition_Date.asc()).all()\n\n for scn in query_result:\n scn_plgin_db_objs = ses.query(EDDSentinel1ASFPlugins).filter(EDDSentinel1ASFPlugins.Scene_PID == scn.PID).all()\n if (scn_plgin_db_objs is None) or (not scn_plgin_db_objs):\n scns2runusranalysis.append(scn.PID)\n else:\n for plugin_key in usr_analysis_keys:\n plugin_completed = False\n for plgin_db_obj in scn_plgin_db_objs:\n if (plgin_db_obj.PlugInName == plugin_key) and plgin_db_obj.Completed:\n plugin_completed = True\n break\n if not plugin_completed:\n scns2runusranalysis.append(scn.PID)\n break\n ses.close()\n logger.debug(\"Closed the database session.\")\n return scns2runusranalysis",
"def get_evaluations(self):\r\n return self.evaluations",
"def final_evaluation(self):\n df_evaluation_result = pd.read_csv(self.path_budget_evaluation_result, header=None, names=['id', 'dataset_name', 'condition', 'name', 'token', 'comment', 'ip', 'date'])\n df_evaluation_base = pd.read_csv(self.path_budget_evaluation_base)\n df_cleaned_bin = pd.read_csv(self.path_bin)\n df_answers_grouped = pd.read_pickle(self.path_answers_clean_grouped)\n df_actual_metadata = pd.read_csv(self.path_answers_metadata, index_col=0, header=[0, 1])\n df_actual_metadata = df_actual_metadata['actual']\n evaluator = ERNofeaturesEvaluator(df_evaluation_result, df_evaluation_base, df_cleaned_bin, df_actual_metadata=df_actual_metadata, target=self.target, dataset_name=self.dataset_name, df_answers_grouped=df_answers_grouped, bootstrap_n=self.bootstrap_n, repetitions=self.repetitions, replace=False)\n raw_data = evaluator.evaluate_all_to_dict(self.feature_range) # raw_data is dict: {CONDITION: {NOFEATURES: [AUCS]}}\n pickle.dump(raw_data, open(self.path_final_evaluation_aucs_nb, 'wb'))",
"def get_model_evaluation(client, model_name):\n model_evaluations = [e for e in client.list_model_evaluations(model_name)]\n model_evaluation = model_evaluations[0]\n print(\"Model evaluation:\")\n print(model_evaluation)\n return model_evaluation"
] | [
"0.6439881",
"0.6177354",
"0.59385824",
"0.5781659",
"0.5643547",
"0.55564284",
"0.5554617",
"0.54602754",
"0.54249114",
"0.53467447",
"0.53456116",
"0.5337599",
"0.53105956",
"0.526651",
"0.52644145",
"0.52471685",
"0.52046084",
"0.50835323",
"0.50834596",
"0.5078256",
"0.5077728",
"0.50637126",
"0.5030825",
"0.5023969",
"0.5007953",
"0.49855632",
"0.49793765",
"0.49770296",
"0.496444",
"0.495257"
] | 0.64801955 | 0 |
Get test case results for a completed Evaluation. Paginated API which returns the test case results of an evaluation. This should be considered the 'expensive' operation while getNluEvaluation is 'cheap'. | def get_result_for_nlu_evaluations_v1(self, skill_id, evaluation_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUEvaluationResultsResponse_5ca1fa54, BadRequestError_f854b05]
operation_name = "get_result_for_nlu_evaluations_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'evaluation_id' is set
if ('evaluation_id' not in params) or (params['evaluation_id'] is None):
raise ValueError(
"Missing the required parameter `evaluation_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/nluEvaluations/{evaluationId}/results'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'evaluation_id' in params:
path_params['evaluationId'] = params['evaluation_id']
query_params = [] # type: List
if 'sort_field' in params:
query_params.append(('sort.field', params['sort_field']))
if 'test_case_status' in params:
query_params.append(('testCaseStatus', params['test_case_status']))
if 'actual_intent_name' in params:
query_params.append(('actualIntentName', params['actual_intent_name']))
if 'expected_intent_name' in params:
query_params.append(('expectedIntentName', params['expected_intent_name']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_results_response.GetNLUEvaluationResultsResponse", status_code=200, message="Evaluation exists and its status is queryable."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_results_response.GetNLUEvaluationResultsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def __get_evaluation_summary(self):\n self.logger.debug(\n f\"Getting summary for assignment {self.assignment_id}, eval_id {self.eval_id}\"\n )\n result = self.interactor.get_policy_eval_summary(self.assignment_id)\n\n if result.status_code != 200:\n self.logger.debug(\n f\"Could not get summary for assignment {self.assignment_id} for eval_id {self.eval_id} - {result.text}\"\n )\n raise Exception(\n f\"Summary could not be retrived: {result.status_code} - {result.text}\"\n )\n\n return result.json()[\"value\"][0][\"results\"]",
"def get_results(self):\n self.report('Checking finished evaluations.')\n outputs = {}\n while self.indices_to_retrieve:\n idx = self.indices_to_retrieve.pop(0)\n key = self.eval_key(idx)\n self.report('Retrieving output for evaluation {}'.format(idx))\n eval_proc = self.ctx[key]\n if not eval_proc.is_finished_ok:\n return self.exit_codes.ERROR_EVALUATE_PROCESS_FAILED\n outputs[idx] = get_outputs_dict(eval_proc)\n\n with self.optimizer() as opt:\n opt.update(outputs)",
"def get_evaluations(self):\r\n return self.evaluations",
"def _run_one_evaluation(\n self,\n train_future: Optional[concurrent.futures.ThreadPoolExecutor] = None,\n ) -> ResultDict:\n eval_func_to_use = (\n self._evaluate_async\n if self.config.enable_async_evaluation\n else self.evaluate\n )\n\n if self.config.evaluation_duration == \"auto\":\n assert (\n train_future is not None and self.config.evaluation_parallel_to_training\n )\n unit = self.config.evaluation_duration_unit\n eval_results = eval_func_to_use(\n duration_fn=functools.partial(\n self._automatic_evaluation_duration_fn,\n unit,\n self.config.evaluation_num_workers,\n self.evaluation_config,\n train_future,\n )\n )\n # Run `self.evaluate()` only once per training iteration.\n else:\n eval_results = eval_func_to_use()\n\n if self.evaluation_workers is not None:\n # After evaluation, do a round of health check to see if any of\n # the failed workers are back.\n self.restore_workers(self.evaluation_workers)\n\n # Add number of healthy evaluation workers after this iteration.\n eval_results[\"evaluation\"][\n \"num_healthy_workers\"\n ] = self.evaluation_workers.num_healthy_remote_workers()\n eval_results[\"evaluation\"][\n \"num_in_flight_async_reqs\"\n ] = self.evaluation_workers.num_in_flight_async_reqs()\n eval_results[\"evaluation\"][\n \"num_remote_worker_restarts\"\n ] = self.evaluation_workers.num_remote_worker_restarts()\n\n return eval_results",
"def GetEvaluations(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def get_model_evaluation(self):\n\n self.log(f\"{self.cur_file_path}\\t\\tInfo: model_evaluation method invoked for {self.model.__class__.__name__}!\")\n\n evaluation = ModelEvaluation(self.model, (self.trainX, self.trainY), (self.testX, self.testY))\n return evaluation.get_evaluation_report()",
"def step(self) -> ResultDict:\n # Do we have to run `self.evaluate()` this iteration?\n # `self.iteration` gets incremented after this function returns,\n # meaning that e. g. the first time this function is called,\n # self.iteration will be 0.\n evaluate_this_iter = (\n self.config.evaluation_interval is not None\n and (self.iteration + 1) % self.config.evaluation_interval == 0\n )\n\n # Results dict for training (and if appolicable: evaluation).\n results: ResultDict = {}\n\n # Parallel eval + training: Kick off evaluation-loop and parallel train() call.\n if evaluate_this_iter and self.config.evaluation_parallel_to_training:\n (\n results,\n train_iter_ctx,\n ) = self._run_one_training_iteration_and_evaluation_in_parallel()\n # - No evaluation necessary, just run the next training iteration.\n # - We have to evaluate in this training iteration, but no parallelism ->\n # evaluate after the training iteration is entirely done.\n else:\n results, train_iter_ctx = self._run_one_training_iteration()\n\n # Sequential: Train (already done above), then evaluate.\n if evaluate_this_iter and not self.config.evaluation_parallel_to_training:\n results.update(self._run_one_evaluation(train_future=None))\n\n # Attach latest available evaluation results to train results,\n # if necessary.\n if not evaluate_this_iter and self.config.always_attach_evaluation_results:\n assert isinstance(\n self.evaluation_metrics, dict\n ), \"Algorithm.evaluate() needs to return a dict.\"\n results.update(self.evaluation_metrics)\n\n if hasattr(self, \"workers\") and isinstance(self.workers, WorkerSet):\n # Sync filters on workers.\n self._sync_filters_if_needed(\n central_worker=self.workers.local_worker(),\n workers=self.workers,\n config=self.config,\n )\n # TODO (avnishn): Remove the execution plan API by q1 2023\n # Collect worker metrics and add combine them with `results`.\n if self.config._disable_execution_plan_api:\n episodes_this_iter = collect_episodes(\n self.workers,\n self._remote_worker_ids_for_metrics(),\n timeout_seconds=self.config.metrics_episode_collection_timeout_s,\n )\n results = self._compile_iteration_results(\n episodes_this_iter=episodes_this_iter,\n step_ctx=train_iter_ctx,\n iteration_results=results,\n )\n\n # Check `env_task_fn` for possible update of the env's task.\n if self.config.env_task_fn is not None:\n if not callable(self.config.env_task_fn):\n raise ValueError(\n \"`env_task_fn` must be None or a callable taking \"\n \"[train_results, env, env_ctx] as args!\"\n )\n\n def fn(env, env_context, task_fn):\n new_task = task_fn(results, env, env_context)\n cur_task = env.get_task()\n if cur_task != new_task:\n env.set_task(new_task)\n\n fn = functools.partial(fn, task_fn=self.config.env_task_fn)\n self.workers.foreach_env_with_context(fn)\n\n return results",
"def evaluate(self) -> Dict[str, float]:\n eval_dataloader = self.get_eval_dataloader()\n\n output = self._prediction_loop(eval_dataloader, description=\"Evaluation\")\n return output.metrics",
"def run_evaluation(self, epoch=0, global_step=0, verbose=True):\n\n # step-1, compute predictions on test set\n while True:\n try:\n preds_all = helper_utils.compute_predictions(\n self.session, self.meval, global_step, self.test_files, self.comet_exp\n )\n # If epoch trained without raising the below errors, break from loop.\n break\n except (tf.errors.AbortedError, tf.errors.UnavailableError) as e:\n tf.logging.info('Retryable error caught: {}. Retrying.'.format(e))\n\n # step-2 evaluate on predictions\n results = helper_utils.eval_predictions(\n self.gt_depths, preds_all, global_step, min_depth=self.hparams.min_depth,\n max_depth=self.hparams.max_depth, verbose=verbose, comet_exp=self.comet_exp\n )\n return results, preds_all",
"def evaluate_model(self, predictions, expected, bypass_data_to_eval):\n\n result = []\n for i, unique_id in enumerate(np.squeeze(expected[\"unique_ids\"])):\n start_logits = predictions['tf_electra_for_question_answering'][i]\n start_top_index = predictions['tf_electra_for_question_answering_1'\n ][i]\n end_logits = predictions['tf_electra_for_question_answering_2'][i]\n end_top_index = predictions['tf_electra_for_question_answering_3'][i\n ]\n cls_logits = predictions['tf_electra_for_question_answering_4'][i]\n\n result.append(\n SquadResult(\n unique_id,\n start_logits.tolist(),\n end_logits.tolist(),\n start_top_index=start_top_index.tolist(),\n end_top_index=end_top_index.tolist(),\n cls_logits=cls_logits.tolist(),\n )\n )\n\n dev_features = bypass_data_to_eval[\"dev_features\"]\n dev_examples = bypass_data_to_eval[\"dev_examples\"]\n\n answers, nbest_answers = get_answers(\n dev_examples, dev_features, result, self._args\n )\n\n output_prediction_file = os.path.join(\n self._args.output_dir, \"predictions.json\"\n )\n output_nbest_file = os.path.join(\n self._args.output_dir, \"nbest_predictions.json\"\n )\n\n with open(output_prediction_file, \"w\") as f:\n f.write(json.dumps(answers, indent=4) + \"\\n\")\n with open(output_nbest_file, \"w\") as f:\n f.write(json.dumps(nbest_answers, indent=4) + \"\\n\")\n\n if self._args.version_2_with_negative:\n dev_file = \"dev-v2.0.json\"\n eval_file = \"evaluate-v2.0.py\"\n else:\n dev_file = \"dev-v1.1.json\"\n eval_file = \"evaluate-v1.1.py\"\n\n command_str = (\n f\"{sys.executable} {os.path.join(self._args.data_dir, eval_file)} \"\n f\"{os.path.join(self._args.data_dir, dev_file)} \"\n f\"{output_prediction_file}\"\n )\n\n logging.debug(f\"\\nExecuting: `{command_str}`\\n\")\n\n eval_out = subprocess.check_output(shlex.split(command_str))\n\n # scores: {'exact_match': 87.06717123935667, 'f1': 92.78048326711645}\n scores = json.loads(eval_out.decode(\"UTF-8\").strip())\n\n logging.debug(\"scores:\", scores)\n\n metric_units = \"f1\"\n\n return scores[metric_units], metric_units",
"def _run_offline_evaluation(self):\n assert len(self.workers.local_worker().policy_map) == 1\n\n parallelism = self.evaluation_config.evaluation_num_workers or 1\n offline_eval_results = {\"off_policy_estimator\": {}}\n for evaluator_name, offline_evaluator in self.reward_estimators.items():\n offline_eval_results[\"off_policy_estimator\"][\n evaluator_name\n ] = offline_evaluator.estimate_on_dataset(\n self.evaluation_dataset,\n n_parallelism=parallelism,\n )\n return offline_eval_results",
"def evaluation(self):\n return self._evaluation",
"def evaluate(self, epoch, exploration_paths):\n logger.log(\"Collecting samples for evaluation\")\n paths = self._sample_eval_paths(epoch)\n statistics = OrderedDict()\n\n statistics.update(self._statistics_from_paths(paths, \"Test\"))\n statistics.update(self._get_other_statistics())\n statistics.update(self._statistics_from_paths(exploration_paths,\n \"Exploration\"))\n\n statistics['AverageReturn'] = get_average_returns(paths)\n statistics['Epoch'] = epoch\n\n for key, value in statistics.items():\n logger.record_tabular(key, value)\n\n self.log_diagnostics(paths)",
"def run(self):\n\n # TODO try/catch to ensure proper shutdown even if error encountered\n\n params = self._get_params_for_run()\n result_rows = []\n\n # Check for valid configuration\n if self._test_docs is None and self._k_folds == 0:\n self._logger.error(\"Explicit test set or number of cross-validation folds must be specified.\")\n metrics = Metrics()\n result_row = {**params, **metrics.get_scores_as_dict()}\n result_rows.append(result_row)\n return result_rows\n\n # Continue while there are configured parameter settings to evaluate\n while params is not None:\n\n # Get collection of training and test sets for current run\n data_sets = self._get_training_and_test_sets()\n for set_index, (training_docs, test_docs) in enumerate(data_sets):\n\n # Retrieve an encoder module trained with the specified configuration\n self._encoder = self._get_encoder(params)\n\n set_index += 1 # Only used for user output, so start index at 1\n\n num_sets = len(data_sets)\n if num_sets > 1:\n self._logger.info(\"Training and evaluating fold {} of {}.\".format(set_index, num_sets))\n\n start = time.time()\n self._train_and_evaluate(params, self._encoder, training_docs, test_docs)\n runtime = time.time() - start\n self._logger.info(\n \"Trained and evaluated fold {} of sequence model in {} seconds.\".format(set_index, runtime))\n\n # Combine run parameters with evaluation results and store\n result_row = {**params, **self._evaluator.get_score_as_dict()}\n result_rows.append(result_row)\n\n # Check if model should be saved\n if self._is_model_saving_enabled():\n\n operator = self._evaluator.get_operator()\n current_score = self._evaluator.get_score()\n\n best_model = self._get_best_model()\n if best_model is not None:\n (best_metric, _) = best_model\n if not operator(best_metric, current_score):\n self._set_best_model(current_score, (params, self._encoder, self._sequence_learner))\n else:\n # New model is the best one if no previous existed\n self._set_best_model(current_score, (params, self._encoder, self._sequence_learner))\n\n # Invoke optimizer callback to report on results of this run\n if self._optimizer is not None:\n self._optimizer.process_run_result(params=params,\n score=self._evaluator.get_score_as_dict(),\n encoder=self._encoder,\n sequence_learner=self._sequence_learner)\n\n # Check if there are additional runs to execute\n if self._optimizer is not None:\n params = self._optimizer.get_next_params()\n else:\n params = None\n\n # Store best model, if configured\n if self._is_model_saving_enabled():\n path, name = self._get_model_save_path_and_name()\n try:\n self.save(path, name)\n except Exception:\n self._logger.error(\"Failed to save model, clearing Keras session and trying again.\")\n self._sequence_learner.clear_session()\n self.save(path, name)\n\n # Clear Keras/Tensorflow models # TODO why a second time?\n if self._sequence_learner is not None:\n self._sequence_learner.clear_session()\n\n return pd.DataFrame(result_rows)",
"def launch_evaluations(self):\n self.report('Launching pending evaluations.')\n with self.optimizer() as opt:\n evals = {}\n evaluate_process = load_object(self.inputs.evaluate_process.value)\n for idx, inputs in opt.create_inputs().items():\n self.report('Launching evaluation {}'.format(idx))\n inputs_merged = ChainMap(inputs, self.inputs.get('evaluate', {}))\n if is_process_function(evaluate_process):\n _, node = run_get_node(evaluate_process, **inputs_merged)\n else:\n node = self.submit(evaluate_process, **inputs_merged)\n evals[self.eval_key(idx)] = node\n self.indices_to_retrieve.append(idx)\n return self.to_context(**evals)",
"def evaluate():\n\n queue = Queue()\n\n for i in range(threads):\n thread = TestrunThread(queue=queue, config=config)\n thread.daemon = True\n thread.start()\n\n for proxy in proxy_factory.get_evaluation_targets():\n queue.put((url, proxy))\n\n queue.join()",
"def evaluate(self, x_test, y_test, verbose=0):\n\n if self.model is None:\n raise StandardError('Model is not built. Run build method or load model before fitting')\n\n test_results = self.model.evaluate(x_test,\n y_test,\n batch_size=self.batch_size,\n verbose=verbose)\n self.val_history = test_results\n return test_results",
"def evaluate(self, x_test, y_test, verbose=0):\n\n if self.model is None:\n raise StandardError('Model is not built. Run build method or load model before fitting')\n\n test_results = self.model.evaluate(x_test,\n y_test,\n batch_size=self.batch_size,\n verbose=verbose)\n self.val_history = test_results\n return test_results",
"def evaluate(self, x_test, y_test, verbose=0):\n\n if self.model is None:\n raise StandardError('Model is not built. Run build method or load model before fitting')\n\n test_results = self.model.evaluate(x_test,\n y_test,\n batch_size=self.batch_size,\n verbose=verbose)\n self.val_history = test_results\n return test_results",
"def run(self):\n results = self.fetch()\n return results",
"def evaluate(self):\n predictions = self.model.predict(self.test[0])\n accuracy = accuracy_score(self.test[1], predictions)\n print(\"Accuracy:\", str(accuracy * 100) + \"%\")\n self.plot_results(predictions)",
"def get_grades(self, test=None):\r\n target_url = \"https://elearning.linnbenton.edu\\\r\n/grade/report/overview/index.php?id=2721\"\r\n\r\n if test is not None:\r\n target_url = test\r\n\r\n self.web_driver.get(target_url)\r\n self.write_log(f\"Navigating to {target_url}\")\r\n time.sleep(5)\r\n self.write_log(\"Scraping begun.\")\r\n return self.scrape_grades()",
"def evaluate(self, test_data):\n result = self.model.run(test_data)\n self._save_result(result)",
"def getResults():",
"def results(self):\n if not self._results:\n self.read_results()\n return self._results",
"def runtestsuite(self, testsuite):\n if testsuite.status == TestStatus.READY:\n results = testsuite.run()\n else:\n results = ResultList()\n # Disable \"Expression is assigned to nothing\" warning\n # pylint: disable=W0106\n [handler.flush() for handler in self.logger.handlers]\n results.save(heads={'Build': '', 'Branch': self.args.branch})\n sys.stdout.flush()\n self._cleanup_resourceprovider()\n return results",
"def evaluate(self, model_idx,\n max_eval_batches=None,\n write_results=False,\n write_to_summary=True):\n \n # write_summary needs global_step\n self._step_collections[\"GlobalStep\"] = (\n self._sess.run(self._global_step_tensor))\n\n # evaluate the model\n model_name = \"%s-%d\" % (self._names[model_idx], model_idx)\n counts, scores = self._evaluate(\n data=self._data[model_idx],\n logits=self._logits_collections[model_idx],\n predictions=self._predictions_collections[model_idx],\n evaluation_fn=self._evaluation_fns[model_idx],\n max_eval_batches=max_eval_batches,\n calculate_scores=True,\n write_results=write_results)\n\n # write summary\n if write_to_summary:\n self.write_summary(\n \"TASK-%s/ValScores\" % model_name, scores)\n\n return {\"MAIN\": scores}",
"def evaluation( self ) :\n\n return( self.__evaluation )",
"def evals_result(self):\n if self.evals_result_:\n evals_result = self.evals_result_\n else:\n raise XGBoostError('No results.')\n\n return evals_result",
"def evals_result(self):\n if self.evals_result_:\n evals_result = self.evals_result_\n else:\n raise XGBoostError('No results.')\n\n return evals_result"
] | [
"0.6189125",
"0.60605925",
"0.5989458",
"0.5979745",
"0.59796244",
"0.58734286",
"0.58153635",
"0.57028675",
"0.56970245",
"0.5661497",
"0.5653763",
"0.56245905",
"0.5621561",
"0.56146294",
"0.55964917",
"0.55219525",
"0.550872",
"0.550872",
"0.550872",
"0.5491959",
"0.54866976",
"0.54852897",
"0.548428",
"0.54823345",
"0.54815155",
"0.54693544",
"0.5468541",
"0.5431234",
"0.5427623",
"0.5427623"
] | 0.6304654 | 0 |
List nlu evaluations run for a skill. API which requests recently run nlu evaluations started by a vendor for a skill. Returns the evaluation id and some of the parameters used to start the evaluation. Developers can filter the results using locale and stage. Supports paging of results. | def list_nlu_evaluations_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListNLUEvaluationsResponse_7ef8d08f, BadRequestError_f854b05]
operation_name = "list_nlu_evaluations_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/nluEvaluations'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'locale' in params:
query_params.append(('locale', params['locale']))
if 'stage' in params:
query_params.append(('stage', params['stage']))
if 'annotation_id' in params:
query_params.append(('annotationId', params['annotation_id']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.nlu.evaluations.list_nlu_evaluations_response.ListNLUEvaluationsResponse", status_code=200, message="Evaluations are returned."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal Server Error."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.nlu.evaluations.list_nlu_evaluations_response.ListNLUEvaluationsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_result_for_nlu_evaluations_v1(self, skill_id, evaluation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUEvaluationResultsResponse_5ca1fa54, BadRequestError_f854b05]\n operation_name = \"get_result_for_nlu_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'evaluation_id' is set\n if ('evaluation_id' not in params) or (params['evaluation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluEvaluations/{evaluationId}/results'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'evaluation_id' in params:\n path_params['evaluationId'] = params['evaluation_id']\n\n query_params = [] # type: List\n if 'sort_field' in params:\n query_params.append(('sort.field', params['sort_field']))\n if 'test_case_status' in params:\n query_params.append(('testCaseStatus', params['test_case_status']))\n if 'actual_intent_name' in params:\n query_params.append(('actualIntentName', params['actual_intent_name']))\n if 'expected_intent_name' in params:\n query_params.append(('expectedIntentName', params['expected_intent_name']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_results_response.GetNLUEvaluationResultsResponse\", status_code=200, message=\"Evaluation exists and its status is queryable.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_results_response.GetNLUEvaluationResultsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_nlu_evaluation_v1(self, skill_id, evaluation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, GetNLUEvaluationResponse_2fb5e6ed, BadRequestError_f854b05]\n operation_name = \"get_nlu_evaluation_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'evaluation_id' is set\n if ('evaluation_id' not in params) or (params['evaluation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluEvaluations/{evaluationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'evaluation_id' in params:\n path_params['evaluationId'] = params['evaluation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_response.GetNLUEvaluationResponse\", status_code=200, message=\"Evaluation exists and its status is queryable.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.get_nlu_evaluation_response.GetNLUEvaluationResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_nlu_evaluations_v1(self, evaluate_nlu_request, skill_id, **kwargs):\n # type: (EvaluateNLURequest_7a358f6a, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, EvaluateResponse_640ae5b5, BadRequestError_f854b05]\n operation_name = \"create_nlu_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'evaluate_nlu_request' is set\n if ('evaluate_nlu_request' not in params) or (params['evaluate_nlu_request'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluate_nlu_request` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/nluEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'evaluate_nlu_request' in params:\n body_params = params['evaluate_nlu_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.evaluate_response.EvaluateResponse\", status_code=200, message=\"Evaluation has successfully begun.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.nlu.evaluations.evaluate_response.EvaluateResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def list_runs(self):\n postresult = requests.get(\n f\"{self.proto}://{self.host}/ga4gh/wes/v1/runs\", headers=self.auth\n )\n return wes_reponse(postresult)",
"def get_runs(self, offset: int=0):\n resp = self.ph.conn.request(\n 'GET', self.ph.URLS['project'].format(self.token), dict(api_key=self.ph.api_key, offset=offset))\n data = resp.data.decode('utf-8')\n jdata = json.loads(data)['run_list']\n return [PhRun(self.ph, rundata) for rundata in jdata]",
"def list_runs(arn=None, nextToken=None):\n pass",
"def list_smarthome_capability_evaluations_v1(self, skill_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListSHCapabilityEvaluationsResponse_e6fe49d5, BadRequestError_f854b05]\n operation_name = \"list_smarthome_capability_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'stage' in params:\n query_params.append(('stage', params['stage']))\n if 'start_timestamp_from' in params:\n query_params.append(('startTimestampFrom', params['start_timestamp_from']))\n if 'start_timestamp_to' in params:\n query_params.append(('startTimestampTo', params['start_timestamp_to']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse\", status_code=200, message=\"Successfully retrieved the evaluation infomation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def evaluate():\n log.info('Loading dev data...')\n if args.version_2:\n dev_data = SQuAD('dev', version='2.0')\n else:\n dev_data = SQuAD('dev', version='1.1')\n (_, _), (data_file_name, _) \\\n = dev_data._data_file[dev_data._version][dev_data._segment]\n dev_data_path = os.path.join(dev_data._root, data_file_name)\n\n if args.debug:\n sampled_data = [dev_data[0], dev_data[1], dev_data[2]]\n dev_data = mx.gluon.data.SimpleDataset(sampled_data)\n log.info('Number of records in dev data: %d', len(dev_data))\n\n dev_data_features = preprocess_dataset(\n tokenizer, dev_data, vocab=vocab, max_seq_length=args.max_seq_length,\n doc_stride=args.doc_stride, num_workers=args.num_workers,\n max_query_length=args.max_query_length, load_from_pickle=args.load_pickle,\n feature_file=args.dev_dataset_file)\n\n dev_data_input = convert_full_features_to_input_features(dev_data_features)\n log.info('The number of examples after preprocessing: %d', len(dev_data_input))\n\n dev_dataloader = mx.gluon.data.DataLoader(dev_data_input, batchify_fn=batchify_fn,\n num_workers=4, batch_size=args.test_batch_size,\n shuffle=False, last_batch='keep')\n\n log.info('start prediction')\n\n all_results = collections.defaultdict(list)\n\n epoch_tic = time.time()\n total_num = 0\n for (batch_id, data) in enumerate(dev_dataloader):\n data_list = list(split_and_load(data, ctx))\n for splited_data in data_list:\n example_ids, inputs, token_types, valid_length, p_mask, _, _, _ = splited_data\n total_num += len(inputs)\n outputs = net_eval(inputs, token_types, valid_length, p_mask=p_mask)\n example_ids = example_ids.asnumpy().tolist()\n for c, example_ids in enumerate(example_ids):\n result = RawResultExtended(start_top_log_probs=outputs[0][c].asnumpy().tolist(),\n start_top_index=outputs[1][c].asnumpy().tolist(),\n end_top_log_probs=outputs[2][c].asnumpy().tolist(),\n end_top_index=outputs[3][c].asnumpy().tolist(),\n cls_logits=outputs[4][c].asnumpy().tolist())\n all_results[example_ids].append(result)\n if batch_id % args.log_interval == 0:\n log.info('Batch: %d/%d', batch_id + 1, len(dev_dataloader))\n\n epoch_toc = time.time()\n log.info('Time cost=%2f s, Thoughput=%.2f samples/s', epoch_toc - epoch_tic,\n total_num / (epoch_toc - epoch_tic))\n\n log.info('Get prediction results...')\n\n all_predictions = collections.OrderedDict()\n all_nbest_json = collections.OrderedDict()\n scores_diff_json = collections.OrderedDict()\n for features in dev_data_features:\n results = all_results[features[0].example_id]\n example_qas_id = features[0].qas_id\n score_diff, best_non_null_entry, nbest_json = predict_extended(\n features=features, results=results, n_best_size=args.n_best_size,\n max_answer_length=args.max_answer_length, start_n_top=args.start_top_n,\n end_n_top=args.end_top_n)\n scores_diff_json[example_qas_id] = score_diff\n all_predictions[example_qas_id] = best_non_null_entry\n all_nbest_json[example_qas_id] = nbest_json\n\n output_prediction_file = os.path.join(args.output_dir, 'predictions.json')\n output_nbest_file = os.path.join(args.output_dir, 'nbest_predictions.json')\n output_null_log_odds_file = os.path.join(args.output_dir, 'null_odds.json')\n\n with open(output_prediction_file, 'w') as writer:\n writer.write(json.dumps(all_predictions, indent=4) + '\\n')\n with open(output_nbest_file, 'w') as writer:\n writer.write(json.dumps(all_nbest_json, indent=4) + '\\n')\n with open(output_null_log_odds_file, 'w') as writer:\n writer.write(json.dumps(scores_diff_json, indent=4) + '\\n')\n\n if os.path.exists(sys.path[0] + '/evaluate-v2.0.py'):\n arguments = [\n dev_data_path, output_prediction_file, '--na-prob-thresh',\n str(args.null_score_diff_threshold)\n ]\n if args.version_2:\n arguments += ['--na-prob-file', output_null_log_odds_file]\n subprocess.call([sys.executable, sys.path[0] + '/evaluate-v2.0.py'] + arguments)\n else:\n log.info('Please download evaluate-v2.0.py to get evaluation results for SQuAD. '\n 'Check index.rst for the detail.')",
"def execution_list(request, version, project, format=None):\n if request.method == 'GET':\n executions = Execution.objects.filter(versionName=version, tckey__startswith=project).order_by('execId')\n serializer = ExecutionSerializer(executions, many=True)\n return Response(serializer.data)",
"async def next(self) -> list[dict[str, Any]]:\n data = await self.controller.request(\"get\", \"program/nextrun\")\n return cast(list[dict[str, Any]], data[\"nextRuns\"])",
"def experiment_runs (ins, exp) :\n return experiment_info.experiment_runs(ins, exp)",
"def evaluate(self):\n\n rew_rl = []\n for ckpt_path in self._config.eval_ckpt_paths:\n self._load_ckpt(ckpt_path, self._config.ckpt_num)\n\n logger.info(\n \"Run %d evaluations for %d environments\",\n self._config.num_eval,\n len(self._envs),\n )\n rollouts, info = self._evaluate(record_video=self._config.record_video)\n\n info_stat = info.get_stat()\n\n rew_rl.append(np.mean(info[\"rew_rl\"]))\n\n logger.info(\"All Eval Rew Values: %s\", rew_rl)\n logger.info(\"Eval Rew RL Average: %f, Std: %f\", np.mean(rew_rl), np.std(rew_rl))\n\n os.makedirs(\"result\", exist_ok=True)\n with h5py.File(\"result/{}.hdf5\".format(self._config.run_name), \"w\") as hf:\n for k, v in info.items():\n hf.create_dataset(k, data=info[k])\n with open(\"result/{}.txt\".format(self._config.run_name), \"w\") as f:\n for k, v in info_stat.items():\n f.write(\"{}\\t{:.03f} $\\\\pm$ {:.03f}\\n\".format(k, v[0], v[1]))",
"def evaluate(self, runs = 5, use_gui = False):\n self.env.render(use_gui)\n\n evaluation_results = {\n \"runs\" : runs,\n \"unfinished_runs\" : 0,\n \"average_delay\" : [],\n \"episode_mean_delays\" : [],\n \"episode_delay_lists\" : []\n }\n\n for i in range(runs):\n\n print('Evaluate {} -- running episode {} / {}'.format(self.connection_label,\n i+1,\n runs))\n all_trans, mean_delay, vehicle_delays = self.ddqn.evaluate(env = self.env,\n policy = \"greedy\")\n\n evaluation_results[\"episode_delay_lists\"].append(vehicle_delays)\n evaluation_results[\"episode_mean_delays\"].append(mean_delay)\n\n if mean_delay != -1:\n evaluation_results[\"average_delay\"].append(mean_delay)\n else:\n evaluation_results[\"unfinished_runs\"] += 1\n\n runs -= evaluation_results[\"unfinished_runs\"]\n\n if runs == 0:\n evaluation_results[\"average_delay\"].append(-1)\n else:\n evaluation_results[\"average_delay\"] = sum(evaluation_results[\"average_delay\"])/runs\n\n # print(self.ddqn.q_network.get_weights())\n\n return evaluation_results",
"def experiment_run_list(request, instrument, ipts):\n \n logger.debug(\"Catalog: %s : instrument = %s, IPTS = %s\"%(inspect.stack()[0][3],instrument,ipts))\n \n \n \n breadcrumbs = Breadcrumbs(\"home\", reverse('catalog'))\n breadcrumbs.append_experiment_list(instrument)\n breadcrumbs.append(ipts.lower())\n \n template_values = {'instrument': instrument,\n 'experiment': ipts,\n 'title': '%s %s' % (instrument.upper(), ipts.upper()),\n 'breadcrumbs': breadcrumbs}\n\n if users_view_util.is_experiment_member(request, instrument, ipts) is False:\n template_values['user_alert'] = [\"You do not have access to this experiment data.\"]\n else:\n runs = get_ipts_runs(instrument.upper(), ipts)\n template_values['run_data'] = runs\n if len(runs) == 0:\n template_values['user_alert'] = ['No runs were found for instrument %s experiment %s' % (instrument, ipts)]\n # Fill in Fermi auth values, login info,\n template_values = remote_view_util.fill_template_values(request, **template_values)\n template_values = catalog_view_util.fill_template_values(request, **template_values)\n template_values = users_view_util.fill_template_values(request, **template_values)\n return render_to_response('catalog/experiment_run_list.html', template_values)",
"def evaluate_model(self, predictions, expected, bypass_data_to_eval):\n\n result = []\n for i, unique_id in enumerate(np.squeeze(expected[\"unique_ids\"])):\n start_logits = predictions['tf_electra_for_question_answering'][i]\n start_top_index = predictions['tf_electra_for_question_answering_1'\n ][i]\n end_logits = predictions['tf_electra_for_question_answering_2'][i]\n end_top_index = predictions['tf_electra_for_question_answering_3'][i\n ]\n cls_logits = predictions['tf_electra_for_question_answering_4'][i]\n\n result.append(\n SquadResult(\n unique_id,\n start_logits.tolist(),\n end_logits.tolist(),\n start_top_index=start_top_index.tolist(),\n end_top_index=end_top_index.tolist(),\n cls_logits=cls_logits.tolist(),\n )\n )\n\n dev_features = bypass_data_to_eval[\"dev_features\"]\n dev_examples = bypass_data_to_eval[\"dev_examples\"]\n\n answers, nbest_answers = get_answers(\n dev_examples, dev_features, result, self._args\n )\n\n output_prediction_file = os.path.join(\n self._args.output_dir, \"predictions.json\"\n )\n output_nbest_file = os.path.join(\n self._args.output_dir, \"nbest_predictions.json\"\n )\n\n with open(output_prediction_file, \"w\") as f:\n f.write(json.dumps(answers, indent=4) + \"\\n\")\n with open(output_nbest_file, \"w\") as f:\n f.write(json.dumps(nbest_answers, indent=4) + \"\\n\")\n\n if self._args.version_2_with_negative:\n dev_file = \"dev-v2.0.json\"\n eval_file = \"evaluate-v2.0.py\"\n else:\n dev_file = \"dev-v1.1.json\"\n eval_file = \"evaluate-v1.1.py\"\n\n command_str = (\n f\"{sys.executable} {os.path.join(self._args.data_dir, eval_file)} \"\n f\"{os.path.join(self._args.data_dir, dev_file)} \"\n f\"{output_prediction_file}\"\n )\n\n logging.debug(f\"\\nExecuting: `{command_str}`\\n\")\n\n eval_out = subprocess.check_output(shlex.split(command_str))\n\n # scores: {'exact_match': 87.06717123935667, 'f1': 92.78048326711645}\n scores = json.loads(eval_out.decode(\"UTF-8\").strip())\n\n logging.debug(\"scores:\", scores)\n\n metric_units = \"f1\"\n\n return scores[metric_units], metric_units",
"def _evaluate(self, record_video=False):\n assert record_video == False\n assert len(self._runners.keys()) == 1\n num_eval = self._config.num_eval\n rollouts = {}\n info_history = Info()\n\n for k, runner in self._runners.items():\n logger.warn(\"Run %d evaluations for %s\", num_eval, k)\n for i in range(num_eval):\n logger.warn(\"Evaluate run %d\", i + 1)\n rollout, info, frames = runner.run_episode(is_train=False)\n\n rollouts[k] = rollout\n logger.info(\n \"rollout: %s\", {k: v for k, v in info.items() if not \"qpos\" in k},\n )\n\n info_history.add(info)\n\n avg_stats = {}\n for k, v in info_history.items():\n if isinstance(v, list) and not isinstance(v[0], wandb.Video):\n avg_stats[k] = np.mean(v)\n\n std_stats = {}\n for k, v in info_history.items():\n if isinstance(v, list) and not isinstance(v[0], wandb.Video):\n std_stats[k] = np.std(v)\n\n logger.info(\n \"Evaluation Average stats: %s\", {k: v for k, v in avg_stats.items()},\n )\n logger.info(\n \"Evaluation Standard Deviation stats: %s\",\n {k: v for k, v in std_stats.items()},\n )\n\n return rollouts, info_history",
"def get_scnlist_usr_analysis(self):\n scns2runusranalysis = list()\n if self.calc_scn_usr_analysis():\n logger.debug(\"Creating Database Engine and Session.\")\n db_engine = sqlalchemy.create_engine(self.db_info_obj.dbConn)\n session_sqlalc = sqlalchemy.orm.sessionmaker(bind=db_engine)\n ses = session_sqlalc()\n\n usr_analysis_keys = self.get_usr_analysis_keys()\n\n query_result = ses.query(EDDSentinel1ASF).filter(EDDSentinel1ASF.Invalid == False,\n EDDSentinel1ASF.ARDProduct == True).order_by(\n EDDSentinel1ASF.Acquisition_Date.asc()).all()\n\n for scn in query_result:\n scn_plgin_db_objs = ses.query(EDDSentinel1ASFPlugins).filter(EDDSentinel1ASFPlugins.Scene_PID == scn.PID).all()\n if (scn_plgin_db_objs is None) or (not scn_plgin_db_objs):\n scns2runusranalysis.append(scn.PID)\n else:\n for plugin_key in usr_analysis_keys:\n plugin_completed = False\n for plgin_db_obj in scn_plgin_db_objs:\n if (plgin_db_obj.PlugInName == plugin_key) and plgin_db_obj.Completed:\n plugin_completed = True\n break\n if not plugin_completed:\n scns2runusranalysis.append(scn.PID)\n break\n ses.close()\n logger.debug(\"Closed the database session.\")\n return scns2runusranalysis",
"def launch_evaluations(self):\n self.report('Launching pending evaluations.')\n with self.optimizer() as opt:\n evals = {}\n evaluate_process = load_object(self.inputs.evaluate_process.value)\n for idx, inputs in opt.create_inputs().items():\n self.report('Launching evaluation {}'.format(idx))\n inputs_merged = ChainMap(inputs, self.inputs.get('evaluate', {}))\n if is_process_function(evaluate_process):\n _, node = run_get_node(evaluate_process, **inputs_merged)\n else:\n node = self.submit(evaluate_process, **inputs_merged)\n evals[self.eval_key(idx)] = node\n self.indices_to_retrieve.append(idx)\n return self.to_context(**evals)",
"def list_of_runnums (ins, exp) :\n try : expruns = experiment_info.experiment_runs(ins, exp)\n #if exp == 'xcs83814' : return []\n except : return []\n\n return [int(rec['num']) for rec in expruns]\n #runs = experiment_info.experiment_runs(ins, exp)\n #lst = []\n #for rec in runs :\n # lst.append( int(rec['num']) )\n #return lst",
"def executions(self) -> PredictorEvaluationExecutionCollection:\n if getattr(self, 'project_id', None) is None:\n raise AttributeError('Cannot initialize execution without project reference!')\n return PredictorEvaluationExecutionCollection(\n project_id=self.project_id, session=self._session, workflow_id=self.uid)",
"def evaluate(self, runs=100):\n score_record = []\n \n print('Evaluation in progress...')\n for i in range(runs):\n score = self.run_evaluation_episode()\n score_record.append(score)\n \n ave_score = np.mean(score_record)\n \n print('System evaluated with an average score of {} in {} runs'.format(ave_score, runs))",
"def GetEvaluations(self, request, context):\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')",
"def find_runs(model, version, experiment, page_index=0):\n\n # We use filter queries instead of regular boolean queries.\n # This is done so that the sort order isn't influenced.\n # We may need to add additional sorting to make a sensible resultset.\n search_query = {\n 'query': {\n 'bool': {\n 'filter': [\n {'term': {'model': model}},\n {'term': {'version': version}},\n {'term': {'experiment': experiment}}\n ]\n }\n }\n }\n\n results = find_items('run', search_query, page_index)\n\n records = []\n total_items = results['hits']['total']\n\n # Elastic search always returns results, even when you request a non-existing page.\n # To prevent weird behavior in our api, we check for this and return empty results\n # when you requested an empty page.\n if total_items < page_index * PAGE_SIZE:\n return PagedResultSet(page_index, PAGE_SIZE, total_items, [])\n\n for item in results['hits']['hits']:\n records.append({\n 'id': item['_id'],\n 'model': item['_source']['model'],\n 'version': item['_source']['version'],\n 'experiment': item['_source']['experiment'],\n 'date_created': item['_source']['date_created']\n })\n\n return PagedResultSet(page_index, PAGE_SIZE, total_items, records)",
"def get_run_log():\r\n params=request.values\r\n result = ExecRunLog.query.filter(ExecRunLog.exec_id==params['exec_id']).all()\r\n return json_response(result=result)",
"def get_run_detail():\r\n params=request.values\r\n result=ExecRunDetail.query.filter(ExecRunDetail.run_id==params['run_id']).all()\r\n return json_response(result=result)",
"def simulation_run_list(request, simulation):\n runs = get_query('run', simulation).order_by('-id')\n context = {\n 'simulation': simulation,\n 'runs': runs,\n }\n return render(request, 'metro_app/simulation_run_list.html', context)",
"def evaluate(\n config,\n _,\n pstate,\n eval_ds,\n rng,\n unused_num_eval_steps = -1,\n):\n logging.info(\"Starting evaluation.\")\n eval_metrics = None\n state = flax_utils.unreplicate(pstate)\n\n render_loop = instant_ngp_utils.make_render_loop(state.params, config)\n with utils.StepTraceContextHelper(\"eval\", 0) as trace_context:\n for step, batch in enumerate(eval_ds): # pytype: disable=wrong-arg-types\n data = jax.tree_map(jnp.asarray, batch)\n render_poses = data[\"c2w\"]\n hwf = data[\"hwf\"]\n rng = jax.random.fold_in(rng, step)\n\n frames = []\n for pose in render_poses:\n frames.append(\n render_loop(instant_ngp_utils.camera_ray_batch(pose, hwf), rng)[0]\n )\n psnrs_test = [\n -10 * jnp.log10(jnp.mean(jnp.square(rgb - gt)))\n for (rgb, gt) in zip(frames, data[\"images\"])\n ]\n psnr_test = np.array(psnrs_test).mean()\n eval_metrics = EvalMetrics.single_from_model_output(psnr=psnr_test)\n trace_context.next_step()\n eval_info = {\n \"out\": jnp.concatenate([x[None, Ellipsis] for x in frames], axis=0),\n \"gtr\": data[\"images\"],\n }\n return eval_metrics, eval_info",
"def getExecutions(self, prod):\n\n\t\tif self.ccprivate is not None:\n\t\t\treturn\n\t\telif self.bfprivate is not None:\n\t\t\tprod = prod.upper()\n\t\t\tret = self.bfprivate.getexecutions(product_code=prod, count=500, before=0, after=0)\n\t\t\tif len(ret) == 0:\n\t\t\t\tself.logger.debug(\"getExecutions: no execution\")\n\t\t\t\treturn\n\t\t\telif len(ret) == 3:\n\t\t\t\tif ret['status'] != 200:\n\t\t\t\t\tself.logger.error(\"%s '%s'\" % (ret['error_message'], prod))\n\t\t\t\t\treturn\n\t\t\t\telse:\n\t\t\t\t\treturn ret\n\t\t\telse:\n\t\t\t\t# self.logger.debug(\"getExecutions: prod=%s, ret=%s\" % (prod, str(ret)))\n\t\t\t\treturn ret\n\t\telse:\n\t\t\treturn",
"def list_query_executions(NextToken=None, MaxResults=None):\n pass",
"def Run(self, sess=None, threadpool=None):\n del threadpool # Unused.\n with py_utils.Timer() as train_timer:\n for _ in range(self.params.train_executions_per_eval):\n if ret := self.train_program.Run(sess):\n break\n eval_time_in_secs = 0\n return ret, train_timer.duration, eval_time_in_secs"
] | [
"0.6756873",
"0.6303966",
"0.6184463",
"0.5407466",
"0.5142522",
"0.51336783",
"0.50861156",
"0.50807756",
"0.50581384",
"0.5005725",
"0.49959406",
"0.49848005",
"0.49680027",
"0.4956628",
"0.4820104",
"0.48136994",
"0.48029506",
"0.48006204",
"0.47629678",
"0.47599083",
"0.4739225",
"0.47252634",
"0.47202",
"0.463605",
"0.46349818",
"0.46202156",
"0.4605596",
"0.45994097",
"0.45937246",
"0.4582475"
] | 0.69685805 | 0 |
Submit a target skill version to rollback to. Only one rollback or publish operation can be outstanding for a given skillId. | def rollback_skill_v1(self, skill_id, create_rollback_request, **kwargs):
# type: (str, CreateRollbackRequest_e7747a32, **Any) -> Union[ApiResponse, object, CreateRollbackResponse_5a2e8250, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "rollback_skill_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'create_rollback_request' is set
if ('create_rollback_request' not in params) or (params['create_rollback_request'] is None):
raise ValueError(
"Missing the required parameter `create_rollback_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/rollbacks'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'create_rollback_request' in params:
body_params = params['create_rollback_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.create_rollback_response.CreateRollbackResponse", status_code=201, message="Rollback request created; Returns the generated identifier to track the rollback request and returns a URL to track the status in Location header."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=409, message="The request could not be completed due to a conflict with the current state of the target resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.create_rollback_response.CreateRollbackResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def rollback(self, target_revision_id):\n url = DeckhandClient.get_path(\n DeckhandPaths.ROLLBACK\n ).format(target_revision_id)\n\n response = self._post_request(url)\n self._handle_bad_response(response)",
"def rollback_workflow(self, execution_id):\n raise NotImplementedError",
"def rollback(self, rollback_to):\n raise NotImplementedError",
"def rollback(commit_id):\n _confirm_branch()\n \n require('settings', provided_by=[production, staging])\n require('branch', provided_by=[stable, master, branch])\n \n maintenance_up()\n checkout_latest()\n git_reset(commit_id)\n gzip_assets()\n deploy_to_s3()\n maintenance_down()",
"def get_rollback_for_skill_v1(self, skill_id, rollback_request_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, RollbackRequestStatus_71665366]\n operation_name = \"get_rollback_for_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'rollback_request_id' is set\n if ('rollback_request_id' not in params) or (params['rollback_request_id'] is None):\n raise ValueError(\n \"Missing the required parameter `rollback_request_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/rollbacks/{rollbackRequestId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'rollback_request_id' in params:\n path_params['rollbackRequestId'] = params['rollback_request_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.rollback_request_status.RollbackRequestStatus\", status_code=200, message=\"Returns the rollback status for a given skillId and rollbackRequestId. Returns the latest rollback status if ~latest is used in place of rollbackRequestId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.rollback_request_status.RollbackRequestStatus\")\n\n if full_response:\n return api_response\n return api_response.body",
"def SetRollback(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def rollback_action(args, kwargs, was_interrupted, result=None):\n raise NotImplementedError()",
"def rollback(self):\n raise NotImplementedError",
"def rollback(self):\n pass",
"def savepoint_rollback(self, id):\n self.execute(\"ROLLBACK TO SAVEPOINT {}\".format(id))",
"def rollback(self):\n self._rollback = True",
"def service_rollback(name, version):\n if click.confirm(format_text('Rolling back a quick solution but it does not mean that selected version is healthy\\n'\n 'this is your responsibility to check desired version manifest to prevent unwanted '\n 'issues!\\ndo you want to proceed to rollback?',\n TextStyle.WARNING)):\n response = request_service_rollback(name, version)\n present_service_detail(response)\n\n while True:\n details = get_details(name)\n\n if not details:\n sys.exit(302)\n\n click.clear()\n\n if details.get('state') == 'RUNNING':\n present_service_detail(details)\n message = \"\\nCongratulation, Your service is running ^_^\\n\\n\"\n if str(response['service_type']).lower() == 'external':\n message += \"Your service is accessible using the following URLs:\\n{}\".format(\n \"\\n\".join([\" - {}\".format(url)\n for url in response['urls']])\n )\n message += '\\n'\n click.echo(message)\n else:\n message += \"\"\"\n Since your service is internal, it's not accessible from outside your fandogh private network, \n but other services inside your private network will be able to find it using it's name: '{}'\n \"\"\".strip().format(\n response['name']\n )\n message += '\\n'\n click.secho(message, bold=True, fg='yellow')\n sys.exit(0)\n elif details.get('state') == 'UNSTABLE':\n present_service_detail(details)\n click.echo(\n 'You can press ctrl + C to exit details service state monitoring')\n sleep(3)\n else:\n sys.exit(303)",
"def rollback_transaction(self, event=None):\n assert self._current_transaction\n\n # Store stacks\n undo_stack = list(self._undo_stack)\n\n erroneous_tx = self._current_transaction\n self._current_transaction = None\n try:\n with Transaction(self.event_manager):\n try:\n erroneous_tx.execute()\n except Exception as e:\n logger.error(\"Could not roolback transaction\")\n logger.error(e)\n finally:\n # Discard all data collected in the rollback \"transaction\"\n self._undo_stack = undo_stack\n\n self._action_executed()",
"def rollback(self) -> None:\n with self.lock:\n self.wait(self._rollback_gen())",
"def rollback(self, stage, enodes, exception):",
"def cancel_without_rollback(self, stack_id):\n body = {'cancel_without_rollback': None}\n self.client.post('/stacks/%s/actions' % stack_id, data=body)",
"def Rollback(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def rollback(self):\n raise TransactionRollback('rollback called outside of transaction')",
"def cancel_execution_with_rollback(self, execution_id: str):\n execution_url = self.get_execution_url(execution_id)\n try:\n self.logger.info(\"Canceling SSM execution: {}\".format(execution_url))\n self.ssm_client.stop_automation_execution(AutomationExecutionId=execution_id, Type='Cancel')\n self.wait_for_execution_completion(execution_id)\n rollback_execution_id = self.get_step_output(execution_id, constants.rollback_step_name,\n constants.rollback_execution_id_output_name)\n if rollback_execution_id:\n rollback_execution_url = self.get_execution_url(rollback_execution_id)\n self.logger.info(f\"Waiting [RollbackExecution] completed SSM execution: {rollback_execution_url}\")\n self.wait_for_execution_completion(rollback_execution_id)\n except ClientError as e:\n self.logger.error(\"Failed to cancel SSM execution [%s] due to: %s\", execution_url, e.response)\n raise e",
"def rollback(self):\n try:\n if self._cur_batch:\n self._cur_batch.rollback()\n except ValueError:\n # ignore \"Batch must be in progress to rollback\" error\n pass\n self._cur_batch = None\n self._num_mutations = 0",
"def rollback(self):\n self._connection.execute_nonquery(\"sql\", \"ROLLBACK\", True)",
"def SetRollback(self, request, timeout, metadata=None, with_call=False, protocol_options=None):\n raise NotImplementedError()",
"def _do_rollback(self):\n self.backend.rollback()",
"def _Dynamic_Rollback(self, transaction, transaction_response,\n request_id=None):\n transaction.set_app(self.project_id)\n\n try:\n del self.__tx_actions[transaction.handle()]\n except KeyError:\n pass\n\n self._RemoteSend(transaction, transaction_response, \"Rollback\", request_id)\n \n return transaction_response",
"def rollback(self):\n # PEP 249\n raise impala.error.NotSupportedError()",
"def rollback(self, exc):\n USER.info('%s: Rolling Back Failed Build', self.recipe.name)\n cascade = False\n if isinstance(exc, AssertionError):\n logging.error('Error during verify() of %s', self.recipe.name)\n cascade = True\n if cascade or isinstance(exc, PakitLinkError):\n if not cascade:\n logging.error('Error during linking of %s', self.recipe.name)\n walk_and_unlink(self.recipe.install_dir, self.recipe.link_dir)\n cascade = True\n if cascade or (not isinstance(exc, PakitLinkError) and\n not isinstance(exc, AssertionError)):\n if not cascade:\n logging.error('Error during build() of %s', self.recipe.name)\n try:\n Command('rm -rf ' + self.recipe.install_dir).wait()\n except PakitCmdError: # pragma: no cover\n pass",
"def Rollback(self, request, global_params=None):\n config = self.GetMethodConfig('Rollback')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def Rollback(self, request, global_params=None):\n config = self.GetMethodConfig('Rollback')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def rollback(self):\r\n self.db.rollback()",
"def rollback(self):\n self.db.rollback()"
] | [
"0.7157276",
"0.65649027",
"0.6443033",
"0.6164854",
"0.61058706",
"0.60597956",
"0.60287595",
"0.5946078",
"0.5806377",
"0.5673372",
"0.56334734",
"0.56002426",
"0.5596955",
"0.5592444",
"0.5548116",
"0.5537198",
"0.5529087",
"0.5519438",
"0.54865223",
"0.54377615",
"0.54224867",
"0.541689",
"0.5398987",
"0.5386029",
"0.53813106",
"0.5371491",
"0.5363105",
"0.5363105",
"0.5311427",
"0.5280988"
] | 0.6575445 | 1 |
Get the rollback status of a skill given an associated rollbackRequestId. Use ~latest in place of rollbackRequestId to get the latest rollback status. | def get_rollback_for_skill_v1(self, skill_id, rollback_request_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05, RollbackRequestStatus_71665366]
operation_name = "get_rollback_for_skill_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'rollback_request_id' is set
if ('rollback_request_id' not in params) or (params['rollback_request_id'] is None):
raise ValueError(
"Missing the required parameter `rollback_request_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/rollbacks/{rollbackRequestId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'rollback_request_id' in params:
path_params['rollbackRequestId'] = params['rollback_request_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.rollback_request_status.RollbackRequestStatus", status_code=200, message="Returns the rollback status for a given skillId and rollbackRequestId. Returns the latest rollback status if ~latest is used in place of rollbackRequestId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="The operation being requested is not allowed."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.rollback_request_status.RollbackRequestStatus")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def rollback_skill_v1(self, skill_id, create_rollback_request, **kwargs):\n # type: (str, CreateRollbackRequest_e7747a32, **Any) -> Union[ApiResponse, object, CreateRollbackResponse_5a2e8250, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"rollback_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'create_rollback_request' is set\n if ('create_rollback_request' not in params) or (params['create_rollback_request'] is None):\n raise ValueError(\n \"Missing the required parameter `create_rollback_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/rollbacks'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'create_rollback_request' in params:\n body_params = params['create_rollback_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.create_rollback_response.CreateRollbackResponse\", status_code=201, message=\"Rollback request created; Returns the generated identifier to track the rollback request and returns a URL to track the status in Location header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.create_rollback_response.CreateRollbackResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_skill_status_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, SkillStatus_4fdd647b, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_skill_status_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/status'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'resource' in params:\n query_params.append(('resource', params['resource']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.skill_status.SkillStatus\", status_code=200, message=\"Returns status for skill resource and sub-resources.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.skill_status.SkillStatus\")\n\n if full_response:\n return api_response\n return api_response.body",
"def fusion_api_get_restore_status(self, param='', uri=None, api=None, headers=None):\n return self.restore.get(uri=uri, api=api, headers=headers, param=param)",
"def rollback(self):\n return self.connection.rollback",
"def get_status(self, scenario_id):\n table = self.get_execute_table()\n try:\n return table.loc[int(scenario_id), \"status\"]\n except KeyError:\n raise Exception(f\"Scenario not found in execute list, id = {scenario_id}\")",
"def get_stack_status(self, stack):\n stack_description = self.cfn.describe_stacks(StackName=stack)\n return stack_description['Stacks'][0]['StackStatus']",
"def Rollback(self, request, global_params=None):\n config = self.GetMethodConfig('Rollback')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def Rollback(self, request, global_params=None):\n config = self.GetMethodConfig('Rollback')\n return self._RunMethod(\n config, request, global_params=global_params)",
"def _get_stack_status(stack_name: str, region: str, profile: str = None) -> Optional[str]:\n logger.debug(f\"Getting stack status for {stack_name} in {region}\")\n cfn_client = _get_cfn_client(region=region, profile=profile)\n try:\n result = cfn_client.describe_stacks(StackName=stack_name)\n except ClientError as e:\n if 'does not exist' in e.__str__():\n logger.debug(f\"Stack {stack_name} has no status. Is it deployed?\")\n return None\n else:\n raise e\n return result['Stacks'][0]['StackStatus']",
"def rollback(self):\n return self.connection.rollback()",
"def SetRollback(self, request, context):\n context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)",
"def _reverted_task_status(task_audit, revert_before):\n task = Task.objects.get(id=task_audit['task']['id'])\n\n flattened_iterations = [\n iteration_audit\n for assignment_audit in task_audit['assignments']\n for iteration_audit in assignment_audit['iterations']]\n changed_items = _parse_changed_items(flattened_iterations, 'iteration')\n\n latest_iterations = (\n get_iteration_history(task, reverse=True)\n .exclude(id__in=changed_items[RevertChange.DELETED.value]))\n\n num_iterations = latest_iterations.count()\n if num_iterations == 0:\n return Task.Status.AWAITING_PROCESSING\n elif revert_before:\n # Reverting before the first iteration in an assignment means the task\n # is pending review, since at least one iteration exists\n return Task.Status.PENDING_REVIEW\n else:\n # Revert to a processing iteration state\n if num_iterations == 1:\n return Task.Status.PROCESSING\n else:\n previous_status = latest_iterations[1].status\n if previous_status == Iteration.Status.REQUESTED_REVIEW:\n return Task.Status.REVIEWING\n else:\n return Task.Status.POST_REVIEW_PROCESSING",
"def get_status_by_id(cls, request, id):\n return request.dbsession.query(cls).get(id).status",
"def get_role_request_status(self, user_id):\n try:\n status = self.db_handler.get_role_request_status(user_id)\n\n self.logger.write_to_log('got role request status', user_id)\n return status\n except Exception as err:\n method_name = sys._getframe().f_code.co_name\n\n self.logger.write_to_log('exception', 'model')\n self.logger.write_to_err_log(f'exception in method {method_name} - {err}', 'model')",
"def rollback(self, target_revision_id):\n url = DeckhandClient.get_path(\n DeckhandPaths.ROLLBACK\n ).format(target_revision_id)\n\n response = self._post_request(url)\n self._handle_bad_response(response)",
"def rollback(self, project_id, transaction):\n request_pb = _datastore_pb2.RollbackRequest(\n project_id=project_id, transaction=transaction\n )\n # Response is empty (i.e. no fields) but we return it anyway.\n return _rpc(\n self.client._http,\n project_id,\n \"rollback\",\n self.client._base_url,\n self.client._client_info,\n request_pb,\n _datastore_pb2.RollbackResponse,\n )",
"def rollback(self):\n if self._transaction is None:\n raise TransactionNotStartedError(\"Cannot call rollback without a transaction\")\n else:\n def _resetTxn(result):\n self._transaction = None\n d = self._config.rollback(self._transaction)\n d.addCallback(_resetTxn)\n return d",
"def cancel_execution_with_rollback(self, execution_id: str):\n execution_url = self.get_execution_url(execution_id)\n try:\n self.logger.info(\"Canceling SSM execution: {}\".format(execution_url))\n self.ssm_client.stop_automation_execution(AutomationExecutionId=execution_id, Type='Cancel')\n self.wait_for_execution_completion(execution_id)\n rollback_execution_id = self.get_step_output(execution_id, constants.rollback_step_name,\n constants.rollback_execution_id_output_name)\n if rollback_execution_id:\n rollback_execution_url = self.get_execution_url(rollback_execution_id)\n self.logger.info(f\"Waiting [RollbackExecution] completed SSM execution: {rollback_execution_url}\")\n self.wait_for_execution_completion(rollback_execution_id)\n except ClientError as e:\n self.logger.error(\"Failed to cancel SSM execution [%s] due to: %s\", execution_url, e.response)\n raise e",
"def get_transaction_status(self, transaction_id):\n param_dict = {\n \"vid\": self.vendor_id,\n \"reference\": transaction_id,\n }\n # return with hashed key as required by the documentation\n parameters = {\n 'hash': get_hash(parse_data(param_dict), self.security_key),\n **param_dict\n }\n response = send_request(\n data=parameters,\n url=f\"{B2C_ENDPOINT}transaction/status\"\n )\n return response",
"def rollback_transaction(self, event=None):\n assert self._current_transaction\n\n # Store stacks\n undo_stack = list(self._undo_stack)\n\n erroneous_tx = self._current_transaction\n self._current_transaction = None\n try:\n with Transaction(self.event_manager):\n try:\n erroneous_tx.execute()\n except Exception as e:\n logger.error(\"Could not roolback transaction\")\n logger.error(e)\n finally:\n # Discard all data collected in the rollback \"transaction\"\n self._undo_stack = undo_stack\n\n self._action_executed()",
"def init_for_rollback(self, _req):\n\n # Tempoary state and will depends on prior state\n self.state = \"rollback\"\n\n if \"stack_id\" in _req.keys():\n if _req[\"stack_id\"] is not None:\n stack_id = _req[\"stack_id\"].strip()\n\n stack_id_elements = stack_id.split('/', 1)\n if len(stack_id_elements) > 1:\n self.app_id = stack_id_elements[1]\n else:\n self.app_id = stack_id\n\n self.logger.debug(\"stack_id = \" + self.app_id)\n else:\n # If the stack fails, stack_id can be null.\n self.app_id = \"none\"\n\n self.logger.debug(\"stack_id = None\")\n else:\n self.status = \"no stack_id in request\"\n return\n\n if \"suppress_rollback\" in _req.keys():\n self.suppress_rollback = _req[\"suppress_rollback\"]\n\n if \"error_message\" in _req.keys():\n # TODO(Gueyoung): analyze the error message.\n\n if _req[\"error_message\"] is None:\n self.logger.warning(\"error message from platform: none\")\n else:\n self.logger.warning(\"error message from platform:\" + _req[\"error_message\"])",
"def getOrderStatus(self):\n return self.__orderhistory[0]",
"def get_workflow_status(github_token: str, workflow_id: str) -> Tuple[str, str, str]:\n\n # get the workflow run status\n workflow_url = GET_WORKFLOW_URL.format(workflow_id)\n res = requests.get(workflow_url,\n headers={'Authorization': f'Bearer {github_token}'},\n verify=False)\n if res.status_code != 200:\n logging.critical(\n f'Failed to gets private repo workflow, request to {workflow_url} failed with error: {str(res.content)}')\n sys.exit(1)\n\n # parse response\n try:\n workflow = json.loads(res.content)\n except ValueError:\n logging.exception('Enable to parse private repo workflows response')\n sys.exit(1)\n\n # get the workflow job from the response to know what step is in progress now\n jobs = workflow.get('jobs', [])\n\n if not jobs:\n logging.critical(f'Failed to gets private repo workflow jobs, build url: {WORKFLOW_HTML_URL}/{workflow_id}')\n sys.exit(1)\n\n curr_job = jobs[0]\n job_status = curr_job.get('status')\n job_conclusion = curr_job.get('conclusion')\n\n if job_status == 'completed':\n return 'completed', job_conclusion, ''\n\n # check for failure steps\n failure_steps = [step for step in jobs[0].get('steps') if step.get('conclusion') == 'failure']\n if failure_steps:\n return 'completed', 'failure', failure_steps[0].get('name')\n\n # if the job is still in progress - get the current step\n curr_step = next((step for step in jobs[0].get('steps') if step.get('status') == 'in_progress'), None)\n if not curr_step:\n logging.info('All the steps completed waiting for job to get updated, and finish')\n return job_status, job_conclusion, 'unknown'\n return job_status, job_conclusion, curr_step.get('name')",
"def get_rollout(\n self,\n ) -> Callable[[cloud_deploy.GetRolloutRequest], cloud_deploy.Rollout]:\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_rollout\" not in self._stubs:\n self._stubs[\"get_rollout\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.deploy.v1.CloudDeploy/GetRollout\",\n request_serializer=cloud_deploy.GetRolloutRequest.serialize,\n response_deserializer=cloud_deploy.Rollout.deserialize,\n )\n return self._stubs[\"get_rollout\"]",
"def cancel_without_rollback(self, stack_id):\n body = {'cancel_without_rollback': None}\n self.client.post('/stacks/%s/actions' % stack_id, data=body)",
"def get_razorpay_transaction_status(transaction_id):\n global RazorPayClient\n return RazorPayClient.order.fetch(transaction_id)['status']",
"def get_import_status_v1(self, import_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, ImportResponse_364fa39f]\n operation_name = \"get_import_status_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'import_id' is set\n if ('import_id' not in params) or (params['import_id'] is None):\n raise ValueError(\n \"Missing the required parameter `import_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/imports/{importId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'import_id' in params:\n path_params['importId'] = params['import_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.import_response.ImportResponse\", status_code=200, message=\"OK.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.import_response.ImportResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def rollback(self, rollback_to):\n raise NotImplementedError",
"def get_status(self):\n data = self.client._perform_json(\n \"GET\", \"/projects/%s/recipes/%s/status\" % (self.project_key, self.recipe_name))\n return DSSRecipeStatus(self.client, data)",
"def get_previous_ti_statuses(self, context: dict) -> enum.Enum:\n dagrun = context['ti'].get_dagrun()\n failed_ti = dagrun.get_task_instances(state='failed')\n success_ti = dagrun.get_task_instances(state='success')\n if not failed_ti and not success_ti: # There is no prev task so it can't have been failed\n logger.info(\"There are no tasks before this one. So it has status RUNNING\")\n return self.prev_ti_state.NONE\n if failed_ti:\n logger.info(\"There are failed tasks before this one. So it has status FAILED\")\n return self.prev_ti_state.FAILED\n logger.info(\"There are successed tasks before this one. So it has status SUCCESSED\")\n return self.prev_ti_state.SUCCESS"
] | [
"0.6188353",
"0.5348794",
"0.50636834",
"0.49248162",
"0.4864631",
"0.4824027",
"0.4814775",
"0.4814775",
"0.4810125",
"0.47206628",
"0.46720722",
"0.4601886",
"0.4582974",
"0.45225385",
"0.4521484",
"0.45111957",
"0.44771323",
"0.44711003",
"0.44195473",
"0.44100633",
"0.4402711",
"0.43941587",
"0.4393271",
"0.4387696",
"0.43875536",
"0.43720198",
"0.43669772",
"0.43521002",
"0.43461084",
"0.43433982"
] | 0.719928 | 0 |
Simulate executing a skill with the given id. This is an asynchronous API that simulates a skill execution in the Alexa ecosystem given an utterance text of what a customer would say to Alexa. A successful response will contain a header with the location of the simulation resource. In cases where requests to this API results in an error, the response will contain an error code and a description of the problem. The skill being simulated must be in development stage, and it must also belong to and be enabled by the user of this API. Concurrent requests per user is currently not supported. | def simulate_skill_v1(self, skill_id, simulations_api_request, **kwargs):
# type: (str, SimulationsApiRequest_606eed02, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, SimulationsApiResponse_328955bc]
operation_name = "simulate_skill_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'simulations_api_request' is set
if ('simulations_api_request' not in params) or (params['simulations_api_request'] is None):
raise ValueError(
"Missing the required parameter `simulations_api_request` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/simulations'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'simulations_api_request' in params:
body_params = params['simulations_api_request']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.simulations.simulations_api_response.SimulationsApiResponse", status_code=200, message="Skill simulation has successfully began."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad request due to invalid or missing data."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="API user does not have permission to call this API or is currently in a state that does not allow simulation of this skill. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=404, message="The specified skill does not exist."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="This requests conflicts with another one currently being processed. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=429, message="API user has exceeded the permitted request rate."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=500, message="Internal service error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.skill.simulations.simulations_api_response.SimulationsApiResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def simulate_skill_v2(self, skill_id, stage, simulations_api_request, **kwargs):\n # type: (str, str, SimulationsApiRequest_ae2e6503, **Any) -> Union[ApiResponse, object, SimulationsApiResponse_e4ad17d, BadRequestError_765e0ac6, Error_ea6c1a5a]\n operation_name = \"simulate_skill_v2\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'simulations_api_request' is set\n if ('simulations_api_request' not in params) or (params['simulations_api_request'] is None):\n raise ValueError(\n \"Missing the required parameter `simulations_api_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v2/skills/{skillId}/stages/{stage}/simulations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'simulations_api_request' in params:\n body_params = params['simulations_api_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.skill.simulations.simulations_api_response.SimulationsApiResponse\", status_code=200, message=\"Skill simulation has successfully began.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request due to invalid or missing data.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission to call this API or is currently in a state that does not allow simulation of this skill. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=404, message=\"The specified skill does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=409, message=\"This requests conflicts with another one currently being processed. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=429, message=\"API user has exceeded the permitted request rate.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=500, message=\"Internal service error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v2.skill.simulations.simulations_api_response.SimulationsApiResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_skill_simulation_v1(self, skill_id, simulation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, SimulationsApiResponse_328955bc]\n operation_name = \"get_skill_simulation_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'simulation_id' is set\n if ('simulation_id' not in params) or (params['simulation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `simulation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/simulations/{simulationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'simulation_id' in params:\n path_params['simulationId'] = params['simulation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.simulations.simulations_api_response.SimulationsApiResponse\", status_code=200, message=\"Successfully retrieved skill simulation information.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The specified skill or simulation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"API user has exceeded the permitted request rate.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal service error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.simulations.simulations_api_response.SimulationsApiResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def invoke_skill_v1(self, skill_id, invoke_skill_request, **kwargs):\n # type: (str, InvokeSkillRequest_8cf8aff9, **Any) -> Union[ApiResponse, object, InvokeSkillResponse_6f32f451, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"invoke_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'invoke_skill_request' is set\n if ('invoke_skill_request' not in params) or (params['invoke_skill_request'] is None):\n raise ValueError(\n \"Missing the required parameter `invoke_skill_request` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/invocations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'invoke_skill_request' in params:\n body_params = params['invoke_skill_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.invocations.invoke_skill_response.InvokeSkillResponse\", status_code=200, message=\"Skill was invoked.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request due to invalid or missing data.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission to call this API or is currently in a state that does not allow invocation of this skill. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The specified skill does not exist.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"API user has exceeded the permitted request rate.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.invocations.invoke_skill_response.InvokeSkillResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def run(self,identity,params=None, headers=None):\n path = self._sub_url_params('/scenario_simulators/:identity/actions/run', {\n \n 'identity': identity,\n })\n \n if params is not None:\n params = {'data': params}\n response = self._perform_request('POST', path, params, headers,\n retry_failures=False)\n return self._resource_for(response)",
"def delete_skill_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"delete_skill_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message=\"Success. No content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"DELETE\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_dispatch_intent(self):\n @self.skill.intent('test_intent')\n def sample_func():\n \"\"\"Decorated function.\"\"\"\n self.skill.response.sessionAttributes['run'] = True\n self.skill.request.request.type = 'IntentRequest'\n self.skill.request.request.intent = interface.Intent()\n self.skill.request.request.intent.name = 'test_intent'\n self.skill.dispatch()\n self.assertTrue(self.skill.response.sessionAttributes['run'])",
"def simulate_stimulation(self, patt):\n # Defining the response:\n self.identities['resp'] = identity_summary('resp', patt)\n respindex = attribute_index('resp', self)\n # Running the simulation if no response has been computed for this pattern:\n if respindex == None :\n print('Running the simulation. It may take some time.')\n self.resp['coords'], self.resp['glus'], self.resp['AMPAtot'], self.resp['V'] = execute_c_code(self, patt)\n print(\"Simulation completed.\")\n # Retrieving the existing response otherwise:\n else:\n print(\"Response already computed.\")\n self.retrieve_response(respindex)",
"def test_single_skill_request(self):\n self._add_aggregates()\n actions.login(ADMIN_EMAIL)\n get_url = '%s?%s' % (self.URL, urllib.urlencode({\n 'ids': [self.skill_ids[0]]}, True))\n\n response = self.get(get_url)\n self.assertEqual(200, response.status_int)\n payload = transforms.loads(response.body)['payload']\n\n expected_header = ['Date', str(self.skill_ids[0])]\n expected_data = [[self.day1, 1], [self.day2, 2]]\n result = transforms.loads(payload)\n self.assertEqual(expected_header, result['column_headers'])\n self.assertEqual(len(expected_data), len(result['data']))\n for row in expected_data:\n self.assertIn(row, result['data'])",
"def get_skill_simulation_v2(self, skill_id, stage, simulation_id, **kwargs):\n # type: (str, str, str, **Any) -> Union[ApiResponse, object, SimulationsApiResponse_e4ad17d, BadRequestError_765e0ac6, Error_ea6c1a5a]\n operation_name = \"get_skill_simulation_v2\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'simulation_id' is set\n if ('simulation_id' not in params) or (params['simulation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `simulation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v2/skills/{skillId}/stages/{stage}/simulations/{simulationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'stage' in params:\n path_params['stage'] = params['stage']\n if 'simulation_id' in params:\n path_params['simulationId'] = params['simulation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.skill.simulations.simulations_api_response.SimulationsApiResponse\", status_code=200, message=\"Successfully retrieved skill simulation information.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=404, message=\"The specified skill or simulation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=429, message=\"API user has exceeded the permitted request rate.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=500, message=\"Internal service error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v2.error.Error\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v2.skill.simulations.simulations_api_response.SimulationsApiResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_ask_yesno_yes(self):\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'yes'\n\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'yes')",
"def start_beta_test_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05]\n operation_name = \"start_beta_test_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/start'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Accept. Return a URL to track the resource in 'Location' header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceed the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def test_skills(\n self, mock_get_ai_details, mock_get_ai, mock_get_categories\n ):\n\n mock_get_ai.return_value = self.ai\n mock_get_ai_details.return_value = self.ai_details\n\n mock_get_ai_details.return_value['skills'] = [\n {'name': 'bot 1'},\n {'name': 'bot 2'},\n {'name': 'bot 3'},\n {'name': 'bot 4'},\n {'name': 'bot 5'},\n {'name': 'bot 6'},\n ]\n\n response = self.client.get(reverse(\n 'studio:edit_bot',\n kwargs={'aiid': self.ai['aiid']}\n ))\n\n self.assertContains(response, 'bot 1')\n self.assertContains(response, 'bot 2')\n self.assertContains(response, 'bot 3')\n self.assertContains(response, 'bot 4')\n self.assertContains(response, 'bot 5')\n self.assertNotContains(response, 'bot 6')\n self.assertNotContains(response, 'Speed up your bot building process by '\n 'starting with one of our Templates from the store.')",
"def simulate(self, simulator, node, agent_id, print_info=False):\n state = copy.deepcopy(node.state)\n agent_index = agent_id\n if print_info:\n self.print_state(state)\n simulator.current_game_state = state\n simulator.current_agent_index = agent_id\n cumulativeReward = 0.0\n depth = 0\n\n simulation_episode_done = 0\n\n while not simulator.endState(state) and not simulator.gameEnds():\n if print_info:\n print(f\"no.{simulation_episode_done}simulation\")\n if print_info:\n print('\\n' + \">>\" * 50 + '\\n')\n print(f\"agent_id{self.agent_id}\")\n action = self.choose(simulator, state, agent_index)\n if print_info:\n print(action)\n print(f\"excute\")\n (state, reward, agent_index) = simulator.execute(state, action, agent_index)\n if print_info:\n print(f\"agent_index: {agent_index}\")\n simulator.current_agent_index = agent_index\n if print_info:\n self.print_state(state)\n\n if simulator.endState(state):\n if print_info:\n print(\"game over\")\n break\n\n cumulativeReward += pow(0.9, depth) * reward\n depth += 1\n\n game_end = False\n while agent_index != agent_id:\n if print_info:\n print(f\"agent_index{agent_index}\")\n actions = simulator.getLegalActions(state, agent_index)\n selected_action = random.choice(actions)\n if print_info:\n print(f\"selected_action: {selected_action}\")\n try:\n state, _, agent_index = simulator.execute(state, selected_action, agent_index)\n simulator.current_agent_index = agent_index\n if print_info:\n print(\"situation\")\n self.print_state(state)\n print(f\"agent_index: {agent_index}\")\n if simulator.endState(state):\n if print_info:\n print(f\"player{agent_index}:game over\")\n game_end = True\n break\n except:\n game_end = True\n\n if game_end:\n break\n\n simulation_episode_done += 1\n return cumulativeReward",
"def test_dispatch_launch(self):\n @self.skill.launch\n def sample_func():\n \"\"\"Decorated function.\"\"\"\n self.skill.response.sessionAttributes['run'] = True\n self.skill.request.request.type = 'LaunchRequest'\n self.skill.dispatch()\n self.assertTrue(self.skill.response.sessionAttributes['run'])",
"def test_ask_yesno_no(self):\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'nope'\n\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'no')",
"def get_little_skillful_agent(id_skills, str_id=False):\n skills = {id_skill: Agent.MINIMUM_SKILL_VALUE for id_skill in id_skills}\n agent_id = Agent.DEFAULT_ID if not str_id else str(Agent.DEFAULT_ID)\n return Agent(agent_id, skills)",
"def alexa_skill_id(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"alexa_skill_id\")",
"def on_intent(intent_request, session):\n\n print(\"on_intent requestId=\" + intent_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n\n intent = intent_request['intent']\n intent_name = intent_request['intent']['name']\n\n # Dispatch to your skill's intent handlers\n if intent_name == \"<YOUR INTENT NAME HERE>\":\n # Update the wordsmith_data variable with your data. Use key, value\n # pairs where the key is the column name in Wordsmith and the value is\n # the value contained in that column\n wordsmith_data = { 'column1': 'value1', 'column2': 'value2' }\n narrative = wordsmith.generate(WORDSMITH_API_KEY, WORDSMITH_PROJECT_SLUG, WORDSMITH_TEMPLATE_SLUG, wordsmith_data)\n if 'errors' not in narrative:\n return build_response(session.get('attributes', {}), build_speechlet_response('Wordsmith Generated Response', narrative['data']['content'],\n '<REPROMPT TEXT HERE>', True))\n else:\n if not isinstance(narrative['errors'], list) :\n return build_response(session.get('attributes', {}), build_speechlet_response('Wordsmith Generation Error', 'Wordsmith reported the following error: {}'.format(narrative['errors']['detail']),\n '<REPROMPT TEXT HERE>', True))\n else:\n details = ', '.join([e['details'] for e in narrative['errors']])\n return build_response(session.get('attributes', {}), build_speechlet_response('Wordsmith Generation Error', 'Wordsmith reported the following error: {}'.format(details),\n '<REPROMPT TEXT HERE>', True))\n elif intent_name == \"AMAZON.HelpIntent\":\n return get_welcome_response()\n elif intent_name == \"AMAZON.CancelIntent\" or intent_name == \"AMAZON.StopIntent\":\n return handle_session_end_request()\n else:\n raise ValueError(\"Invalid intent\")",
"def test_get_skill_name(self):\n result = self.runner.invoke(\n cli,\n [*CLI_LOG_OPTION, \"config\", \"get\", \"skills.dummy.name\"],\n standalone_mode=False,\n )\n assert result.exit_code == 0\n assert result.output == \"dummy\\n\"",
"async def test_intent(self, dm):\n request = create_request(\"other\", \"intent\")\n result = await dm.apply_handler(request, create_responder(request))\n assert result.dialogue_state == \"intent\"",
"def submit_skill_for_certification_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"submit_skill_for_certification_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/submit'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'submit_skill_for_certification_request' in params:\n body_params = params['submit_skill_for_certification_request']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=None, status_code=202, message=\"Success. There is no content but returns Location in the header.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=None)\n\n if full_response:\n return api_response\n \n return None",
"def simulate(self, query):\n return self.master.simulate(query)",
"def put(self, id):\n data = request.json\n update_scenario(id, data)\n return None, 204",
"def create_smarthome_capability_evaluation_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, EvaluateSHCapabilityResponse_38ae7f22]\n operation_name = \"create_smarthome_capability_evaluation_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'evaluate_sh_capability_payload' in params:\n body_params = params['evaluate_sh_capability_payload']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse\", status_code=200, message=\"Evaluation has successfully begun.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"A test run is already in progress for the specified endpoint. Please retry after some time. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"async def quick_response(self, voice_id: int) -> None:\n await self.api.quick_response(self.product_type, self.serial_no, voice_id)",
"def run_sample(self):\n # there will be validation failures for sample data\n self.validate_req(ignore_failure=True)\n runner_fn = self.model_runner.execute_model_for_sample_data\n return self.do_handle_request(runner_fn)",
"def get_experiment_v1(self, skill_id, experiment_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, GetExperimentResponse_fcd92c35, StandardizedError_f5106a89, BadRequestError_f854b05]\n operation_name = \"get_experiment_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'experiment_id' is set\n if ('experiment_id' not in params) or (params['experiment_id'] is None):\n raise ValueError(\n \"Missing the required parameter `experiment_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/experiments/{experimentId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'experiment_id' in params:\n path_params['experimentId'] = params['experiment_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\", status_code=200, message=\"Returned skill experiment.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"The operation being requested is not allowed.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.experiment.get_experiment_response.GetExperimentResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def delete_skill(id, skill):\n with app.app_context():\n user = User.query.get(id)\n if user is None:\n return \"User not found\", 404\n skill_db = Skill.query.filter_by(name=skill).first()\n if skill_db is None:\n return \"Skill not found\", 404\n user.skills.remove(skill_db)\n user_response = UsersResponse(\n users=[\n {\n \"id\": user.id,\n \"name\": user.name,\n \"skills\": [skill.name for skill in user.skills]\n }\n ]\n )\n db.session.commit()\n return user_response.json(), 200",
"def test_ask_yesno_other(self):\n skill = create_skill()\n skill.get_response = mock.Mock()\n skill.get_response.return_value = 'I am a fish'\n\n response = skill.ask_yesno('Do you like breakfast')\n self.assertEqual(response, 'I am a fish')",
"def skill(ctx: Context, public_id: PublicId):\n _eject_item(ctx, \"skill\", public_id)"
] | [
"0.6684668",
"0.60161704",
"0.57356066",
"0.55610174",
"0.5556969",
"0.54888636",
"0.5188477",
"0.5132964",
"0.51322925",
"0.5122536",
"0.51062113",
"0.5103608",
"0.5095683",
"0.50377196",
"0.50327593",
"0.49875507",
"0.49757802",
"0.49560156",
"0.4947358",
"0.49434194",
"0.49336392",
"0.49317026",
"0.49114823",
"0.48914778",
"0.48776007",
"0.48727536",
"0.48561025",
"0.48485163",
"0.4824108",
"0.4813317"
] | 0.7329467 | 0 |
Get top level information and status of a Smart Home capability evaluation. Get top level information and status of a Smart Home capability evaluation. | def get_smart_home_capability_evaluation_v1(self, skill_id, evaluation_id, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, GetSHCapabilityEvaluationResponse_d484531f]
operation_name = "get_smart_home_capability_evaluation_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'evaluation_id' is set
if ('evaluation_id' not in params) or (params['evaluation_id'] is None):
raise ValueError(
"Missing the required parameter `evaluation_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations/{evaluationId}'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
if 'evaluation_id' in params:
path_params['evaluationId'] = params['evaluation_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_response.GetSHCapabilityEvaluationResponse", status_code=200, message="Successfully retrieved the evaluation status."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="API user does not have permission or is currently in a state that does not allow calls to this API. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=404, message="The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=429, message="Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=0, message="Internal server error. "))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_response.GetSHCapabilityEvaluationResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_get_hyperflex_capability_info_list(self):\n pass",
"async def get_capability_report(self):\n if self.query_reply_data.get(\n PrivateConstants.CAPABILITY_QUERY) is None:\n await self._send_sysex(PrivateConstants.CAPABILITY_QUERY, None)\n while self.query_reply_data.get(\n PrivateConstants.CAPABILITY_RESPONSE) is None:\n await asyncio.sleep(self.sleep_tune)\n return self.query_reply_data.get(PrivateConstants.CAPABILITY_RESPONSE)",
"async def get_capability_report(self):\n if self.query_reply_data.get(\n PrivateConstants.CAPABILITY_QUERY) is None:\n await self._send_sysex(PrivateConstants.CAPABILITY_QUERY, None)\n while self.query_reply_data.get(\n PrivateConstants.CAPABILITY_RESPONSE) is None:\n await asyncio.sleep(self.sleep_tune)\n return self.query_reply_data.get(PrivateConstants.CAPABILITY_RESPONSE)",
"def capability(self):\n code, data, capabilities = (\n self.__send_command(\"CAPABILITY\", withcontent=True))\n if code == \"OK\":\n return capabilities\n return None",
"def test_wmts_get_capabilities(self):\n ref_hash = 'b49538ed143340f11230eac8b8f9ecca'\n req_url = r'http://localhost/reproject/test/wmts/wmts.cgi?Request=GetCapabilities'\n if DEBUG:\n print('\\nTesting WMTS GetCapablities')\n print('URL: ' + req_url)\n response = get_url(req_url)\n\n # Check if the response is valid XML\n try:\n XMLroot = ElementTree.XML(response.read())\n XMLdict = XmlDictConfig(XMLroot)\n xml_check = True\n except:\n xml_check = False\n self.assertTrue(xml_check, 'GetCapabilities response is not a valid XML file. URL: ' + req_url)\n\n refXMLtree = ElementTree.parse(os.path.join(os.getcwd(), 'mod_reproject_test_data/GetCapabilities.1.0.0.xml'))\n refXMLroot = refXMLtree.getroot()\n refXMLdict = XmlDictConfig(refXMLroot)\n\n check_result = check_dicts(XMLdict, refXMLdict)\n #check_result = check_tile_request(req_url, ref_hash)\n self.assertTrue(check_result, 'WTMTS Get GetCapabilities Request does not match what\\'s expected. URL: ' + req_url)",
"def get_smarthome_capablity_evaluation_results_v1(self, skill_id, evaluation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, GetSHCapabilityEvaluationResultsResponse_9a1d4db0]\n operation_name = \"get_smarthome_capablity_evaluation_results_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'evaluation_id' is set\n if ('evaluation_id' not in params) or (params['evaluation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations/{evaluationId}/results'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'evaluation_id' in params:\n path_params['evaluationId'] = params['evaluation_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_results_response.GetSHCapabilityEvaluationResultsResponse\", status_code=200, message=\"Successfully retrieved the evaluation result content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_results_response.GetSHCapabilityEvaluationResultsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_twms_get_capabilities(self):\n ref_hash = '8663c1e1d45e4be1cdaefc8e6749ead4'\n req_url = r'http://localhost/reproject/test/twms/twms.cgi?Request=GetCapabilities'\n if DEBUG:\n print('\\nTesting TWMS GetCapablities')\n print('URL: ' + req_url)\n response = get_url(req_url)\n\n # Check if the response is valid XML\n try:\n XMLroot = ElementTree.XML(response.read())\n XMLdict = XmlDictConfig(XMLroot)\n xml_check = True\n except:\n xml_check = False\n self.assertTrue(xml_check, 'GetCapabilities response is not a valid XML file. URL: ' + req_url)\n\n refXMLtree = ElementTree.parse(os.path.join(os.getcwd(), 'mod_reproject_test_data/GetCapabilities.1.1.1.xml'))\n refXMLroot = refXMLtree.getroot()\n refXMLdict = XmlDictConfig(refXMLroot)\n\n check_result = check_dicts(XMLdict, refXMLdict)\n #check_result = check_tile_request(req_url, ref_hash)\n self.assertTrue(check_result, 'TWMS Get GetCapabilities Request does not match what\\'s expected. URL: ' + req_url)",
"def __get_capability(self):\n requests = self.__get_capability_request()\n exception = self.__get_capability_exception()\n layers = self.__get_capability_layer()\n \n capability = { \"requests\": requests,\n \"exception\" : exception,\n \"layers\" : layers}\n return capability",
"def test_wmts_rest_get_capabilities(self):\n ref_hash = 'b49538ed143340f11230eac8b8f9ecca'\n req_url = r'http://localhost/reproject/test/wmts/1.0.0/WMTSCapabilities.xml'\n if DEBUG:\n print('\\nTesting WMTS (REST) GetCapablities')\n print('URL: ' + req_url)\n response = get_url(req_url)\n\n # Check if the response is valid XML\n try:\n XMLroot = ElementTree.XML(response.read())\n XMLdict = XmlDictConfig(XMLroot)\n xml_check = True\n except:\n xml_check = False\n self.assertTrue(xml_check, 'GetCapabilities response is not a valid XML file. URL: ' + req_url)\n\n refXMLtree = ElementTree.parse(os.path.join(os.getcwd(), 'mod_reproject_test_data/wmts_endpoint/1.0.0/WMTSCapabilities.xml'))\n refXMLroot = refXMLtree.getroot()\n refXMLdict = XmlDictConfig(refXMLroot)\n\n check_result = check_dicts(XMLdict, refXMLdict)\n self.assertTrue(check_result, 'WTMTS (REST) Get Capabilities Request does not match what\\'s expected. URL: ' + req_url)",
"def fusion_api_get_metrics_capability(self, api=None, headers=None):\n return self.metrics.get(api=api, headers=headers, param='/capability')",
"def capabilities(self):\n\n class Capabilities(ct.Structure):\n _fields_ = [(\"Size\", ct.c_ulong),\n (\"AcqModes\", ct.c_ulong),\n (\"ReadModes\", ct.c_ulong),\n (\"FTReadModes\", ct.c_ulong),\n (\"TriggerModes\", ct.c_ulong),\n (\"CameraType\", ct.c_ulong),\n (\"PixelModes\", ct.c_ulong),\n (\"SetFunctions\", ct.c_ulong),\n (\"GetFunctions\", ct.c_ulong),\n (\"Features\", ct.c_ulong),\n (\"PCICard\", ct.c_ulong),\n (\"EMGainCapability\", ct.c_ulong)]\n\n stru = Capabilities()\n stru.Size = ct.sizeof(stru)\n self.lib.GetCapabilities(ct.pointer(stru))\n\n return stru",
"def get_capabilities(self, method='get'):\n self.client.getcapabilities()\n\n self._has_capabilities = True",
"def getcapabilities(self):\n reader = WFSCapabilitiesReader(self.version, auth=self.auth)\n return openURL(\n reader.capabilities_url(self.url), timeout=self.timeout,\n headers=self.headers, auth=self.auth\n )",
"def list_smarthome_capability_evaluations_v1(self, skill_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListSHCapabilityEvaluationsResponse_e6fe49d5, BadRequestError_f854b05]\n operation_name = \"list_smarthome_capability_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'stage' in params:\n query_params.append(('stage', params['stage']))\n if 'start_timestamp_from' in params:\n query_params.append(('startTimestampFrom', params['start_timestamp_from']))\n if 'start_timestamp_to' in params:\n query_params.append(('startTimestampTo', params['start_timestamp_to']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse\", status_code=200, message=\"Successfully retrieved the evaluation infomation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def create_smarthome_capability_evaluation_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, EvaluateSHCapabilityResponse_38ae7f22]\n operation_name = \"create_smarthome_capability_evaluation_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'evaluate_sh_capability_payload' in params:\n body_params = params['evaluate_sh_capability_payload']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse\", status_code=200, message=\"Evaluation has successfully begun.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"A test run is already in progress for the specified endpoint. Please retry after some time. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_get_hyperflex_capability_info_by_moid(self):\n pass",
"def capabilities(self):\n return None",
"def capability(self):\n return self.get(\"capabilityClass\")",
"def capabilities(self):\n pass",
"def get(self):\n xml = self._robot.GetCapabilitiesXml()\n self.response.headers['Content-Type'] = 'text/xml'\n self.response.out.write(xml)",
"def get_capabilities(self):\n\n service = self.__get_service()\n capability = self.__get_capability()\n contents = {\"service\" : service, \"capability\" : capability}\n return contents, self.params['format']",
"def get_capabilities(self, config_section):\n get_opt = self.shishito_support.get_opt\n test_platform = self.shishito_support.test_platform\n if (test_platform == 'web'):\n # Get logging levels from config\n logging_driver = get_opt(config_section, 'logging_driver', default='WARNING').upper()\n logging_browser = get_opt(config_section, 'logging_browser', default='WARNING').upper()\n logging_performance = get_opt(config_section, 'logging_performance', default='WARNING').upper()\n\n capabilities = {\n 'browserName': get_opt(config_section, 'browser').lower(),\n 'version': get_opt(config_section, 'browser_version'),\n 'resolution': get_opt(config_section, 'resolution'),\n 'javascriptEnabled': True,\n 'acceptSslCerts': get_opt('accept_ssl_cert').lower() == 'true',\n 'goog:loggingPrefs': {'driver': logging_driver,\n 'browser': logging_browser,\n 'performance': logging_performance}\n }\n if (test_platform == 'mobile'):\n capabilities = {\n 'browserName': get_opt(config_section, 'browser').lower(),\n 'javascriptEnabled': True,\n 'acceptSslCerts': get_opt('accept_ssl_cert').lower() == 'true',\n }\n\n self.add_cmdline_arguments_to_browser(capabilities, config_section)\n self.add_extensions_to_browser(capabilities, config_section)\n self.add_experimental_option(capabilities, config_section)\n return capabilities",
"def capabilities(self):\n return []",
"def capabilities(self) -> Optional[Sequence[str]]:\n return pulumi.get(self, \"capabilities\")",
"def skill_information():\r\n\r\n client = boto3.client('iot-data', region_name='us-west-2')\r\n\r\n session_attributes = {}\r\n card_title = \"Welcome\"\r\n should_end_session = True\r\n reprompt_text = None\r\n\r\n if(is_online()):\r\n speech_output = \"The coffee machine is offline.\"\r\n else:\r\n client.publish(topic=TOPIC_TURN_ON_OFF, qos=1, payload=json.dumps({\"state\": \"1\"}))\r\n speech_output = \"The coffee machine is on\"\r\n save_on_off_status(1)\r\n\r\n return build_response(session_attributes,\r\n build_speechlet_response(card_title, speech_output, reprompt_text, should_end_session))",
"def do_capabilities(cs, args):\n caps = cs.capabilities.list()\n fields = [\"scheme\", \"location\", \"term\", \"title\"]\n\n schemes = {i[\"scheme\"] for i in caps}\n\n print schemes\n for scheme in schemes:\n aux = [i for i in caps if scheme == i[\"scheme\"]]\n utils.print_list(aux, fields)",
"def capabilities(self):\n return self._dll.JLINKARM_GetEmuCaps()",
"def get_rp_health_summary(isamAppliance, check_mode=False, force=False):\n return isamAppliance.invoke_get(\"Retrieving a summary of Reverse Proxy health\",\n \"/wga/widgets/health.json\",requires_model=requires_model)",
"def detect_supported_caps():\n result = []\n # generate list of supported capabilities\n\n # Intel RDT L3 CAT\n if common.PQOS_API.is_l3_cat_supported():\n result.append(common.CAT_L3_CAP)\n\n # Intel RDT L2 CAT\n if common.PQOS_API.is_l2_cat_supported():\n result.append(common.CAT_L2_CAP)\n\n # Intel RDT MBA\n if common.PQOS_API.is_mba_supported():\n result.append(common.MBA_CAP)\n\n if sstbf.is_sstbf_enabled():\n result.append(common.SSTBF_CAP)\n\n if power.is_sstcp_enabled():\n result.append(common.POWER_CAP)\n\n return result",
"def get_quantization_capability(self):\n return self.cur_config['capabilities']"
] | [
"0.59970254",
"0.58907706",
"0.58907706",
"0.588435",
"0.5783326",
"0.5717561",
"0.5607293",
"0.5583511",
"0.5554896",
"0.5549661",
"0.5512408",
"0.55064833",
"0.5498162",
"0.5478075",
"0.5438951",
"0.5420143",
"0.5403651",
"0.5392647",
"0.53825986",
"0.53586215",
"0.535828",
"0.53178334",
"0.5243183",
"0.52342296",
"0.5217403",
"0.5199343",
"0.518945",
"0.51863337",
"0.51610154",
"0.5132021"
] | 0.6896341 | 0 |
List Smart Home capability evaluation runs for a skill. List Smart Home capability evaluation runs for a skill. | def list_smarthome_capability_evaluations_v1(self, skill_id, stage, **kwargs):
# type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListSHCapabilityEvaluationsResponse_e6fe49d5, BadRequestError_f854b05]
operation_name = "list_smarthome_capability_evaluations_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'stage' is set
if ('stage' not in params) or (params['stage'] is None):
raise ValueError(
"Missing the required parameter `stage` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'stage' in params:
query_params.append(('stage', params['stage']))
if 'start_timestamp_from' in params:
query_params.append(('startTimestampFrom', params['start_timestamp_from']))
if 'start_timestamp_to' in params:
query_params.append(('startTimestampTo', params['start_timestamp_to']))
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse", status_code=200, message="Successfully retrieved the evaluation infomation."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="API user does not have permission or is currently in a state that does not allow calls to this API. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=404, message="The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=429, message="Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=0, message="Internal server error. "))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_smart_home_capability_evaluation_v1(self, skill_id, evaluation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, GetSHCapabilityEvaluationResponse_d484531f]\n operation_name = \"get_smart_home_capability_evaluation_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'evaluation_id' is set\n if ('evaluation_id' not in params) or (params['evaluation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations/{evaluationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'evaluation_id' in params:\n path_params['evaluationId'] = params['evaluation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_response.GetSHCapabilityEvaluationResponse\", status_code=200, message=\"Successfully retrieved the evaluation status.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_response.GetSHCapabilityEvaluationResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_skill_list(self):\n return [\n i.strip() for i in\n self.ansi_escape.sub('', check_output([BIN, 'list'])).split('\\n')\n ]",
"def create_smarthome_capability_evaluation_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, EvaluateSHCapabilityResponse_38ae7f22]\n operation_name = \"create_smarthome_capability_evaluation_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n if 'evaluate_sh_capability_payload' in params:\n body_params = params['evaluate_sh_capability_payload']\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse\", status_code=200, message=\"Evaluation has successfully begun.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"A test run is already in progress for the specified endpoint. Please retry after some time. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"POST\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def get_smarthome_capablity_evaluation_results_v1(self, skill_id, evaluation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, GetSHCapabilityEvaluationResultsResponse_9a1d4db0]\n operation_name = \"get_smarthome_capablity_evaluation_results_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'evaluation_id' is set\n if ('evaluation_id' not in params) or (params['evaluation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations/{evaluationId}/results'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'evaluation_id' in params:\n path_params['evaluationId'] = params['evaluation_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_results_response.GetSHCapabilityEvaluationResultsResponse\", status_code=200, message=\"Successfully retrieved the evaluation result content.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_results_response.GetSHCapabilityEvaluationResultsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"async def capabilities(self, abilities):\n capabilities = []\n for ability in abilities:\n if self.privileged_to_run(ability) and ability.find_executors(self.executors, self.platform):\n capabilities.append(ability)\n return capabilities",
"def do_capabilities(cs, args):\n caps = cs.capabilities.list()\n fields = [\"scheme\", \"location\", \"term\", \"title\"]\n\n schemes = {i[\"scheme\"] for i in caps}\n\n print schemes\n for scheme in schemes:\n aux = [i for i in caps if scheme == i[\"scheme\"]]\n utils.print_list(aux, fields)",
"def list_runtimes(self, workbench):\n pass",
"def list_runs(arn=None, nextToken=None):\n pass",
"def experiment_runs (ins, exp) :\n return experiment_info.experiment_runs(ins, exp)",
"def list_smarthome_capability_test_plans_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListSHCapabilityTestPlansResponse_cb289d6, BadRequestError_f854b05]\n operation_name = \"list_smarthome_capability_test_plans_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityTestPlans'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_test_plans_response.ListSHCapabilityTestPlansResponse\", status_code=200, message=\"Successfully got the list of test plans.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_test_plans_response.ListSHCapabilityTestPlansResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def test_get_hyperflex_capability_info_list(self):\n pass",
"async def listlaunches(self, ctx, *args):\n if not can_answer(ctx):\n return\n num = 5\n for arg in args:\n if arg.isdigit():\n num = int(arg)\n launches = launchlibrary.Launch.fetch(api, status=(1,2))[:num]\n if launches[0].agency != None:\n embedcolor = discord.Colour(await get_color(launches[0].agency.id))\n else:\n embedcolor = discord.Colour(5592405)\n msg = discord.Embed(title=\"Listing next launches: \", colour=embedcolor)\n IDs = []\n for launch in launches:\n launchtime = launch.net\n utc = datetime.now(timezone.utc)\n T = chop_microseconds(launchtime - utc)\n if launch.status == 1:\n value = \"T-: {0}\".format(T)\n else:\n value = \"T-: {0}; {1}\".format(T, launch.get_status().name)\n msg.add_field(name=launch.name, value=value, inline=False)\n IDs.append(launch.id)\n footer = 'IDs: ' + ', '.join(str(x) for x in IDs)\n msg.set_footer(text=footer)\n await ctx.send(embed=msg)",
"def experiment_run_list(request, instrument, ipts):\n \n logger.debug(\"Catalog: %s : instrument = %s, IPTS = %s\"%(inspect.stack()[0][3],instrument,ipts))\n \n \n \n breadcrumbs = Breadcrumbs(\"home\", reverse('catalog'))\n breadcrumbs.append_experiment_list(instrument)\n breadcrumbs.append(ipts.lower())\n \n template_values = {'instrument': instrument,\n 'experiment': ipts,\n 'title': '%s %s' % (instrument.upper(), ipts.upper()),\n 'breadcrumbs': breadcrumbs}\n\n if users_view_util.is_experiment_member(request, instrument, ipts) is False:\n template_values['user_alert'] = [\"You do not have access to this experiment data.\"]\n else:\n runs = get_ipts_runs(instrument.upper(), ipts)\n template_values['run_data'] = runs\n if len(runs) == 0:\n template_values['user_alert'] = ['No runs were found for instrument %s experiment %s' % (instrument, ipts)]\n # Fill in Fermi auth values, login info,\n template_values = remote_view_util.fill_template_values(request, **template_values)\n template_values = catalog_view_util.fill_template_values(request, **template_values)\n template_values = users_view_util.fill_template_values(request, **template_values)\n return render_to_response('catalog/experiment_run_list.html', template_values)",
"def _build_experiment_embedded_list():\n pass",
"def evaluate(self):\n scores = []\n scores.append(self.word_analogy())\n print(\"Word Analogy (acc): \", scores[0])\n scores.append(self.word_similarity())\n print(\"Word Similarity (MSE): \", scores[1])\n scores.append(self.concept_categorization())\n print(\"Concept Categorization (purity): \", scores[2])\n scores.append(self.sentiment_analysis())\n print(\"Sentiment Analysis (acc): \", scores[3])\n return scores",
"def capabilities(self):\n return []",
"def list(args):\n experiments = sorted(os.listdir('./litmus'))\n print_color(\"Available Litmus Chaos Experiments:\\n\\n\")\n if (f\"{args.platform}\" == \"GKE\"):\n i = 1\n for experiment_file in experiments:\n print_color(f\"\\t{i}. {experiment_file.replace('.yaml', '')}\")\n i += 1\n\n if (f\"{args.platform}\" == \"kind\"):\n kind_supported = [\"pod-delete\",\"container-kill\",\"node-cpu-hog\",\"node-memory-hog\"]\n i = 0\n for i in range(0, len(kind_supported)):\n print_color(f\"\\t{i+1}. {kind_supported[i]}\")\n i += 1\n\n if (f\"{args.platform}\" == \"EKS\"):\n i = 1\n for experiment_file in experiments:\n print_color(f\"\\t{i}. {experiment_file.replace('.yaml', '')}\")\n i += 1",
"def list_runs(self):\n postresult = requests.get(\n f\"{self.proto}://{self.host}/ga4gh/wes/v1/runs\", headers=self.auth\n )\n return wes_reponse(postresult)",
"def applicants_skills(driver):\n try:\n raw_skills = driver.find_elements_by_css_selector(\"span.pill\")\n skills = [skill.text for skill in raw_skills] \n return skills\n except Exception as e:\n print(\"error acquiring applicant skills\")\n print(e)\n return []",
"def evaluate_questions(self):\n for question in self.question_list:\n question.evaluate_question()",
"def getcapabilities(self):\n reader = WFSCapabilitiesReader(self.version, auth=self.auth)\n return openURL(\n reader.capabilities_url(self.url), timeout=self.timeout,\n headers=self.headers, auth=self.auth\n )",
"def model_qua_launch(self, dict):\r\n list_result = []\r\n if \"SVR\" in dict:\r\n SVR = dict[\"SVR\"]\r\n if SVR[\"Auto\"]:\r\n result = SVR_b(self.ml_data.feature, self.ml_data.target, SVR[\"Auto\"])\r\n model, score, graph, time = result\r\n result_win = Window_Quant()\r\n result_win.setWindowTitle(\"SVR Result Auto\")\r\n result_win.setData(model, score, graph, time)\r\n list_result.append(result_win)\r\n else:\r\n result = SVR_b(self.ml_data.feature, self.ml_data.target, SVR[\"Auto\"], [SVR[\"C\"],\r\n SVR[\"Kernel\"],\r\n SVR[\"Degree\"]])\r\n model, score, graph, time = result\r\n result_win = Window_Quant()\r\n result_win.setWindowTitle(\"SVR Result\")\r\n result_win.setData(model, score, graph, time)\r\n list_result.append(result_win)\r\n if \"LR\" in dict:\r\n LR = dict[\"LR\"]\r\n if LR[\"Auto\"]:\r\n result = regression_lin(self.ml_data.feature, self.ml_data.target, LR[\"Auto\"])\r\n model, score, graph, time = result\r\n result_win = Window_Quant()\r\n result_win.setWindowTitle(\"Linear Regression Result Auto\")\r\n result_win.setData(model, score, graph, time)\r\n list_result.append(result_win)\r\n else:\r\n result = regression_lin(self.ml_data.feature, self.ml_data.target, LR[\"Auto\"], LR[\"fit_intercept\"], LR[\"normalize\"])\r\n model, score, graph, time = result\r\n result_win = Window_Quant()\r\n result_win.setWindowTitle(\"Linear Regression Result\")\r\n result_win.setData(model, score, graph, time)\r\n list_result.append(result_win)\r\n\r\n if \"RT\" in dict:\r\n RT = dict[\"RT\"]\r\n if RT[\"Auto\"]:\r\n result = RegTree(self.ml_data.feature, self.ml_data.target, RT[\"Auto\"])\r\n model, score, graph, time = result\r\n result_win = Window_Quant()\r\n result_win.setWindowTitle(\"Regression Tree Result Auto\")\r\n result_win.setData(model, score, graph, time)\r\n list_result.append(result_win)\r\n else:\r\n result = RegTree(self.ml_data.feature, self.ml_data.target, RT[\"Auto\"], [RT[\"Criterion\"],\r\n RT[\"Min_Samples_Split\"],\r\n RT[\"Min_Samples_Leaf\"]])\r\n model, score, graph, time = result\r\n result_win = Window_Quant()\r\n result_win.setWindowTitle(\"Regression Tree Result\")\r\n result_win.setData(model, score, graph, time)\r\n list_result.append(result_win)\r\n\r\n if \"KNN\" in dict:\r\n KNN = dict[\"KNN\"]\r\n if KNN[\"Auto\"]:\r\n result = knn_class(self.ml_data.feature, self.ml_data.target, KNN[\"Auto\"])\r\n model, matrix, dict_cr, graph, time = result\r\n result_win = Window()\r\n result_win.setWindowTitle(\"KNN Result Auto\")\r\n result_win.setData(model, matrix, dict_cr, graph, time)\r\n list_result.append(result_win)\r\n else:\r\n result = knn_class(self.ml_data.feature, self.ml_data.target, KNN[\"Auto\"],\r\n [KNN[\"leaf_size\"], KNN[\"n_neighbors\"], KNN[\"p\"], KNN[\"metric\"]])\r\n model, matrix, dict_cr, graph, time = result\r\n self.model_quali.close()\r\n result_win = Window()\r\n result_win.setWindowTitle(\"KNN Result\")\r\n result_win.setData(model, matrix, dict_cr, graph, time)\r\n list_result.append(result_win)\r\n if \"LogiR\" in dict:\r\n LogiR = dict[\"LogiR\"]\r\n if LogiR[\"Auto\"]:\r\n result = LogReg(self.ml_data.feature, self.ml_data.target, LogiR[\"Auto\"])\r\n model, matrix, dict_cr, graph, time = result\r\n result_win = Window()\r\n result_win.setWindowTitle(\"Logistic Regression Result Auto\")\r\n result_win.setData(model, matrix, dict_cr, graph, time)\r\n list_result.append(result_win)\r\n else:\r\n result = LogReg(self.ml_data.feature, self.ml_data.target, LogiR[\"Auto\"], [LogiR['C'],\r\n LogiR['penalty']])\r\n model, matrix, dict_cr, graph, time = result\r\n result_win = Window()\r\n result_win.setWindowTitle(\"Logistic Regression Result\")\r\n result_win.setData(model, matrix, dict_cr, graph, time)\r\n list_result.append(result_win)\r\n\r\n if \"DTC\" in dict:\r\n DTC = dict[\"DTC\"]\r\n if DTC[\"Auto\"]:\r\n result = arbre_clas(self.ml_data.feature, self.ml_data.target, DTC[\"Auto\"])\r\n model, matrix, dict_cr, graph, time = result\r\n result_win = Window()\r\n result_win.setWindowTitle(\"Tree Decision Classification Auto\")\r\n result_win.setData(model, matrix, dict_cr, graph, time)\r\n list_result.append(result_win)\r\n\r\n else:\r\n result = arbre_clas(self.ml_data.feature, self.ml_data.target, DTC[\"Auto\"],DTC[\"max_leaf_nodes\"],DTC[\"max_depth\"],DTC[\"min_samples_split\"])\r\n model, matrix, dict_cr, graph, time = result\r\n result_win = Window()\r\n result_win.setWindowTitle(\"Tree Decision Classification\")\r\n result_win.setData(model, matrix, dict_cr, graph, time)\r\n list_result.append(result_win)\r\n\r\n\r\n self.close()\r\n self.trigger_result.emit(list_result)",
"def scenario(self):\n scenario = []\n for action in self.application_tree['scenario']:\n scenario.append(action)\n return scenario",
"def capabilities(self) -> Sequence['outputs.SkuCapabilityResponse']:\n return pulumi.get(self, \"capabilities\")",
"def list_parameter_value_scores(\n self, legit_arms_only: bool = False\n ) -> pd.DataFrame:\n\n # For experiments which have not ran generate_evaluate_new_parameter_values,\n # we cannot provide trial data without metrics, so we return empty dataframe\n if not self._exp.metrics:\n return pd.DataFrame(\n [],\n columns=[\n \"arm_name\",\n \"metric_name\",\n \"mean\",\n \"sem\",\n \"parameters\",\n \"trial_index\",\n ],\n )\n armscore_df = self._trial_data.df.copy()\n armscore_df[\"parameters\"] = armscore_df[\"arm_name\"].map(\n {k: v.parameters for k, v in self._exp.arms_by_name.items()}\n )\n if self.outcome_constraints:\n # Deduplicate entries for which there are outcome constraints\n armscore_df = armscore_df.loc[\n # pyre-ignore[16]: `None` has no attribute `index`.\n armscore_df.astype(str)\n .drop_duplicates()\n .index\n ]\n if legit_arms_only:\n\n def filter_violating_arms(\n arms: List[Arm], data: Data, optimization_config: OptimizationConfig\n ) -> List[Arm]:\n boolean_indices = []\n for oc in optimization_config.outcome_constraints:\n if oc.op is ComparisonOp.LEQ:\n boolean_indices.append(\n data.df[data.df.metric_name == oc.metric.name][\"mean\"]\n <= oc.bound\n )\n else:\n boolean_indices.append(\n data.df[data.df.metric_name == oc.metric.name][\"mean\"]\n >= oc.bound\n )\n eligible_arm_indices = reduce(lambda x, y: x & y, boolean_indices)\n eligible_arm_names = data.df.loc[eligible_arm_indices.index][\n eligible_arm_indices\n ].arm_name\n return list(\n filter(lambda x: x.name in eligible_arm_names.values, arms)\n )\n\n filtered_arms = filter_violating_arms(\n list(self._exp.arms_by_name.values()),\n self._exp.fetch_data(),\n # pyre-fixme[6]: Expected `OptimizationConfig` for 3rd param but\n # got `Optional[ax.core.optimization_config.OptimizationConfig]`.\n self._exp.optimization_config,\n )\n armscore_df = armscore_df[\n armscore_df[\"arm_name\"].isin([arm.name for arm in filtered_arms])\n ]\n armscore_df = self._repivot_dataframe(armscore_df)\n return armscore_df",
"def enumerate(self, capability: int = Capability.ALL) -> List[Technique]:\n\n # Update the cache for the current user\n self.find_suid()\n\n known_techniques = []\n for user, paths in self.suid_paths.items():\n for path in paths:\n binary = gtfobins.Binary.find(self.pty.which, path=path)\n if binary is not None:\n if (capability & binary.capabilities) == 0:\n continue\n\n known_techniques.append(\n Technique(user, self, binary, binary.capabilities)\n )\n\n return known_techniques",
"def getScreenList(self, verbose = False):\n return execCmd(\"%s -list\" % self._screenPath, verbose)",
"def evaluate(self):\n\n rew_rl = []\n for ckpt_path in self._config.eval_ckpt_paths:\n self._load_ckpt(ckpt_path, self._config.ckpt_num)\n\n logger.info(\n \"Run %d evaluations for %d environments\",\n self._config.num_eval,\n len(self._envs),\n )\n rollouts, info = self._evaluate(record_video=self._config.record_video)\n\n info_stat = info.get_stat()\n\n rew_rl.append(np.mean(info[\"rew_rl\"]))\n\n logger.info(\"All Eval Rew Values: %s\", rew_rl)\n logger.info(\"Eval Rew RL Average: %f, Std: %f\", np.mean(rew_rl), np.std(rew_rl))\n\n os.makedirs(\"result\", exist_ok=True)\n with h5py.File(\"result/{}.hdf5\".format(self._config.run_name), \"w\") as hf:\n for k, v in info.items():\n hf.create_dataset(k, data=info[k])\n with open(\"result/{}.txt\".format(self._config.run_name), \"w\") as f:\n for k, v in info_stat.items():\n f.write(\"{}\\t{:.03f} $\\\\pm$ {:.03f}\\n\".format(k, v[0], v[1]))",
"def get_list_powers(self):\r\n return self._api.get_list_powers()",
"def evaluate(agent, env, n_games=1):\n # env.render()\n game_rewards = []\n for _ in range(n_games):\n states = env.reset()\n\n total_reward = 0\n i = 0\n while True:\n i += 1\n actions = agent.sample_actions(agent.step(states))\n states, rewards, dones, infos = env.step(actions)\n total_reward += sum(rewards)\n if dones[0]:\n break\n\n # We rescale the reward back to ensure compatibility\n # with other evaluations.\n game_rewards.append(total_reward / env.num_envs)\n # env.render('disable')\n return game_rewards"
] | [
"0.5974147",
"0.55311066",
"0.55134237",
"0.5457463",
"0.53889436",
"0.5352742",
"0.53285867",
"0.5295565",
"0.5224027",
"0.5071003",
"0.50637674",
"0.5046169",
"0.49195978",
"0.49133945",
"0.49074385",
"0.4904921",
"0.4887613",
"0.4860214",
"0.48416483",
"0.48318592",
"0.48205298",
"0.4805715",
"0.47876143",
"0.4784968",
"0.47814962",
"0.47635007",
"0.47538528",
"0.47528753",
"0.4743823",
"0.47348306"
] | 0.63355774 | 0 |
Start a capability evaluation against a Smart Home skill. Start a capability evaluation against a Smart Home skill. | def create_smarthome_capability_evaluation_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, EvaluateSHCapabilityResponse_38ae7f22]
operation_name = "create_smarthome_capability_evaluation_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'evaluate_sh_capability_payload' in params:
body_params = params['evaluate_sh_capability_payload']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse", status_code=200, message="Evaluation has successfully begun."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="API user does not have permission or is currently in a state that does not allow calls to this API. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=404, message="The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=409, message="A test run is already in progress for the specified endpoint. Please retry after some time. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=429, message="Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=0, message="Internal server error. "))
api_response = self.invoke(
method="POST",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.smart_home_evaluation.evaluate_sh_capability_response.EvaluateSHCapabilityResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_smart_home_capability_evaluation_v1(self, skill_id, evaluation_id, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, GetSHCapabilityEvaluationResponse_d484531f]\n operation_name = \"get_smart_home_capability_evaluation_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'evaluation_id' is set\n if ('evaluation_id' not in params) or (params['evaluation_id'] is None):\n raise ValueError(\n \"Missing the required parameter `evaluation_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations/{evaluationId}'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n if 'evaluation_id' in params:\n path_params['evaluationId'] = params['evaluation_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_response.GetSHCapabilityEvaluationResponse\", status_code=200, message=\"Successfully retrieved the evaluation status.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.get_sh_capability_evaluation_response.GetSHCapabilityEvaluationResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def list_smarthome_capability_evaluations_v1(self, skill_id, stage, **kwargs):\n # type: (str, str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListSHCapabilityEvaluationsResponse_e6fe49d5, BadRequestError_f854b05]\n operation_name = \"list_smarthome_capability_evaluations_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n # verify the required parameter 'stage' is set\n if ('stage' not in params) or (params['stage'] is None):\n raise ValueError(\n \"Missing the required parameter `stage` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityEvaluations'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'stage' in params:\n query_params.append(('stage', params['stage']))\n if 'start_timestamp_from' in params:\n query_params.append(('startTimestampFrom', params['start_timestamp_from']))\n if 'start_timestamp_to' in params:\n query_params.append(('startTimestampTo', params['start_timestamp_to']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse\", status_code=200, message=\"Successfully retrieved the evaluation infomation.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=403, message=\"API user does not have permission or is currently in a state that does not allow calls to this API. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=404, message=\"The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=0, message=\"Internal server error. \"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_evaluations_response.ListSHCapabilityEvaluationsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def launch_intent():\n welcome_message = \"On which cloud would you like to launch Galaxy?\"\n return question(welcome_message).reprompt(help_text)",
"def test_dispatch_launch(self):\n @self.skill.launch\n def sample_func():\n \"\"\"Decorated function.\"\"\"\n self.skill.response.sessionAttributes['run'] = True\n self.skill.request.request.type = 'LaunchRequest'\n self.skill.dispatch()\n self.assertTrue(self.skill.response.sessionAttributes['run'])",
"def _starting_up():\n global ws, skill_reload_thread, event_scheduler\n\n ws.on('intent_failure', FallbackSkill.make_intent_failure_handler(ws))\n\n # Create skill_manager listener and invoke the first time\n ws.on('skill_manager', skills_manager)\n ws.on('mycroft.internet.connected', install_default_skills)\n ws.emit(Message('skill_manager', {}))\n\n # Create the Intent manager, which converts utterances to intents\n # This is the heart of the voice invoked skill system\n\n PadatiousService(ws)\n IntentService(ws)\n event_scheduler = EventScheduler(ws)\n # Create a thread that monitors the loaded skills, looking for updates\n skill_reload_thread = WatchSkills()\n skill_reload_thread.daemon = True\n skill_reload_thread.start()\n\n # Wait until skills have been loaded once before starting to check\n # network connection\n skill_reload_thread.wait_loaded_priority()\n check_connection()",
"def test_launch(self):\n\n\n username,userpass = self.testdata.find_account_for('toolsubmitter')\n\n self.utils.account.login_as(username,userpass)\n\n self.contribtool.launch(TOOLNAME,username,userpass)",
"def test_with_short_role(self, do_student_launch, student_payload):\n student_payload[\"https://purl.imsglobal.org/spec/lti/claim/roles\"] = [\"Learner\"]\n\n response = do_student_launch()\n\n assert_launched_as_student(response)",
"def on_launch(launch_request, session):\n # Dispatch to your skill's launch\n return get_welcome_response()",
"def main(_):\n description = xm.ExperimentDescription(\n 'HIS - trial=%d' % FLAGS.trial, tags=['his'])\n experiment = build_experiment()\n xm.launch_experiment(description, experiment)",
"def new_skill_interaction(self, skill):\n self.skill_interact[skill] = True",
"def start_experiment():\r\n check_parameters()\r\n try:\r\n EXP.start()\r\n except InputError as inst:\r\n tkMessageBox.showinfo(inst.expr, inst.msg)",
"def on_launch(launch_request, session):\r\n\r\n #print(\"****on_launch requestId=\" + launch_request['requestId'] +\r\n # \", sessionId=\" + session['sessionId'])\r\n # Dispatch to your skill's launch\r\n return get_welcome_response()",
"def on_launch(launch_request, session):\r\n # Dispatch to your skill's launch message\r\n return get_welcome_response()",
"def on_launch(launch_request, session):\n # Dispatch to your skill's launch message\n return get_welcome_response()",
"def setup(mu=MU, sigma=SIGMA, beta=BETA, tau=TAU,\n draw_probability=DRAW_PROBABILITY, backend=None, env=None):\n if env is None:\n env = TrueSkill(mu, sigma, beta, tau, draw_probability, backend)\n global_env.__trueskill__ = env\n return env",
"def _starting_up():\n global bus, skill_manager, event_scheduler\n\n bus.on('intent_failure', FallbackSkill.make_intent_failure_handler(bus))\n\n # Create the Intent manager, which converts utterances to intents\n # This is the heart of the voice invoked skill system\n service = IntentService(bus)\n try:\n PadatiousService(bus, service)\n except Exception as e:\n LOG.exception('Failed to create padatious handlers '\n '({})'.format(repr(e)))\n event_scheduler = EventScheduler(bus)\n\n # Create a thread that monitors the loaded skills, looking for updates\n try:\n skill_manager = SkillManager(bus)\n except MsmException:\n # skill manager couldn't be created, wait for network connection and\n # retry\n LOG.info('Msm is uninitialized and requires network connection',\n 'to fetch skill information\\n'\n 'Waiting for network connection...')\n while not connected():\n time.sleep(30)\n skill_manager = SkillManager(bus)\n\n skill_manager.daemon = True\n # Wait until priority skills have been loaded before checking\n # network connection\n skill_manager.load_priority()\n skill_manager.start()\n check_connection()",
"def on_launch(launch_request, session):\n print(\"on_launch requestId=\" + launch_request['requestId'] +\n \", sessionId=\" + session['sessionId'])\n # Dispatch to your skill's launch\n return get_welcome_help_response()",
"def test_dispatch_intent(self):\n @self.skill.intent('test_intent')\n def sample_func():\n \"\"\"Decorated function.\"\"\"\n self.skill.response.sessionAttributes['run'] = True\n self.skill.request.request.type = 'IntentRequest'\n self.skill.request.request.intent = interface.Intent()\n self.skill.request.request.intent.name = 'test_intent'\n self.skill.dispatch()\n self.assertTrue(self.skill.response.sessionAttributes['run'])",
"def test_start_interactive_session(sample_serial_workflow_in_db):\n with patch.multiple(\"reana_workflow_controller.k8s\",\n current_k8s_corev1_api_client=DEFAULT,\n current_k8s_extensions_v1beta1=DEFAULT) as mocks:\n kwrm = KubernetesWorkflowRunManager(sample_serial_workflow_in_db)\n if len(INTERACTIVE_SESSION_TYPES):\n kwrm.start_interactive_session(INTERACTIVE_SESSION_TYPES[0])\n mocks['current_k8s_extensions_v1beta1'].\\\n create_namespaced_deployment.assert_called_once()\n mocks['current_k8s_corev1_api_client'].\\\n create_namespaced_service.assert_called_once()\n mocks['current_k8s_extensions_v1beta1'].\\\n create_namespaced_ingress.assert_called_once()",
"def capability(self):\r\n return PythonCapability(self.mixins().values())",
"def launch_experiment_on_device(args):\n run_exp_args = args[:-1]\n available_devices = args[-1]\n spec = args[0]\n\n # Get an available GPU device \n gpu_id = available_devices.get()\n old_visible_devices = os.environ.get(c.CVISIBLE, \"\")\n os.environ[c.CVISIBLE] = str(gpu_id)\n\n # Launch the experiment\n try:\n logger.info(\"Running experiment {} on GPU {}\".format(spec[\"name\"], gpu_id))\n proc = multiprocessing.Process(target=run_experiment, args=run_exp_args)\n proc.start()\n proc.join()\n\n logger.info(\"Experiment {} completed sucessfully\".format(spec[\"name\"]))\n except:\n pass\n finally:\n # Return the GPU toekn back to the queue.\n os.environ[c.CVISIBLE] = old_visible_devices\n available_devices.put(gpu_id)",
"def start_sml():\n launchfile = basepath + '/launch/teststarter.launch'\n\n uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)\n #print roslaunch.rlutil.check_roslaunch(launchfile)\n #roslaunch.configure_logging(uuid)\n launch = roslaunch.parent.ROSLaunchParent(uuid, [launchfile])\n launch.start()",
"def start_SLP_server(self):\n import slp\n \n s = self.op.get_value('mode_params')\n if len(s) == 0:\n print 'No parameter received'\n params = {}\n else:\n l_p = self.parse_params(s)\n params = {'action':[np.int(l_p[0])]}\n if len(l_p) == 2:\n params['image_feature_layer_name'] = l_p[1]\n slpserver = slp.SLPServerTrial(self, params)\n slpserver.start()",
"def set_capabilities(self, capabilities: WlSeat.capability) -> None:\n lib.wlr_seat_set_capabilities(self._ptr, capabilities)",
"async def async_turn_on_when_active(self, **kwargs: Any) -> None:\n await self._data.controller.programs.start(self.entity_description.uid)\n self._update_activities()",
"def with_capability(self, capability):\n if not isinstance(capability, str):\n raise TypeError('Capability must be a string')\n\n token = self.token\n capabilities = set(token['capabilities']) if 'capabilities' in token else set([])\n\n capabilities.add(capability)\n\n self.token['capabilities'] = sorted(list(capabilities))\n\n return self",
"def pre_launch(mission):\n started_since = mission.ut() - mission.current_step[\"start_ut\"]\n if started_since > 5:\n mission.next()\n elif mission.current_step[\"first_call\"]:\n vessel = mission.conn.space_center.active_vessel\n ap = vessel.auto_pilot\n\n ap.engage()\n ap.target_pitch_and_heading(90, 90)\n vessel.control.throttle = 1\n vessel.control.sas = False\n vessel.control.rcs = mission.parameters.get('use_rcs', False)",
"def on_launch(launch_request, session):\r\n print(\"on_launch requestId=\" + launch_request['requestId'] +\r\n \", sessionId=\" + session['sessionId'])\r\n # Dispatch to your skill's launch\r\n return get_welcome_response()",
"def on_launch(launch_request, session):\r\n\r\n print(\"on_launch requestId=\" + launch_request['requestId'] +\r\n \", sessionId=\" + session['sessionId'])\r\n # Dispatch to your skill's launch\r\n return skill_information()",
"def start_acquisition(self):\n self.lib.StartAcquisition()"
] | [
"0.62772197",
"0.5553884",
"0.54501694",
"0.5428658",
"0.54112387",
"0.5186431",
"0.5139538",
"0.5126761",
"0.5113529",
"0.508713",
"0.5083189",
"0.5056585",
"0.50493526",
"0.50450873",
"0.5036143",
"0.5013719",
"0.501051",
"0.5009153",
"0.49964237",
"0.49895394",
"0.4989269",
"0.4960641",
"0.49572352",
"0.48863408",
"0.4874462",
"0.48716915",
"0.4870826",
"0.486382",
"0.48571104",
"0.48513716"
] | 0.6188139 | 1 |
List all the test plan names and ids for a given skill ID. List all the test plan names and ids for a given skill ID. | def list_smarthome_capability_test_plans_v1(self, skill_id, **kwargs):
# type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, ListSHCapabilityTestPlansResponse_cb289d6, BadRequestError_f854b05]
operation_name = "list_smarthome_capability_test_plans_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/smartHome/testing/capabilityTestPlans'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
if 'max_results' in params:
query_params.append(('maxResults', params['max_results']))
if 'next_token' in params:
query_params.append(('nextToken', params['next_token']))
header_params = [] # type: List
body_params = None
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_test_plans_response.ListSHCapabilityTestPlansResponse", status_code=200, message="Successfully got the list of test plans."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Bad Request. Returned when the request payload is malformed or when, at least, one required property is missing or invalid. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=403, message="API user does not have permission or is currently in a state that does not allow calls to this API. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=404, message="The specified skill, test plan, or evaluation does not exist. The error response will contain a description that indicates the specific resource type that was not found. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=429, message="Exceeded the permitted request limit. Throttling criteria includes total requests, per API and CustomerId. "))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.error.Error", status_code=0, message="Internal server error. "))
api_response = self.invoke(
method="GET",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type="ask_smapi_model.v1.smart_home_evaluation.list_sh_capability_test_plans_response.ListSHCapabilityTestPlansResponse")
if full_response:
return api_response
return api_response.body | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def list(ctx):\n handler = ValidateCommandHandler(ctx.obj['qa_dir'])\n if handler.validate():\n handler = ListCommandHandler(ctx.obj['qa_dir'])\n handler.show_test_case_tree()\n else:\n exit(1)",
"def list_suites(arn=None, nextToken=None):\n pass",
"def get(cls, plan_id):\n return cls().requests.get(f\"plan/{plan_id}\")",
"def get_list_of_testers_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListTestersResponse_991ec8e9]\n operation_name = \"get_list_of_testers_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/betaTest/testers'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.beta_test.testers.list_testers_response.ListTestersResponse\", status_code=200, message=\"Success.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Bad request.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=409, message=\"The request could not be completed due to a conflict with the current state of the target resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.beta_test.testers.list_testers_response.ListTestersResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def show(self):\n self.parser.add_argument('plan_uuid',\n help=\"Plan uuid or name\")\n args = self.parser.parse_args()\n response = self.client.plans.find(name_or_id=args.plan_uuid)\n fields = ['uuid', 'name', 'description', 'uri']\n data = dict([(f, getattr(response, f, ''))\n for f in fields])\n cliutils.print_dict(data, wrap=72)",
"def list(cls):\n return cls().requests.get('plan')",
"def run_list_cli_tests(experiment_id: int) -> None:\n\n subprocess.check_call(\n [\"det\", \"-m\", conf.make_master_url(), \"experiment\", \"list-trials\", str(experiment_id)]\n )\n\n subprocess.check_call(\n [\"det\", \"-m\", conf.make_master_url(), \"experiment\", \"list-checkpoints\", str(experiment_id)]\n )\n subprocess.check_call(\n [\n \"det\",\n \"-m\",\n conf.make_master_url(),\n \"experiment\",\n \"list-checkpoints\",\n \"--best\",\n str(1),\n str(experiment_id),\n ]\n )",
"def get_challenge_suggestions(self, cr, uid, context=None):\n plan_info = []\n goal_plan_obj = self.pool.get('gamification.goal.plan')\n plan_ids = goal_plan_obj.search(cr, uid, [('proposed_user_ids', 'in', uid), ('state', '=', 'inprogress')], context=context)\n for plan in goal_plan_obj.browse(cr, uid, plan_ids, context=context):\n values = {\n 'id': plan.id,\n 'name': plan.name,\n 'description': plan.description,\n }\n plan_info.append(values)\n return plan_info",
"def list(self):\n print \"\\nAvailable Test Cases\"\n print \"====================\"\n for case in self.cases:\n print case.__name__",
"def lab_test_list(\n self, params: Optional[Dict] = None, headers: Optional[Dict] = None\n ) -> List[LabTestDetails]:\n method = self._get_method(\"lab_tests\")\n\n return self.call_api_get(method=method, params=params, headers=headers)",
"def plans(self):\n title = self.context.Title()\n return self.portal_catalog(portal_type='Plan', Subject=title)",
"def show(ctx):\n skale = ctx.obj['skale']\n # from skale.utils.contracts_provision.main import add_test_permissions\n # add_test_permissions(skale)\n show_all_schains_names(skale)",
"def planned(sid):\n manager = Actions()\n tasks = manager.get_planned_list(sid)\n if not tasks:\n click.echo(\"No tasks with such sid\")\n return\n click.secho(\"Scheduler ID: \" + sid, fg='yellow')\n for task in tasks:\n click.echo(task.tid + \" - \" + task.title)",
"def test_get_product_rate_plan_by_id(self):\n pass",
"def plans():\n results = []\n if 'qry' in request.args:\n look_for = request.args['qry']\n if look_for[0] == '*':\n look_for = ''\n zipcode = request.args['zipcode']\n\n try:\n plan = request.args['plan']\n except KeyError:\n return None\n\n # If this is a medicaid or private plan\n where = tools.get_location(zipcode)\n if where:\n if plan in ('medicaid', 'private'):\n state = where.STATE\n results = PlanNames.by_state(state, look_for, plan=='medicaid')\n results = [r.plan_name for r in results]\n if state == 'OH':\n results.append('OH State Medicaid')\n elif plan == 'medicare':\n county_code = where.GEO.COUNTY_CODE\n ma_region = where.GEO.MA_REGION_CODE\n pdp_region = where.GEO.PDP_REGION_CODE\n results = Plans.find_in_county(county_code, ma_region, pdp_region, look_for)\n\n return jsonify(sorted(results))",
"def list_tests(arn=None, nextToken=None):\n pass",
"def plan_detail(request, plan_id):\n\n plan = get_object_or_404(Plan, pk=plan_id)\n\n context = {\n 'plan': plan,\n }\n\n return render(request, 'plans/plan_detail.html', context)",
"def List(ctx):\n \"\"\"Note: This method is available only through the per-node API endpoint 5.0 or later.\"\"\"\n if ctx.element is None:\n ctx.logger.error(\"You must establish at least one connection and specify which you intend to use.\")\n exit()\n\n\n\n ctx.logger.info(\"\")\n try:\n ListTestsResult = ctx.element.list_tests()\n except common.ApiServerError as e:\n ctx.logger.error(e.message)\n exit()\n except BaseException as e:\n ctx.logger.error(e.__str__())\n exit()\n\n cli_utils.print_result(ListTestsResult, ctx.logger, as_json=ctx.json, depth=ctx.depth, filter_tree=ctx.filter_tree)",
"def get_goals_todo_info(self, cr, uid, context=None):\n all_goals_info = []\n plan_obj = self.pool.get('gamification.goal.plan')\n\n plan_ids = plan_obj.search(cr, uid, [('user_ids', 'in', uid), ('state', '=', 'inprogress')], context=context)\n for plan in plan_obj.browse(cr, uid, plan_ids, context=context):\n # serialize goals info to be able to use it in javascript\n serialized_goals_info = {\n 'id': plan.id,\n 'name': plan.name,\n 'visibility_mode': plan.visibility_mode,\n }\n user = self.browse(cr, uid, uid, context=context)\n serialized_goals_info['currency'] = user.company_id.currency_id.id\n\n if plan.visibility_mode == 'board':\n # board report should be grouped by planline for all users\n goals_info = plan_obj.get_board_goal_info(cr, uid, plan, subset_goal_ids=False, context=context)\n\n if len(goals_info) == 0:\n # plan with no valid planlines\n continue\n\n serialized_goals_info['planlines'] = []\n for planline_board in goals_info:\n vals = {'type_name': planline_board['goal_type'].name,\n 'type_description': planline_board['goal_type'].description,\n 'type_condition': planline_board['goal_type'].condition,\n 'type_computation_mode': planline_board['goal_type'].computation_mode,\n 'type_monetary': planline_board['goal_type'].monetary,\n 'type_suffix': planline_board['goal_type'].suffix,\n 'type_action': True if planline_board['goal_type'].action_id else False,\n 'type_display': planline_board['goal_type'].display_mode,\n 'target_goal': planline_board['target_goal'],\n 'goals': []}\n for goal in planline_board['board_goals']:\n # Keep only the Top 3 and the current user\n if goal[0] > 2 and goal[1].user_id.id != uid:\n continue\n\n vals['goals'].append({\n 'rank': goal[0] + 1,\n 'id': goal[1].id,\n 'user_id': goal[1].user_id.id,\n 'user_name': goal[1].user_id.name,\n 'state': goal[1].state,\n 'completeness': goal[1].completeness,\n 'current': goal[1].current,\n 'target_goal': goal[1].target_goal,\n })\n if uid == goal[1].user_id.id:\n vals['own_goal_id'] = goal[1].id\n serialized_goals_info['planlines'].append(vals)\n\n else:\n # individual report are simply a list of goal\n goals_info = plan_obj.get_indivual_goal_info(cr, uid, uid, plan, subset_goal_ids=False, context=context)\n\n if not goals_info:\n continue\n\n serialized_goals_info['goals'] = []\n for goal in goals_info:\n serialized_goals_info['goals'].append({\n 'id': goal.id,\n 'type_name': goal.type_id.name,\n 'type_description': goal.type_description,\n 'type_condition': goal.type_id.condition,\n 'type_monetary': goal.type_id.monetary,\n 'type_suffix': goal.type_id.suffix,\n 'type_action': True if goal.type_id.action_id else False,\n 'type_display': goal.type_id.display_mode,\n 'state': goal.state,\n 'completeness': goal.completeness,\n 'computation_mode': goal.computation_mode,\n 'current': goal.current,\n 'target_goal': goal.target_goal,\n })\n\n all_goals_info.append(serialized_goals_info)\n return all_goals_info",
"def get_plan(self):\n\t\tresponse = self.client.get(self._endpoint + \"/plan\")\n\t\tplan = response.json['plans']\n\t\tplan = list(plan.items())[0][1]\n\t\treturn Plan(plan['plan_id'],data=plan)",
"def test_get_all_rate_plans(self):\n pass",
"def plan_list_get(request):\n return list_by_company_guid(request, PlanModel)",
"def get_plan_logs(res: List[Dict[str, Any]], plan_id: str) -> str:\n plan_substr = f'plan \"{plan_id}\"'\n return \"; \".join(_get_logs_with_substring(res, plan_substr))",
"def test_skills(\n self, mock_get_ai_details, mock_get_ai, mock_get_categories\n ):\n\n mock_get_ai.return_value = self.ai\n mock_get_ai_details.return_value = self.ai_details\n\n mock_get_ai_details.return_value['skills'] = [\n {'name': 'bot 1'},\n {'name': 'bot 2'},\n {'name': 'bot 3'},\n {'name': 'bot 4'},\n {'name': 'bot 5'},\n {'name': 'bot 6'},\n ]\n\n response = self.client.get(reverse(\n 'studio:edit_bot',\n kwargs={'aiid': self.ai['aiid']}\n ))\n\n self.assertContains(response, 'bot 1')\n self.assertContains(response, 'bot 2')\n self.assertContains(response, 'bot 3')\n self.assertContains(response, 'bot 4')\n self.assertContains(response, 'bot 5')\n self.assertNotContains(response, 'bot 6')\n self.assertNotContains(response, 'Speed up your bot building process by '\n 'starting with one of our Templates from the store.')",
"def show_skill(self, index, show_other_skill=False):\n show = [[],[]]\n show[0].append('Top Skills: ')\n show[1].append('Other Skills: ')\n if 'skills' not in self.data_profile[index].keys():\n print('This profile doesn\\'t contain any skill.')\n return\n for skills in self.data_profile[index]['skills']:\n if skills['title'] == 'Top Skills':\n for skill in skills['skills']:\n show[0].append(skill['title'])\n else:\n for skill in skills['skills']:\n show[1].append(skill['title'])\n print(\"index:\",index)\n print(show[0])\n if show_other_skill:\n print(show[1])\n print(\" \")\n return",
"def all_plans(request):\n\n plans = Plan.objects.all()\n\n context = {\n 'plans': plans,\n }\n\n return render(request, 'plans/plans.html', context)",
"def get_skill_list(self):\n return [\n i.strip() for i in\n self.ansi_escape.sub('', check_output([BIN, 'list'])).split('\\n')\n ]",
"def lab_test_details(\n self,\n lab_test_id: str,\n params: Optional[Dict] = None,\n headers: Optional[Dict] = None,\n ) -> LabTestDetails:\n method = self._get_method(\"lab_test_details\")\n method = method.format(**{\"id\": lab_test_id})\n\n return self.call_api_get(method=method, params=params, headers=headers)",
"def printout_all(self, indent_level):\n indent = \" \"*indent_level*INDENTATION_MULTIPLIER\n\n print(indent, \"\\nTest Definition ID:\", self.ID, sep='')\n print(indent, \"|-name:\", self.name, sep='')\n\n print(indent, \"|-associated test case ID:\", self.test_case_ID, sep='')\n test_case = get_indexed_item_from_list(self.test_case_ID, AutoResilGlobal.test_case_list)\n if test_case != None:\n test_case.printout_all(indent_level+1)\n\n print(indent, \"|-test code ID:\", self.test_code_ID, sep='')\n\n print(indent, \"|-associated challenge def ID:\", self.challenge_def_ID, sep='')\n challenge_def = get_indexed_item_from_list(self.challenge_def_ID, AutoResilGlobal.challenge_definition_list)\n if challenge_def != None:\n challenge_def.printout_all(indent_level+1)\n\n if self.VNF_ID_list != None:\n if len(self.VNF_ID_list) >0:\n print(indent, \"|-associated VNFs:\", sep='')\n for VNF_ID in self.VNF_ID_list:\n VNF_item = get_indexed_item_from_list(VNF_ID, AutoResilGlobal.VNF_Service_list)\n if VNF_item != None:\n VNF_item.printout_all(indent_level+1)\n\n if self.associated_metrics_ID_list != None:\n if len(self.associated_metrics_ID_list) >0:\n print(indent, \"|-associated metrics:\", sep='')\n for Metric_ID in self.associated_metrics_ID_list:\n Metric_item = get_indexed_item_from_list(Metric_ID, AutoResilGlobal.metric_definition_list)\n if Metric_item != None:\n Metric_item.printout_all(indent_level+1)\n\n if self.recipient_ID_list != None:\n if len(self.recipient_ID_list) >0:\n print(indent, \"|-associated recipients:\", sep='')\n for recipient_ID in self.recipient_ID_list:\n recipient_item = get_indexed_item_from_list(recipient_ID, AutoResilGlobal.recipient_list)\n if recipient_item != None:\n recipient_item.printout_all(indent_level+1)\n\n if self.test_CLI_command_sent_list != None:\n if len(self.test_CLI_command_sent_list) >0:\n print(indent, \"|-associated CLI commands:\", sep='')\n for CLI_command in self.test_CLI_command_sent_list:\n print(\" \"*INDENTATION_MULTIPLIER, \"|- \", CLI_command, sep='')\n\n # TODO: self.test_API_command_sent_list (depends how API commands are stored: likely a list of strings)",
"def test_get_skills_multiple_lessons(self):\n skill_graph = SkillGraph.load()\n\n skill_1 = skill_graph.add(Skill.build(SKILL_NAME, SKILL_DESC))\n unit = self.course.add_unit()\n unit.title = 'Test Unit'\n lesson1 = self.course.add_lesson(unit)\n lesson1.title = 'Test Lesson 1'\n lesson2 = self.course.add_lesson(unit)\n lesson2.title = 'Test Lesson 2'\n self.course.save()\n lesson1.properties[SKILLS_KEY] = [skill_1.id]\n lesson2.properties[SKILLS_KEY] = [skill_1.id]\n self.course.save()\n\n actions.login(ADMIN_EMAIL)\n response = transforms.loads(self.get(self.URL).body)\n self.assertEqual(200, response['status'])\n\n skills = transforms.loads(response['payload'])['skills']\n self.assertEqual(1, len(skills))\n # All lessons listed\n self.assertEqual(2, len(skills[0]['lessons']))"
] | [
"0.56431407",
"0.55883217",
"0.5554718",
"0.5404543",
"0.5404047",
"0.5321804",
"0.5203172",
"0.51931494",
"0.516061",
"0.51549864",
"0.5103691",
"0.50883895",
"0.50455576",
"0.50242794",
"0.5016513",
"0.50162756",
"0.500834",
"0.49830192",
"0.4971972",
"0.4864909",
"0.48607227",
"0.4837905",
"0.47789833",
"0.47492447",
"0.4731878",
"0.47005522",
"0.47002748",
"0.4695561",
"0.4681499",
"0.46571913"
] | 0.68275034 | 0 |
Updates the ssl certificates associated with this skill. | def set_ssl_certificates_v1(self, skill_id, ssl_certificate_payload, **kwargs):
# type: (str, SSLCertificatePayload_97891902, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, BadRequestError_f854b05]
operation_name = "set_ssl_certificates_v1"
params = locals()
for key, val in six.iteritems(params['kwargs']):
params[key] = val
del params['kwargs']
# verify the required parameter 'skill_id' is set
if ('skill_id' not in params) or (params['skill_id'] is None):
raise ValueError(
"Missing the required parameter `skill_id` when calling `" + operation_name + "`")
# verify the required parameter 'ssl_certificate_payload' is set
if ('ssl_certificate_payload' not in params) or (params['ssl_certificate_payload'] is None):
raise ValueError(
"Missing the required parameter `ssl_certificate_payload` when calling `" + operation_name + "`")
resource_path = '/v1/skills/{skillId}/sslCertificateSets/~latest'
resource_path = resource_path.replace('{format}', 'json')
path_params = {} # type: Dict
if 'skill_id' in params:
path_params['skillId'] = params['skill_id']
query_params = [] # type: List
header_params = [] # type: List
body_params = None
if 'ssl_certificate_payload' in params:
body_params = params['ssl_certificate_payload']
header_params.append(('Content-type', 'application/json'))
header_params.append(('User-Agent', self.user_agent))
# Response Type
full_response = False
if 'full_response' in params:
full_response = params['full_response']
# Authentication setting
access_token = self._lwa_service_client.get_access_token_from_refresh_token()
authorization_value = "Bearer " + access_token
header_params.append(('Authorization', authorization_value))
error_definitions = [] # type: List
error_definitions.append(ServiceClientResponse(response_type=None, status_code=204, message="Accepted; Request was successful and get will now result in the new values."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.bad_request_error.BadRequestError", status_code=400, message="Server cannot process the request due to a client error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=401, message="The auth token is invalid/expired or doesn't have access to the resource."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=404, message="The resource being requested is not found."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=429, message="Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=500, message="Internal Server Error."))
error_definitions.append(ServiceClientResponse(response_type="ask_smapi_model.v1.skill.standardized_error.StandardizedError", status_code=503, message="Service Unavailable."))
api_response = self.invoke(
method="PUT",
endpoint=self._api_endpoint,
path=resource_path,
path_params=path_params,
query_params=query_params,
header_params=header_params,
body=body_params,
response_definitions=error_definitions,
response_type=None)
if full_response:
return api_response
return None | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_ssl(self):\n for params in self.config.get_ssl_params():\n self.connection.transport.set_ssl(**params)",
"def get_ssl_certificates_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, StandardizedError_f5106a89, SSLCertificatePayload_97891902]\n operation_name = \"get_ssl_certificates_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/sslCertificateSets/~latest'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.ssl_certificate_payload.SSLCertificatePayload\", status_code=200, message=\"Response contains the latest version of the ssl certificates.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=429, message=\"Exceeds the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=500, message=\"Internal Server Error.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.standardized_error.StandardizedError\", status_code=503, message=\"Service Unavailable.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.ssl_certificate_payload.SSLCertificatePayload\")\n\n if full_response:\n return api_response\n return api_response.body",
"def push_ssl_crt():\n logger.info(u\"Pushing SSl Certificates\")\n key = '%(config_folder)s/%(ssl_key)s' % env\n crt = '%(config_folder)s/%(ssl_crt)s' % env\n bundle = '%(config_folder)s/rapidssl_ca_bundle.pem' % env\n logger.info(u\"Using SSL keys and certs at %s and %s\" % (key, crt))\n\n # Putting to /tmp and moving for permission purposes\n put(key, '/tmp/_.policystat.com.key')\n sudo('mv /tmp/_.policystat.com.key /etc/ssl/private/_.policystat.com.key')\n sudo('chmod 640 /etc/ssl/private/_.policystat.com.key')\n sudo('chown root:ssl-cert /etc/ssl/private/_.policystat.com.key')\n\n put(crt, '/tmp/_.policystat.com.crt')\n put(bundle, '/tmp/rapidssl_ca_bundle.pem')\n # Combine the crt with the rapidssl intermediate bundle\n sudo('cat /tmp/_.policystat.com.crt /tmp/rapidssl_ca_bundle.pem > \\\n /tmp/_.policystat.com.crt.bundled')\n sudo(\n 'mv /tmp/_.policystat.com.crt.bundled '\n '/etc/ssl/certs/_.policystat.com.crt'\n )\n sudo('chmod 777 /etc/ssl/certs/_.policystat.com.crt')",
"def apply_certs(application_name):\n APP_CERT_DIR = os.path.join(CERT_DIR, application_name)\n ssl_options = [\n ('ssl_ca', os.path.join(CERT_DIR, 'cacert.pem')),\n ('ssl_cert', os.path.join(APP_CERT_DIR, 'cert.pem')),\n ('ssl_key', os.path.join(APP_CERT_DIR, 'cert.key'))]\n charm_config = {}\n for (charm_option, ssl_file) in ssl_options:\n with open(ssl_file, 'rb') as f:\n ssl_data = f.read()\n charm_config[charm_option] = base64.b64encode(ssl_data).decode('utf8')\n model.set_application_config(\n application_name,\n configuration=charm_config)",
"def ModifyCertificateAttributes(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyCertificateAttributes\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyCertificateAttributesResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def update_ssl_termination(self, securePort=None, enabled=None,\n secureTrafficOnly=None):\n return self.manager.update_ssl_termination(self, securePort=securePort,\n enabled=enabled, secureTrafficOnly=secureTrafficOnly)",
"def configure_https():\n # need to write all to ensure changes to the entire request pipeline\n # propagate (c-api, haprxy, apache)\n CONFIGS.write_all()\n if 'https' in CONFIGS.complete_contexts():\n cmd = ['a2ensite', 'openstack_https_frontend']\n subprocess.check_call(cmd)\n else:\n cmd = ['a2dissite', 'openstack_https_frontend']\n subprocess.check_call(cmd)\n\n # TODO: improve this by checking if local CN certs are available\n # first then checking reload status (see LP #1433114).\n service_reload('apache2', restart_on_failure=True)\n\n for rid in relation_ids('identity-service'):\n identity_joined(rid=rid)",
"def fusion_api_edit_login_domains_login_certificates(self, body, param='', api=None, headers=None):\n return self.login_certificates.update(body, param, api, headers)",
"def ModifyCertificate(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyCertificate\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyCertificateResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def ssl(self, cainfo=None, verify=True, cert=None, key=None):\n if cainfo:\n self.curl.setopt(pycurl.CAINFO, cainfo)\n\n if verify == False:\n self.curl.setopt(pycurl.SSL_VERIFYPEER, 0)\n self.curl.setopt(pycurl.SSL_VERIFYHOST, 0)\n else:\n self.curl.setopt(pycurl.SSL_VERIFYPEER, 1)\n self.curl.setopt(pycurl.SSL_VERIFYHOST, 2)\n if cert:\n #self.curl.setopt(pycurl.SSLCERTTYPE, \"DER\")\n self.curl.setopt(pycurl.SSLCERT, cert)\n if key:\n self.curl.setopt(pycurl.SSLKEY, key)",
"def _load_ssl_certificate(self) -> ssl.SSLContext:\n\n sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)\n sslcontext.load_cert_chain(\n path.join(path.dirname(__file__), '..', '..', 'player.crt'),\n path.join(path.dirname(__file__), '..', '..', 'player.key')\n )\n\n return sslcontext",
"def update_cert(c, stack_name, domain_name, profile, create=False):\n action = 'create' if create else 'update'\n\n with chdir(WORKING_DIR):\n aws('cloudformation', f'{action}-stack',\n '--stack-name', f'{stack_name}-cert',\n '--template-body', f'file://cert.yaml',\n '--parameters',\n f'ParameterKey=DomainName,ParameterValue={domain_name}',\n f'--profile', f'{profile}')\n # Cert also needs adding to us-east-1 to be used by CloudFront\n aws('cloudformation', f'{action}-stack',\n '--stack-name', f'{stack_name}-cert',\n '--template-body', f'file://cert.yaml',\n '--parameters',\n f'ParameterKey=DomainName,ParameterValue={domain_name}',\n f'--profile', f'{profile}',\n '--region', 'us-east-1')",
"def initialize_ssl(self):\n self.ssl_context = ssl.SSLContext()\n # if self.config.get('ca_file', None):\n # self.ssl_context.load_verify_locations(ca_file=self.config['ca_file'])\n\n # TODO : Remove this\n\n verify_ssl = self.config[\"AUTH\"][\"verify_ssl\"]\n if isinstance(verify_ssl, str):\n verify_ssl = strtobool(verify_ssl)\n\n if not verify_ssl:\n self.ssl_context.verify_mode = ssl.CERT_NONE",
"def get_ssl_certificate() :",
"def test_update_certificate_keys(self):\n self.client.post(\n '/api/v1/certificates', data=json.dumps(new_certificate),\n content_type='application/json',\n headers=self.get_registrar_token())\n response = self.client.put(\n '/api/v1/certificates/1', data=json.dumps(update_certificate_keys),\n content_type='application/json',\n headers=self.get_registrar_token())\n result = json.loads(response.data.decode())\n self.assertEqual(result['message'],\n 'Invalid certificate_name key')\n assert response.status_code == 400",
"def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,\n secureTrafficOnly=None):\n return loadbalancer.update_ssl_termination(securePort=securePort,\n enabled=enabled, secureTrafficOnly=secureTrafficOnly)",
"def _load_ssl(self, ssl_options: tuple):\n try:\n self._ssl.load_cert_chain(certfile=ssl_options[0], keyfile=ssl_options[1], password=ssl_options[2])\n except IOError as e:\n self.logger.error(\"Unable to load certificate files: {}\".format(e))\n self.stop()",
"def create_https_certificates(ssl_cert, ssl_key):\n\n import logger\n from OpenSSL import crypto\n from certgen import createKeyPair, createCertRequest, createCertificate, \\\n TYPE_RSA, serial\n\n # Create the CA Certificate\n cakey = createKeyPair(TYPE_RSA, 2048)\n careq = createCertRequest(cakey, CN=\"Certificate Authority\")\n cacert = createCertificate(careq, (careq, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years\n\n pkey = createKeyPair(TYPE_RSA, 2048)\n req = createCertRequest(pkey, CN=\"Mylar\")\n cert = createCertificate(req, (cacert, cakey), serial, (0, 60 * 60 * 24 * 365 * 10)) # ten years\n\n # Save the key and certificate to disk\n try:\n with open(ssl_key, \"w\") as fp:\n fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))\n with open(ssl_cert, \"w\") as fp:\n fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))\n except IOError as e:\n logger.error(\"Error creating SSL key and certificate: %s\", e)\n return False\n\n return True",
"def redirect_to_ssl(self, domains):\n for dom in domains:\n try:\n self.installer.enhance(dom, \"redirect\")\n except errors.LetsEncryptConfiguratorError:\n logging.warn(\"Unable to perform redirect for %s\", dom)\n\n self.installer.save(\"Add Redirects\")\n self.installer.restart()",
"def ssl_config(self) -> 'outputs.SslConfigResponse':\n return pulumi.get(self, \"ssl_config\")",
"def ModifyHTTPSListenerAttribute(self, request):\n try:\n params = request._serialize()\n headers = request.headers\n body = self.call(\"ModifyHTTPSListenerAttribute\", params, headers=headers)\n response = json.loads(body)\n model = models.ModifyHTTPSListenerAttributeResponse()\n model._deserialize(response[\"Response\"])\n return model\n except Exception as e:\n if isinstance(e, TencentCloudSDKException):\n raise\n else:\n raise TencentCloudSDKException(type(e).__name__, str(e))",
"def test_update_certificate(self):\n self.client.post(\n '/api/v1/certificates', data=json.dumps(new_certificate),\n content_type='application/json',\n headers=self.get_registrar_token())\n response = self.client.put(\n '/api/v1/certificates/1', data=json.dumps(update_certificate),\n content_type='application/json',\n headers=self.get_registrar_token())\n result = json.loads(response.data.decode())\n self.assertEqual(result['message'],\n 'Certificate updated successfully')\n assert response.status_code == 200",
"def ConnectSSL(self):\n with open(self.DEFAULT_CLIENT_KEY_FILE, 'rb') as f:\n private_key = f.read()\n with open(self.DEFAULT_CLIENT_CHAIN_FILE, 'rb') as f:\n certificate_chain = f.read()\n with open(self.DEFAULT_ROOT_CERT_FILE, 'rb') as f:\n root_ca = f.read()\n credentials = grpc.ssl_channel_credentials(root_certificates=root_ca, private_key=private_key, certificate_chain=certificate_chain)\n self.channel = grpc.secure_channel(self.address, credentials)\n self._setup()",
"def fusion_api_update_server_certificate(self, aliasname, body, api=None, headers=None):\n return self.server_certificate.put(aliasname, body, api, headers)",
"def get_ssl_certificate():",
"def set_ssl_context(self, ssl_verify, ssl_cafile):\n if not ssl_verify:\n self.ssl_context = ssl.create_default_context()\n self.ssl_context.check_hostname = False\n self.ssl_context.verify_mode = ssl.CERT_NONE\n elif ssl_cafile:\n self.ssl_context = ssl.create_default_context(cafile=ssl_cafile)\n else:\n self.ssl_context = ssl.create_default_context()",
"def update_server_cert(self, cert_name, new_cert_name=None,\r\n new_path=None):\r\n params = {'ServerCertificateName' : cert_name}\r\n if new_cert_name:\r\n params['NewServerCertificateName'] = new_cert_name\r\n if new_path:\r\n params['NewPath'] = new_path\r\n return self.get_response('UpdateServerCertificate', params)",
"def update_listener(self, service, bigips):\n\n u\"\"\"\n ATTENTION: The hole impl. is a hack.\n For ssl profile settings the order is very important:\n 1. A new ssl profile is created but not applied to the listener\n 2. The esd_apply configures the listener with the new profile (so the old one will be detached)\n 3. The update will apply the changes to the listener\n 4. The remove_ssl is than be able to remove unneeded ssl profiles because they got detached in 3.\n \"\"\"\n\n # check for ssl client cert changes\n old_default = None\n old_sni_containers = None\n new_default = None\n new_sni_containers = None\n vip = self.service_adapter.get_virtual(service)\n\n #pdb.set_trace()\n\n listener = service.get('listener')\n if listener.get('protocol') == 'TERMINATED_HTTPS':\n old_listener = service.get('old_listener')\n if old_listener != None:\n listener = service.get('listener')\n if old_listener.get('default_tls_container_id') != listener.get('default_tls_container_id'):\n old_default = old_listener.get('default_tls_container_id')\n new_default = listener.get('default_tls_container_id')\n\n # determine sni delta with set substraction\n old_snis = old_listener.get('sni_containers')\n new_snis = listener.get('sni_containers')\n old_ids = []\n new_ids = []\n for old in old_snis:\n old_ids.append(old.get('tls_container_id'))\n for new in new_snis:\n new_ids.append(new.get('tls_container_id'))\n new_sni_containers = self._make_sni_tls(vip, list(set(new_ids) - set(old_ids)))\n old_sni_containers = self._make_sni_tls(vip, list(set(old_ids) - set(new_ids)))\n\n # create old and new tls listener configurations\n # create new ssl-profiles on F5 BUT DO NOT APPLY them to listener\n old_tls = None\n if (new_default != None or (new_sni_containers != None and new_sni_containers['sni_containers'])):\n new_tls = self.service_adapter.get_tls(service)\n new_tls = self._make_default_tls(vip, new_tls.get('default_tls_container_id'))\n\n if old_default != None:\n old_tls = self._make_default_tls(vip, old_default)\n\n for bigip in bigips:\n # create ssl profile but do not apply\n if new_tls != None:\n try:\n self.add_ssl_profile(new_tls, bigip, False)\n except:\n pass\n if new_sni_containers != None and new_sni_containers['sni_containers']:\n try:\n self.add_ssl_profile(new_sni_containers, bigip, False)\n except:\n pass\n\n\n # process esd's AND create new client ssl config for listener\n self.apply_esds(service, vip)\n\n # apply changes to listener AND remove not needed ssl profiles on F5\n error = None\n network_id = service['loadbalancer']['network_id']\n for bigip in bigips:\n self.service_adapter.get_vlan(vip, bigip, network_id)\n try:\n self.vs_helper.update(bigip, vip)\n except Exception as err:\n LOG.error(\"Error changing listener: {0}\".format(err))\n error = err if error is None else error\n # delete ssl profiles\n if listener.get('protocol') == 'TERMINATED_HTTPS':\n if old_tls != None:\n try:\n self.remove_ssl_profiles(old_tls, bigip)\n except:\n pass\n if old_sni_containers != None and old_sni_containers['sni_containers']:\n try:\n self.remove_ssl_profiles(old_sni_containers, bigip)\n except:\n pass\n\n if error:\n raise error",
"def get_certifications_list_v1(self, skill_id, **kwargs):\n # type: (str, **Any) -> Union[ApiResponse, object, Error_fbe913d9, BadRequestError_f854b05, ListCertificationsResponse_f2a417c6]\n operation_name = \"get_certifications_list_v1\"\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'skill_id' is set\n if ('skill_id' not in params) or (params['skill_id'] is None):\n raise ValueError(\n \"Missing the required parameter `skill_id` when calling `\" + operation_name + \"`\")\n\n resource_path = '/v1/skills/{skillId}/certifications'\n resource_path = resource_path.replace('{format}', 'json')\n\n path_params = {} # type: Dict\n if 'skill_id' in params:\n path_params['skillId'] = params['skill_id']\n\n query_params = [] # type: List\n if 'next_token' in params:\n query_params.append(('nextToken', params['next_token']))\n if 'max_results' in params:\n query_params.append(('maxResults', params['max_results']))\n\n header_params = [] # type: List\n\n body_params = None\n header_params.append(('Content-type', 'application/json'))\n header_params.append(('User-Agent', self.user_agent))\n\n # Response Type\n full_response = False\n if 'full_response' in params:\n full_response = params['full_response']\n\n # Authentication setting\n access_token = self._lwa_service_client.get_access_token_from_refresh_token()\n authorization_value = \"Bearer \" + access_token\n header_params.append(('Authorization', authorization_value))\n\n error_definitions = [] # type: List\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.skill.certification.list_certifications_response.ListCertificationsResponse\", status_code=200, message=\"Returns list of certifications for the skillId.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.bad_request_error.BadRequestError\", status_code=400, message=\"Server cannot process the request due to a client error e.g. if any request parameter is invalid like certification Id or pagination token etc. If the maxResults is not in the range of 1 to 50, it also qualifies for this error. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=401, message=\"The auth token is invalid/expired or doesn't have access to the resource.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=404, message=\"The resource being requested is not found.\"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=429, message=\"Exceeded the permitted request limit. Throttling criteria includes total requests, per API, ClientId, and CustomerId. \"))\n error_definitions.append(ServiceClientResponse(response_type=\"ask_smapi_model.v1.error.Error\", status_code=500, message=\"Internal Server Error.\"))\n\n api_response = self.invoke(\n method=\"GET\",\n endpoint=self._api_endpoint,\n path=resource_path,\n path_params=path_params,\n query_params=query_params,\n header_params=header_params,\n body=body_params,\n response_definitions=error_definitions,\n response_type=\"ask_smapi_model.v1.skill.certification.list_certifications_response.ListCertificationsResponse\")\n\n if full_response:\n return api_response\n return api_response.body",
"def ssl_required(self, ssl_required):\n\n self._ssl_required = ssl_required"
] | [
"0.6306607",
"0.6258621",
"0.5748135",
"0.5698498",
"0.55363846",
"0.5513241",
"0.54940665",
"0.54402393",
"0.539449",
"0.536771",
"0.5336908",
"0.5336089",
"0.5336076",
"0.53339297",
"0.53305984",
"0.531012",
"0.5247898",
"0.5241155",
"0.5202548",
"0.52011997",
"0.5197142",
"0.5145615",
"0.5128926",
"0.512857",
"0.5111923",
"0.5103219",
"0.5057522",
"0.5051065",
"0.5050169",
"0.5044515"
] | 0.71147346 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.