Best Python code snippet using pyatom_python
tensor_format_test.py
Source:tensor_format_test.py  
...93        self.assertEqual(match.start(), start_col)94        self.assertEqual(match.end(), end_col)95        element_index += 196    self.assertEqual(element_index, np.size(a))97  def _findFirst(self, lines, string):98    """Find first occurrence of a string in a list of strings."""99    for i, line in enumerate(lines):100      find_index = line.find(string)101      if find_index >= 0:102        return i, find_index103  def _extractBoldNumbers(self, out, start_line):104    """Extract all numbers that have the bold font attribute.105    Args:106      out: An instance of RichTextLines.107      start_line: 0-based index to start from.108    Returns:109      A list of floats.110    """111    floats = []112    for i in range(start_line, len(out.lines)):113      if i not in out.font_attr_segs:114        continue115      line_attrs = out.font_attr_segs[i]116      for begin, end, attr_value in line_attrs:117        if attr_value == "bold":118          floats.append(float(out.lines[i][begin:end]))119    return floats120  def testFormatZeroDimensionTensor(self):121    a = np.array(42, dtype=np.int32)122    out = tensor_format.format_tensor(a, "a")123    cli_test_utils.assert_lines_equal_ignoring_whitespace(124        self, ["Tensor \"a\":", ""], out.lines[:2])125    self.assertTrue(out.lines[2].startswith("array(42"))126    self._checkTensorMetadata(a, out.annotations)127  def testFormatTensorHighlightsTensorNameWithoutDebugOp(self):128    tensor_name = "a_tensor:0"129    a = np.zeros(2)130    out = tensor_format.format_tensor(131        a, tensor_name, np_printoptions={"linewidth": 40})132    self.assertEqual([(8, 8 + len(tensor_name), "bold")], out.font_attr_segs[0])133  def testFormatTensorHighlightsTensorNameWithDebugOp(self):134    tensor_name = "a_tensor:0"135    debug_op = "DebugIdentity"136    a = np.zeros(2)137    out = tensor_format.format_tensor(138        a, "%s:%s" % (tensor_name, debug_op), np_printoptions={"linewidth": 40})139    self.assertEqual([(8, 8 + len(tensor_name), "bold"),140                      (8 + len(tensor_name) + 1,141                       8 + len(tensor_name) + 1 + len(debug_op), "yellow")],142                     out.font_attr_segs[0])143  def testFormatTensor1DNoEllipsis(self):144    a = np.zeros(20)145    out = tensor_format.format_tensor(146        a, "a", np_printoptions={"linewidth": 40})147    cli_test_utils.assert_lines_equal_ignoring_whitespace(148        self, ["Tensor \"a\":", ""], out.lines[:2])149    self.assertEqual(repr(a).split("\n"), out.lines[2:])150    self._checkTensorMetadata(a, out.annotations)151    # Check annotations for beginning indices of the lines.152    self._checkBeginIndicesAnnotations(out, a)153  def testFormatTensor2DNoEllipsisNoRowBreak(self):154    a = np.linspace(0.0, 1.0 - 1.0 / 16.0, 16).reshape([4, 4])155    out = tensor_format.format_tensor(a, "a")156    cli_test_utils.assert_lines_equal_ignoring_whitespace(157        self, ["Tensor \"a\":", ""], out.lines[:2])158    self.assertEqual(repr(a).split("\n"), out.lines[2:])159    self._checkTensorMetadata(a, out.annotations)160    self._checkBeginIndicesAnnotations(out, a)161  def testFormatTensorSuppressingTensorName(self):162    a = np.linspace(0.0, 1.0 - 1.0 / 16.0, 16).reshape([4, 4])163    out = tensor_format.format_tensor(a, None)164    self.assertEqual(repr(a).split("\n"), out.lines)165    self._checkTensorMetadata(a, out.annotations)166    self._checkBeginIndicesAnnotations(out, a)167  def testFormatTensorWithMetadata(self):168    a = np.linspace(0.0, 1.0 - 1.0 / 16.0, 16).reshape([4, 4])169    out = tensor_format.format_tensor(a, "a", include_metadata=True)170    cli_test_utils.assert_lines_equal_ignoring_whitespace(171        self,172        ["Tensor \"a\":",173         "  dtype: float64",174         "  shape: (4, 4)",175         ""], out.lines[:4])176    self.assertEqual(repr(a).split("\n"), out.lines[4:])177    self._checkTensorMetadata(a, out.annotations)178    self._checkBeginIndicesAnnotations(out, a)179  def testFormatTensor2DNoEllipsisWithRowBreak(self):180    a = np.linspace(0.0, 1.0 - 1.0 / 40.0, 40).reshape([2, 20])181    out = tensor_format.format_tensor(182        a, "a", np_printoptions={"linewidth": 50})183    self.assertEqual(184        {"dtype": a.dtype, "shape": a.shape},185        out.annotations["tensor_metadata"])186    cli_test_utils.assert_lines_equal_ignoring_whitespace(187        self, ["Tensor \"a\":", ""], out.lines[:2])188    self.assertEqual(repr(a).split("\n"), out.lines[2:])189    self._checkTensorMetadata(a, out.annotations)190    # Check annotations for the beginning indices of the lines.191    self._checkBeginIndicesAnnotations(out, a)192  def testFormatTensor3DNoEllipsis(self):193    a = np.linspace(0.0, 1.0 - 1.0 / 24.0, 24).reshape([2, 3, 4])194    out = tensor_format.format_tensor(a, "a")195    cli_test_utils.assert_lines_equal_ignoring_whitespace(196        self, ["Tensor \"a\":", ""], out.lines[:2])197    self.assertEqual(repr(a).split("\n"), out.lines[2:])198    self._checkTensorMetadata(a, out.annotations)199    self._checkBeginIndicesAnnotations(out, a)200  def testFormatTensor3DNoEllipsisWithArgwhereHighlightWithMatches(self):201    a = np.linspace(0.0, 1.0 - 1.0 / 24.0, 24).reshape([2, 3, 4])202    lower_bound = 0.26203    upper_bound = 0.5204    def highlight_filter(x):205      return np.logical_and(x > lower_bound, x < upper_bound)206    highlight_options = tensor_format.HighlightOptions(207        highlight_filter, description="between 0.26 and 0.5")208    out = tensor_format.format_tensor(209        a, "a", highlight_options=highlight_options)210    cli_test_utils.assert_lines_equal_ignoring_whitespace(211        self,212        ["Tensor \"a\": "213         "Highlighted(between 0.26 and 0.5): 5 of 24 element(s) (20.83%)",214         ""],215        out.lines[:2])216    self.assertEqual(repr(a).split("\n"), out.lines[2:])217    self._checkTensorMetadata(a, out.annotations)218    # Check annotations for beginning indices of the lines.219    self._checkBeginIndicesAnnotations(out, a)220    self.assertAllClose(221        [0.29166667, 0.33333333, 0.375, 0.41666667, 0.45833333],222        self._extractBoldNumbers(out, 2))223  def testFormatTensor3DNoEllipsisWithArgwhereHighlightWithNoMatches(self):224    a = np.linspace(0.0, 1.0 - 1.0 / 24.0, 24).reshape([2, 3, 4])225    def highlight_filter(x):226      return x > 10.0227    highlight_options = tensor_format.HighlightOptions(highlight_filter)228    out = tensor_format.format_tensor(229        a, "a", highlight_options=highlight_options)230    cli_test_utils.assert_lines_equal_ignoring_whitespace(231        self,232        ["Tensor \"a\": Highlighted: 0 of 24 element(s) (0.00%)", ""],233        out.lines[:2])234    self.assertEqual(repr(a).split("\n"), out.lines[2:])235    self._checkTensorMetadata(a, out.annotations)236    self._checkBeginIndicesAnnotations(out, a)237    # Check font attribute segments for highlighted elements.238    for i in range(2, len(out.lines)):239      self.assertNotIn(i, out.font_attr_segs)240  def testFormatTensorWithEllipses(self):241    a = (np.arange(11 * 11 * 11) + 1000).reshape([11, 11, 11]).astype(np.int32)242    out = tensor_format.format_tensor(243        a, "a", False, np_printoptions={"threshold": 100, "edgeitems": 2})244    cli_test_utils.assert_lines_equal_ignoring_whitespace(245        self, ["Tensor \"a\":", ""], out.lines[:2])246    self.assertEqual(repr(a).split("\n"), out.lines[2:])247    self._checkTensorMetadata(a, out.annotations)248    # Check annotations for beginning indices of the lines.249    actual_row_0_0_0, _ = self._findFirst(out.lines, "1000")250    self.assertEqual({tensor_format.BEGIN_INDICES_KEY: [0, 0, 0]},251                     out.annotations[actual_row_0_0_0])252    actual_row_0_1_0, _ = self._findFirst(out.lines, "1011")253    self.assertEqual({tensor_format.BEGIN_INDICES_KEY: [0, 1, 0]},254                     out.annotations[actual_row_0_1_0])255    # Find the first line that is completely omitted.256    omitted_line = 2257    while not out.lines[omitted_line].strip().startswith("..."):258      omitted_line += 1259    self.assertEqual({tensor_format.OMITTED_INDICES_KEY: [0, 2, 0]},260                     out.annotations[omitted_line])261    actual_row_10_10_0, _ = self._findFirst(out.lines, "2320")262    self.assertEqual({tensor_format.BEGIN_INDICES_KEY: [10, 10, 0]},263                     out.annotations[actual_row_10_10_0])264    # Find the last line that is completely omitted.265    omitted_line = len(out.lines) - 1266    while not out.lines[omitted_line].strip().startswith("..."):267      omitted_line -= 1268    self.assertEqual({tensor_format.OMITTED_INDICES_KEY: [10, 2, 0]},269                     out.annotations[omitted_line])270  def testFormatUninitializedTensor(self):271    tensor_proto = tensor_pb2.TensorProto(272        dtype=types_pb2.DataType.Value("DT_FLOAT"),273        tensor_shape=tensor_shape_pb2.TensorShapeProto(274            dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)]))275    out = tensor_format.format_tensor(276        debug_data.InconvertibleTensorProto(tensor_proto, False), "a")277    self.assertEqual(["Tensor \"a\":", "", "Uninitialized tensor:"],278                     out.lines[:3])279    self.assertEqual(str(tensor_proto).split("\n"), out.lines[3:])280  def testFormatResourceTypeTensor(self):281    tensor_proto = tensor_pb2.TensorProto(282        dtype=types_pb2.DataType.Value("DT_RESOURCE"),283        tensor_shape=tensor_shape_pb2.TensorShapeProto(284            dim=[tensor_shape_pb2.TensorShapeProto.Dim(size=1)]))285    out = tensor_format.format_tensor(286        debug_data.InconvertibleTensorProto(tensor_proto), "a")287    self.assertEqual(["Tensor \"a\":", ""], out.lines[:2])288    self.assertEqual(str(tensor_proto).split("\n"), out.lines[2:])289  def testLocateTensorElement1DNoEllipsis(self):290    a = np.zeros(20)291    out = tensor_format.format_tensor(292        a, "a", np_printoptions={"linewidth": 40})293    cli_test_utils.assert_lines_equal_ignoring_whitespace(294        self, ["Tensor \"a\":", ""], out.lines[:2])295    self.assertEqual(repr(a).split("\n"), out.lines[2:])296    self._checkTensorElementLocations(out, a)297    with self.assertRaisesRegexp(298        ValueError, "Indices exceed tensor dimensions"):299      tensor_format.locate_tensor_element(out, [20])300    with self.assertRaisesRegexp(301        ValueError, "Indices contain negative"):302      tensor_format.locate_tensor_element(out, [-1])303    with self.assertRaisesRegexp(304        ValueError, "Dimensions mismatch"):305      tensor_format.locate_tensor_element(out, [0, 0])306  def testLocateTensorElement1DNoEllipsisBatchMode(self):307    a = np.zeros(20)308    out = tensor_format.format_tensor(309        a, "a", np_printoptions={"linewidth": 40})310    cli_test_utils.assert_lines_equal_ignoring_whitespace(311        self, ["Tensor \"a\":", ""], out.lines[:2])312    self.assertEqual(repr(a).split("\n"), out.lines[2:])313    self._checkTensorElementLocations(out, a)314  def testBatchModeWithErrors(self):315    a = np.zeros(20)316    out = tensor_format.format_tensor(317        a, "a", np_printoptions={"linewidth": 40})318    cli_test_utils.assert_lines_equal_ignoring_whitespace(319        self, ["Tensor \"a\":", ""], out.lines[:2])320    self.assertEqual(repr(a).split("\n"), out.lines[2:])321    with self.assertRaisesRegexp(ValueError, "Dimensions mismatch"):322      tensor_format.locate_tensor_element(out, [[0, 0], [0]])323    with self.assertRaisesRegexp(ValueError,324                                 "Indices exceed tensor dimensions"):325      tensor_format.locate_tensor_element(out, [[0], [20]])326    with self.assertRaisesRegexp(ValueError,327                                 r"Indices contain negative value\(s\)"):328      tensor_format.locate_tensor_element(out, [[0], [-1]])329    with self.assertRaisesRegexp(330        ValueError, "Input indices sets are not in ascending order"):331      tensor_format.locate_tensor_element(out, [[5], [0]])332  def testLocateTensorElement1DTinyAndNanValues(self):333    a = np.ones([3, 3]) * 1e-8334    a[1, 0] = np.nan335    a[1, 2] = np.inf336    out = tensor_format.format_tensor(337        a, "a", np_printoptions={"linewidth": 100})338    cli_test_utils.assert_lines_equal_ignoring_whitespace(339        self, ["Tensor \"a\":", ""], out.lines[:2])340    self.assertEqual(repr(a).split("\n"), out.lines[2:])341    self._checkTensorElementLocations(out, a)342  def testLocateTensorElement2DNoEllipsis(self):343    a = np.linspace(0.0, 1.0 - 1.0 / 16.0, 16).reshape([4, 4])344    out = tensor_format.format_tensor(a, "a")345    cli_test_utils.assert_lines_equal_ignoring_whitespace(346        self, ["Tensor \"a\":", ""], out.lines[:2])347    self.assertEqual(repr(a).split("\n"), out.lines[2:])348    self._checkTensorElementLocations(out, a)349    with self.assertRaisesRegexp(350        ValueError, "Indices exceed tensor dimensions"):351      tensor_format.locate_tensor_element(out, [1, 4])352    with self.assertRaisesRegexp(353        ValueError, "Indices contain negative"):354      tensor_format.locate_tensor_element(out, [-1, 2])355    with self.assertRaisesRegexp(356        ValueError, "Dimensions mismatch"):357      tensor_format.locate_tensor_element(out, [0])358  def testLocateTensorElement2DNoEllipsisWithNumericSummary(self):359    a = np.linspace(0.0, 1.0 - 1.0 / 16.0, 16).reshape([4, 4])360    out = tensor_format.format_tensor(a, "a", include_numeric_summary=True)361    cli_test_utils.assert_lines_equal_ignoring_whitespace(362        self,363        ["Tensor \"a\":",364         "",365         "Numeric summary:",366         "|  0  + | total |",367         "|  1 15 |    16 |",368         "|           min           max          mean           std |"],369        out.lines[:6])370    cli_test_utils.assert_array_lines_close(371        self, [0.0, 0.9375, 0.46875, 0.28811076429], out.lines[6:7])372    cli_test_utils.assert_array_lines_close(self, a, out.lines[8:])373    self._checkTensorElementLocations(out, a)374    with self.assertRaisesRegexp(375        ValueError, "Indices exceed tensor dimensions"):376      tensor_format.locate_tensor_element(out, [1, 4])377    with self.assertRaisesRegexp(378        ValueError, "Indices contain negative"):379      tensor_format.locate_tensor_element(out, [-1, 2])380    with self.assertRaisesRegexp(381        ValueError, "Dimensions mismatch"):382      tensor_format.locate_tensor_element(out, [0])383  def testLocateTensorElement3DWithEllipses(self):384    a = (np.arange(11 * 11 * 11) + 1000).reshape([11, 11, 11]).astype(np.int32)385    out = tensor_format.format_tensor(386        a, "a", False, np_printoptions={"threshold": 100, "edgeitems": 2})387    cli_test_utils.assert_lines_equal_ignoring_whitespace(388        self, ["Tensor \"a\":", ""], out.lines[:2])389    actual_row_0_0_0, actual_col_0_0_0 = self._findFirst(out.lines, "1000")390    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(391        out, [0, 0, 0])392    self.assertFalse(is_omitted)393    self.assertEqual(actual_row_0_0_0, row)394    self.assertEqual(actual_col_0_0_0, start_col)395    self.assertEqual(actual_col_0_0_0 + 4, end_col)396    actual_row_0_0_10, _ = self._findFirst(out.lines, "1010")397    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(398        out, [0, 0, 10])399    self.assertFalse(is_omitted)400    self.assertEqual(actual_row_0_0_10, row)401    self.assertIsNone(start_col)  # Passes ellipsis.402    self.assertIsNone(end_col)403    actual_row_0_1_0, actual_col_0_1_0 = self._findFirst(out.lines, "1011")404    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(405        out, [0, 1, 0])406    self.assertFalse(is_omitted)407    self.assertEqual(actual_row_0_1_0, row)408    self.assertEqual(actual_col_0_1_0, start_col)409    self.assertEqual(actual_col_0_1_0 + 4, end_col)410    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(411        out, [0, 2, 0])412    self.assertTrue(is_omitted)  # In omitted line.413    self.assertIsNone(start_col)414    self.assertIsNone(end_col)415    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(416        out, [0, 2, 10])417    self.assertTrue(is_omitted)  # In omitted line.418    self.assertIsNone(start_col)419    self.assertIsNone(end_col)420    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(421        out, [0, 8, 10])422    self.assertTrue(is_omitted)  # In omitted line.423    self.assertIsNone(start_col)424    self.assertIsNone(end_col)425    actual_row_0_10_1, actual_col_0_10_1 = self._findFirst(out.lines, "1111")426    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(427        out, [0, 10, 1])428    self.assertFalse(is_omitted)429    self.assertEqual(actual_row_0_10_1, row)430    self.assertEqual(actual_col_0_10_1, start_col)431    self.assertEqual(actual_col_0_10_1 + 4, end_col)432    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(433        out, [5, 1, 1])434    self.assertTrue(is_omitted)  # In omitted line.435    self.assertIsNone(start_col)436    self.assertIsNone(end_col)437    actual_row_10_10_10, _ = self._findFirst(out.lines, "2330")438    is_omitted, row, start_col, end_col = tensor_format.locate_tensor_element(439        out, [10, 10, 10])440    self.assertFalse(is_omitted)441    self.assertEqual(actual_row_10_10_10, row)442    self.assertIsNone(start_col)  # Past ellipsis.443    self.assertIsNone(end_col)444    with self.assertRaisesRegexp(445        ValueError, "Indices exceed tensor dimensions"):446      tensor_format.locate_tensor_element(out, [11, 5, 5])447    with self.assertRaisesRegexp(448        ValueError, "Indices contain negative"):449      tensor_format.locate_tensor_element(out, [-1, 5, 5])450    with self.assertRaisesRegexp(451        ValueError, "Dimensions mismatch"):452      tensor_format.locate_tensor_element(out, [5, 5])453  def testLocateTensorElement3DWithEllipsesBatchMode(self):454    a = (np.arange(11 * 11 * 11) + 1000).reshape([11, 11, 11]).astype(np.int32)455    out = tensor_format.format_tensor(456        a, "a", False, np_printoptions={"threshold": 100,457                                        "edgeitems": 2})458    cli_test_utils.assert_lines_equal_ignoring_whitespace(459        self, ["Tensor \"a\":", ""], out.lines[:2])460    self.assertEqual(repr(a).split("\n"), out.lines[2:])461    actual_row_0_0_0, actual_col_0_0_0 = self._findFirst(out.lines, "1000")462    actual_row_0_0_10, _ = self._findFirst(out.lines, "1010")463    actual_row_10_10_10, _ = self._findFirst(out.lines, "2330")464    (are_omitted, rows, start_cols,465     end_cols) = tensor_format.locate_tensor_element(out, [[0, 0, 0]])466    self.assertEqual([False], are_omitted)467    self.assertEqual([actual_row_0_0_0], rows)468    self.assertEqual([actual_col_0_0_0], start_cols)469    self.assertEqual([actual_col_0_0_0 + 4], end_cols)470    (are_omitted, rows, start_cols,471     end_cols) = tensor_format.locate_tensor_element(out,472                                                     [[0, 0, 0], [0, 0, 10]])473    self.assertEqual([False, False], are_omitted)474    self.assertEqual([actual_row_0_0_0, actual_row_0_0_10], rows)475    self.assertEqual([actual_col_0_0_0, None], start_cols)476    self.assertEqual([actual_col_0_0_0 + 4, None], end_cols)477    (are_omitted, rows, start_cols,...dao.py
Source:dao.py  
1import random2from typing import List3from sqlalchemy import create_engine, select4from sqlalchemy.orm import sessionmaker, subqueryload5from datetime import datetime6from leetcode_service.leetcode_util import ParseSlugFromUrl7from db.models import Problem, Solve, Base, Member8from db.db_constants import Constants9class DAO:10    _instance = None11    def MakeMember(self, member: Member):12        self._session.add(member)13        self._session.commit()14        return member15    def MakeProblem(self, problem: Problem):16        self._session.add(problem)17        self._session.commit()18        return problem19    def Solved(self, solvee: Member, problem: Problem):20        solution = Solve()21        solution.date = datetime.now()22        solution.problem = problem23        solution.solvee = solvee24        solution.takeaway = ''25        26        solvee.num_solutions += 127        self._session.add(solvee)28        self._session.add(solution)29        self._session.commit()30        return solution31    def UpdateTakeaway(self, solution: Solve, takeaway: str):32        solution.takeaway = takeaway33        self._session.add(solution)34        self._session.commit()35        return solution36    def DeleteSolution(self, solution):37        solvee = solution.solvee38        solvee.num_solutions -= 139        self._session.add(solvee)40        self.DeleteRow(solution)41    def DeleteRow(self, obj):42        klass = obj.__class__43        if klass in Constants.MODELS:44            self._session.delete(obj)45            self._session.commit()46            47        else:48            raise Exception(49                f"""50                Given row is not a member of the models: {51                    [klass.__name__ for klass in Constants.MODELS]52                }    53                """54            )55    def GetMember(self, discordID: str) -> Member:56        query = select(Member).where(Member.discordID == discordID)57        return self._FindFirst(query)58    def GetMemberCount(self) -> int:59        return self._session.query(Member).count()60    def GetMemberStats(self, member: Member):61        joins = self._session.query(Solve).join(Solve.problem).where(Solve.solvee == member)62        retVal = [0, 0, 0]63        for k in Constants.DIFFICULTY_MAPPING.keys():64            retVal[k] = joins.where(Problem.difficulty == k).count()65        return retVal66    def GetTopUsers(self, limit: int = 10):67        return self._session.query(Member).order_by(Member.num_solutions.desc()).limit(limit).all()68    69    def GetSolution(self, id: int) -> Solve:70        query = select(Solve).where(Solve.id == id)71        return self._FindFirst(query)72    73    def GetProblem(self, search: str, n_args: int) -> Problem:74        if search.isnumeric():75            # Query based on problem number76            problem_number = int(search)77            return self._GetProblemByNumber(problem_number)78        elif search.startswith('https'):79            # Query based on slug80            slug = ParseSlugFromUrl(search)81            return self._GetProblemBySlug(slug)82        elif n_args == 1:83            # Query based on slug84            return self._GetProblemBySlug(search)85        else:86            # Query based on title87            return self._GetProblemByTitle(search)88    def RecentProblemSolutions(self, problem: Problem = None, limit: int = 5) -> List[Solve]:89        query = select(Solve)90        if problem:91            query = query.where(Solve.problem == problem)92        query = query.order_by(Solve.date.desc()).limit(limit).options(subqueryload(Solve.solvee))93        return self._session.execute(query).scalars().all()94    def RecentUserSolutions(self, solvee: Member = None, limit: int = 5) -> List[Solve]:95        query = select(Solve)96        if solvee:97            query = query.where(Solve.solvee == solvee)98        query = query.order_by(Solve.date.desc()).limit(limit).options(subqueryload(Solve.problem))99        return self._session.execute(query).scalars().all()100    def GetRandomProblem(self, difficulty_filter = None, premium_filter = None) -> Problem:101        query = self._session.query(Problem)102        if premium_filter is False:103            query = query.where(Problem.premium == premium_filter)104        105        if difficulty_filter is not None:106            query = query.where(Problem.difficulty == difficulty_filter)107        108        row_count = query.count()109        return query.order_by(Problem.id).limit(1).offset(random.randint(0, row_count-1)).first()110    def _GetProblemByNumber(self, number: int):111        query = select(Problem).where(Problem.problem_number == number)112        return self._FindFirst(query)113    114    def _GetProblemBySlug(self, slug: str):115        query = select(Problem).where(Problem.slug == slug)116        return self._FindFirst(query)117    118    def _GetProblemByTitle(self, title: str):119        query = select(Problem).where(Problem.problem_name == title)120        return self._FindFirst(query)121    def _FindFirst(self, query):122        return self._session.execute(query.limit(1)).scalars().first()123    def __new__(cls):124        if cls._instance is None:125            cls._instance = super(DAO, cls).__new__(cls)126            127            engine = create_engine(Constants.CONNECTION_URL, pool_size=300, pool_pre_ping=True)            128            Base.metadata.create_all(bind=engine)129            Session = sessionmaker(bind=engine)130            cls._session = Session()131        return cls._instance132    def __del__(cls):...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
