language
stringclasses
1 value
repo
stringclasses
346 values
path
stringlengths
6
201
class_span
dict
source
stringlengths
21
2.38M
target
stringlengths
1
96
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/sensors/test_ecs.py
{ "start": 8630, "end": 11738 }
class ____(EcsBaseTestCase): @pytest.mark.parametrize( ("return_state", "expected"), [ ("PROVISIONING", False), ("PENDING", False), ("ACTIVATING", False), ("RUNNING", True), ("DEACTIVATING", False), ("STOPPING", False), ("DEPROVISIONING", False), ("NONE", False), ], ) def test_default_values_poke(self, return_state, expected): task = self.create_rendered_task(EcsTaskStateSensor, cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN) with mock.patch.object(task.hook, "get_task_state") as m: m.return_value = return_state assert task.poke({}) == expected m.assert_called_once_with(cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN) @pytest.mark.parametrize("return_state", ["STOPPED"]) def test_default_values_terminal_state(self, return_state): task = self.create_rendered_task(EcsTaskStateSensor, cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN) with mock.patch.object(task.hook, "get_task_state") as m: m.return_value = return_state with pytest.raises(AirflowException, match="Terminal state reached"): task.poke({}) m.assert_called_once_with(cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN) @pytest.mark.parametrize( ("target_state", "return_state", "expected"), [ (EcsTaskStates.RUNNING, "RUNNING", True), (EcsTaskStates.DEACTIVATING, "DEACTIVATING", True), (EcsTaskStates.NONE, "PENDING", False), (EcsTaskStates.STOPPING, "NONE", False), ], ) def test_custom_values_poke(self, target_state, return_state, expected): task = self.create_rendered_task( EcsTaskStateSensor, cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN, target_state=target_state ) with mock.patch.object(task.hook, "get_task_state") as m: m.return_value = return_state assert task.poke({}) == expected m.assert_called_once_with(cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN) @pytest.mark.parametrize( ("failure_states", "return_state"), [ ({EcsTaskStates.RUNNING}, "RUNNING"), ({EcsTaskStates.RUNNING, EcsTaskStates.DEACTIVATING}, "DEACTIVATING"), ({EcsTaskStates.RUNNING, EcsTaskStates.DEACTIVATING}, "RUNNING"), ], ) def test_custom_values_terminal_state(self, failure_states, return_state): task = self.create_rendered_task( EcsTaskStateSensor, cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN, target_state=EcsTaskStates.NONE, failure_states=failure_states, ) with mock.patch.object(task.hook, "get_task_state") as m: m.return_value = return_state with pytest.raises(AirflowException, match="Terminal state reached"): task.poke({}) m.assert_called_once_with(cluster=TEST_CLUSTER_NAME, task=TEST_TASK_ARN)
TestEcsTaskStateSensor
python
sympy__sympy
sympy/vector/implicitregion.py
{ "start": 614, "end": 16158 }
class ____(Basic): """ Represents an implicit region in space. Examples ======== >>> from sympy import Eq >>> from sympy.abc import x, y, z, t >>> from sympy.vector import ImplicitRegion >>> ImplicitRegion((x, y), x**2 + y**2 - 4) ImplicitRegion((x, y), x**2 + y**2 - 4) >>> ImplicitRegion((x, y), Eq(y*x, 1)) ImplicitRegion((x, y), x*y - 1) >>> parabola = ImplicitRegion((x, y), y**2 - 4*x) >>> parabola.degree 2 >>> parabola.equation -4*x + y**2 >>> parabola.rational_parametrization(t) (4/t**2, 4/t) >>> r = ImplicitRegion((x, y, z), Eq(z, x**2 + y**2)) >>> r.variables (x, y, z) >>> r.singular_points() EmptySet >>> r.regular_point() (-10, -10, 200) Parameters ========== variables : tuple to map variables in implicit equation to base scalars. equation : An expression or Eq denoting the implicit equation of the region. """ def __new__(cls, variables, equation): if not isinstance(variables, Tuple): variables = Tuple(*variables) if isinstance(equation, Eq): equation = equation.lhs - equation.rhs return super().__new__(cls, variables, equation) @property def variables(self): return self.args[0] @property def equation(self): return self.args[1] @property def degree(self): return total_degree(self.equation) def regular_point(self): """ Returns a point on the implicit region. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.vector import ImplicitRegion >>> circle = ImplicitRegion((x, y), (x + 2)**2 + (y - 3)**2 - 16) >>> circle.regular_point() (-2, -1) >>> parabola = ImplicitRegion((x, y), x**2 - 4*y) >>> parabola.regular_point() (0, 0) >>> r = ImplicitRegion((x, y, z), (x + y + z)**4) >>> r.regular_point() (-10, -10, 20) References ========== - Erik Hillgarter, "Rational Points on Conics", Diploma Thesis, RISC-Linz, J. Kepler Universitat Linz, 1996. Available: https://www3.risc.jku.at/publications/download/risc_1355/Rational%20Points%20on%20Conics.pdf """ equation = self.equation if len(self.variables) == 1: return (list(solveset(equation, self.variables[0], domain=S.Reals))[0],) elif len(self.variables) == 2: if self.degree == 2: coeffs = a, b, c, d, e, f = conic_coeff(self.variables, equation) if b**2 == 4*a*c: x_reg, y_reg = self._regular_point_parabola(*coeffs) else: x_reg, y_reg = self._regular_point_ellipse(*coeffs) return x_reg, y_reg if len(self.variables) == 3: x, y, z = self.variables for x_reg in range(-10, 10): for y_reg in range(-10, 10): if not solveset(equation.subs({x: x_reg, y: y_reg}), self.variables[2], domain=S.Reals).is_empty: return (x_reg, y_reg, list(solveset(equation.subs({x: x_reg, y: y_reg})))[0]) if len(self.singular_points()) != 0: return list[self.singular_points()][0] raise NotImplementedError() def _regular_point_parabola(self, a, b, c, d, e, f): ok = (a, d) != (0, 0) and (c, e) != (0, 0) and b**2 == 4*a*c and (a, c) != (0, 0) if not ok: raise ValueError("Rational Point on the conic does not exist") if a != 0: d_dash, f_dash = (4*a*e - 2*b*d, 4*a*f - d**2) if d_dash != 0: y_reg = -f_dash/d_dash x_reg = -(d + b*y_reg)/(2*a) else: ok = False elif c != 0: d_dash, f_dash = (4*c*d - 2*b*e, 4*c*f - e**2) if d_dash != 0: x_reg = -f_dash/d_dash y_reg = -(e + b*x_reg)/(2*c) else: ok = False if ok: return x_reg, y_reg else: raise ValueError("Rational Point on the conic does not exist") def _regular_point_ellipse(self, a, b, c, d, e, f): D = 4*a*c - b**2 ok = D if not ok: raise ValueError("Rational Point on the conic does not exist") if a == 0 and c == 0: K = -1 L = 4*(d*e - b*f) elif c != 0: K = D L = 4*c**2*d**2 - 4*b*c*d*e + 4*a*c*e**2 + 4*b**2*c*f - 16*a*c**2*f else: K = D L = 4*a**2*e**2 - 4*b*a*d*e + 4*b**2*a*f ok = L != 0 and not(K > 0 and L < 0) if not ok: raise ValueError("Rational Point on the conic does not exist") K = Rational(K).limit_denominator(10**12) L = Rational(L).limit_denominator(10**12) k1, k2 = K.p, K.q l1, l2 = L.p, L.q g = gcd(k2, l2) a1 = (l2*k2)/g b1 = (k1*l2)/g c1 = -(l1*k2)/g a2 = sign(a1)*core(abs(a1), 2) r1 = sqrt(a1/a2) b2 = sign(b1)*core(abs(b1), 2) r2 = sqrt(b1/b2) c2 = sign(c1)*core(abs(c1), 2) r3 = sqrt(c1/c2) g = gcd(gcd(a2, b2), c2) a2 = a2/g b2 = b2/g c2 = c2/g g1 = gcd(a2, b2) a2 = a2/g1 b2 = b2/g1 c2 = c2*g1 g2 = gcd(a2,c2) a2 = a2/g2 b2 = b2*g2 c2 = c2/g2 g3 = gcd(b2, c2) a2 = a2*g3 b2 = b2/g3 c2 = c2/g3 x, y, z = symbols("x y z") eq = a2*x**2 + b2*y**2 + c2*z**2 solutions = diophantine(eq) if len(solutions) == 0: raise ValueError("Rational Point on the conic does not exist") flag = False for sol in solutions: syms = Tuple(*sol).free_symbols rep = dict.fromkeys(syms, 3) sol_z = sol[2] if sol_z == 0: flag = True continue if not isinstance(sol_z, (int, Integer)): syms_z = sol_z.free_symbols if len(syms_z) == 1: p = next(iter(syms_z)) p_values = Complement(S.Integers, solveset(Eq(sol_z, 0), p, S.Integers)) rep[p] = next(iter(p_values)) if len(syms_z) == 2: p, q = list(ordered(syms_z)) for i in S.Integers: subs_sol_z = sol_z.subs(p, i) q_values = Complement(S.Integers, solveset(Eq(subs_sol_z, 0), q, S.Integers)) if not q_values.is_empty: rep[p] = i rep[q] = next(iter(q_values)) break if len(syms) != 0: x, y, z = tuple(s.subs(rep) for s in sol) else: x, y, z = sol flag = False break if flag: raise ValueError("Rational Point on the conic does not exist") x = (x*g3)/r1 y = (y*g2)/r2 z = (z*g1)/r3 x = x/z y = y/z if a == 0 and c == 0: x_reg = (x + y - 2*e)/(2*b) y_reg = (x - y - 2*d)/(2*b) elif c != 0: x_reg = (x - 2*d*c + b*e)/K y_reg = (y - b*x_reg - e)/(2*c) else: y_reg = (x - 2*e*a + b*d)/K x_reg = (y - b*y_reg - d)/(2*a) return x_reg, y_reg def singular_points(self): """ Returns a set of singular points of the region. The singular points are those points on the region where all partial derivatives vanish. Examples ======== >>> from sympy.abc import x, y >>> from sympy.vector import ImplicitRegion >>> I = ImplicitRegion((x, y), (y-1)**2 -x**3 + 2*x**2 -x) >>> I.singular_points() {(1, 1)} """ eq_list = [self.equation] for var in self.variables: eq_list += [diff(self.equation, var)] return nonlinsolve(eq_list, list(self.variables)) def multiplicity(self, point): """ Returns the multiplicity of a singular point on the region. A singular point (x,y) of region is said to be of multiplicity m if all the partial derivatives off to order m - 1 vanish there. Examples ======== >>> from sympy.abc import x, y, z >>> from sympy.vector import ImplicitRegion >>> I = ImplicitRegion((x, y, z), x**2 + y**3 - z**4) >>> I.singular_points() {(0, 0, 0)} >>> I.multiplicity((0, 0, 0)) 2 """ if isinstance(point, Point): point = point.args modified_eq = self.equation for i, var in enumerate(self.variables): modified_eq = modified_eq.subs(var, var + point[i]) modified_eq = expand(modified_eq) if len(modified_eq.args) != 0: terms = modified_eq.args m = min(total_degree(term) for term in terms) else: terms = modified_eq m = total_degree(terms) return m def rational_parametrization(self, parameters=('t', 's'), reg_point=None): """ Returns the rational parametrization of implicit region. Examples ======== >>> from sympy import Eq >>> from sympy.abc import x, y, z, s, t >>> from sympy.vector import ImplicitRegion >>> parabola = ImplicitRegion((x, y), y**2 - 4*x) >>> parabola.rational_parametrization() (4/t**2, 4/t) >>> circle = ImplicitRegion((x, y), Eq(x**2 + y**2, 4)) >>> circle.rational_parametrization() (4*t/(t**2 + 1), 4*t**2/(t**2 + 1) - 2) >>> I = ImplicitRegion((x, y), x**3 + x**2 - y**2) >>> I.rational_parametrization() (t**2 - 1, t*(t**2 - 1)) >>> cubic_curve = ImplicitRegion((x, y), x**3 + x**2 - y**2) >>> cubic_curve.rational_parametrization(parameters=(t)) (t**2 - 1, t*(t**2 - 1)) >>> sphere = ImplicitRegion((x, y, z), x**2 + y**2 + z**2 - 4) >>> sphere.rational_parametrization(parameters=(t, s)) (-2 + 4/(s**2 + t**2 + 1), 4*s/(s**2 + t**2 + 1), 4*t/(s**2 + t**2 + 1)) For some conics, regular_points() is unable to find a point on curve. To calulcate the parametric representation in such cases, user need to determine a point on the region and pass it using reg_point. >>> c = ImplicitRegion((x, y), (x - 1/2)**2 + (y)**2 - (1/4)**2) >>> c.rational_parametrization(reg_point=(3/4, 0)) (0.75 - 0.5/(t**2 + 1), -0.5*t/(t**2 + 1)) References ========== - Christoph M. Hoffmann, "Conversion Methods between Parametric and Implicit Curves and Surfaces", Purdue e-Pubs, 1990. Available: https://docs.lib.purdue.edu/cgi/viewcontent.cgi?article=1827&context=cstech """ equation = self.equation degree = self.degree if degree == 1: if len(self.variables) == 1: return (equation,) elif len(self.variables) == 2: x, y = self.variables y_par = list(solveset(equation, y))[0] return x, y_par else: raise NotImplementedError() point = () # Finding the (n - 1) fold point of the monoid of degree if degree == 2: # For degree 2 curves, either a regular point or a singular point can be used. if reg_point is not None: # Using point provided by the user as regular point point = reg_point else: if len(self.singular_points()) != 0: point = list(self.singular_points())[0] else: point = self.regular_point() if len(self.singular_points()) != 0: singular_points = self.singular_points() for spoint in singular_points: syms = Tuple(*spoint).free_symbols rep = dict.fromkeys(syms, 2) if len(syms) != 0: spoint = tuple(s.subs(rep) for s in spoint) if self.multiplicity(spoint) == degree - 1: point = spoint break if len(point) == 0: # The region in not a monoid raise NotImplementedError() modified_eq = equation # Shifting the region such that fold point moves to origin for i, var in enumerate(self.variables): modified_eq = modified_eq.subs(var, var + point[i]) modified_eq = expand(modified_eq) hn = hn_1 = 0 for term in modified_eq.args: if total_degree(term) == degree: hn += term else: hn_1 += term hn_1 = -1*hn_1 if not isinstance(parameters, tuple): parameters = (parameters,) if len(self.variables) == 2: parameter1 = parameters[0] if parameter1 == 's': # To avoid name conflict between parameters s = _symbol('s_', real=True) else: s = _symbol('s', real=True) t = _symbol(parameter1, real=True) hn = hn.subs({self.variables[0]: s, self.variables[1]: t}) hn_1 = hn_1.subs({self.variables[0]: s, self.variables[1]: t}) x_par = (s*(hn_1/hn)).subs(s, 1) + point[0] y_par = (t*(hn_1/hn)).subs(s, 1) + point[1] return x_par, y_par elif len(self.variables) == 3: parameter1, parameter2 = parameters if 'r' in parameters: # To avoid name conflict between parameters r = _symbol('r_', real=True) else: r = _symbol('r', real=True) s = _symbol(parameter2, real=True) t = _symbol(parameter1, real=True) hn = hn.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t}) hn_1 = hn_1.subs({self.variables[0]: r, self.variables[1]: s, self.variables[2]: t}) x_par = (r*(hn_1/hn)).subs(r, 1) + point[0] y_par = (s*(hn_1/hn)).subs(r, 1) + point[1] z_par = (t*(hn_1/hn)).subs(r, 1) + point[2] return x_par, y_par, z_par raise NotImplementedError() def conic_coeff(variables, equation): if total_degree(equation) != 2: raise ValueError() x = variables[0] y = variables[1] equation = expand(equation) a = equation.coeff(x**2) b = equation.coeff(x*y) c = equation.coeff(y**2) d = equation.coeff(x, 1).coeff(y, 0) e = equation.coeff(y, 1).coeff(x, 0) f = equation.coeff(x, 0).coeff(y, 0) return a, b, c, d, e, f
ImplicitRegion
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/openblas/package.py
{ "start": 217, "end": 1021 }
class ____(Package): """OpenBLAS: An optimized BLAS library""" homepage = "http://www.openblas.net" url = "http://github.com/xianyi/OpenBLAS/archive/v0.2.15.tar.gz" version("0.2.16", md5="b1190f3d3471685f17cfd1ec1d252ac9") version("0.2.15", md5="b1190f3d3471685f17cfd1ec1d252ac9") version("0.2.14", md5="b1190f3d3471685f17cfd1ec1d252ac9") version("0.2.13", md5="b1190f3d3471685f17cfd1ec1d252ac9") variant("shared", default=True, description="Build shared libraries") depends_on("c", type="build") depends_on("fortran", type="build") # See #20019 for this conflict conflicts("%gcc@:4.4", when="@0.2.14:") # To ensure test works with newer gcc versions conflicts("%gcc@:10.1", when="@0.2.16:") depends_on("perl") provides("blas")
Openblas
python
astropy__astropy
astropy/io/ascii/core.py
{ "start": 57210, "end": 66609 }
class ____(DefaultSplitter): def process_line(self, line: str) -> str: """Replace tab with space within ``line`` while respecting quoted substrings.""" newline = [] in_quote = False lastchar = None for char in line: if char == self.quotechar and ( self.escapechar is None or lastchar != self.escapechar ): in_quote = not in_quote if char == "\t" and not in_quote: char = " " lastchar = char newline.append(char) return "".join(newline) extra_reader_pars = ( "delimiter", "comment", "quotechar", "header_start", "data_start", "data_end", "converters", "encoding", "data_splitter_cls", "header_splitter_cls", "names", "include_names", "exclude_names", "strict_names", "fill_values", "fill_include_names", "fill_exclude_names", ) def _get_reader(reader_cls, inputter_cls=None, outputter_cls=None, **kwargs): """Initialize a table reader allowing for common customizations. See ui.get_reader() for param docs. This routine is for internal (package) use only and is useful because it depends only on the "core" module. """ from .fastbasic import FastBasic if issubclass(reader_cls, FastBasic): # Fast readers handle args separately if inputter_cls is not None: kwargs["inputter_cls"] = inputter_cls return reader_cls(**kwargs) # If user explicitly passed a fast reader with enable='force' # (e.g. by passing non-default options), raise an error for slow readers if "fast_reader" in kwargs: if kwargs["fast_reader"]["enable"] == "force": raise ParameterError( "fast_reader required with " "{}, but this is not a fast C reader: {}".format( kwargs["fast_reader"], reader_cls ) ) else: del kwargs["fast_reader"] # Otherwise ignore fast_reader parameter reader_kwargs = {k: v for k, v in kwargs.items() if k not in extra_reader_pars} reader = reader_cls(**reader_kwargs) if inputter_cls is not None: reader.inputter = inputter_cls() if outputter_cls is not None: reader.outputter = outputter_cls() # Issue #855 suggested to set data_start to header_start + default_header_length # Thus, we need to retrieve this from the class definition before resetting these numbers. try: default_header_length = reader.data.start_line - reader.header.start_line except TypeError: # Start line could be None or an instancemethod default_header_length = None # csv.reader is hard-coded to recognise either '\r' or '\n' as end-of-line, # therefore DefaultSplitter cannot handle these as delimiters. if "delimiter" in kwargs: if kwargs["delimiter"] in ("\n", "\r", "\r\n"): reader.header.splitter = BaseSplitter() reader.data.splitter = BaseSplitter() reader.header.splitter.delimiter = kwargs["delimiter"] reader.data.splitter.delimiter = kwargs["delimiter"] if "comment" in kwargs: reader.header.comment = kwargs["comment"] reader.data.comment = kwargs["comment"] if "quotechar" in kwargs: reader.header.splitter.quotechar = kwargs["quotechar"] reader.data.splitter.quotechar = kwargs["quotechar"] if "data_start" in kwargs: reader.data.start_line = kwargs["data_start"] if "data_end" in kwargs: reader.data.end_line = kwargs["data_end"] if "header_start" in kwargs: if reader.header.start_line is not None: reader.header.start_line = kwargs["header_start"] # For FixedWidthTwoLine the data_start is calculated relative to the position line. # However, position_line is given as absolute number and not relative to header_start. # So, ignore this Reader here. if ( ("data_start" not in kwargs) and (default_header_length is not None) and reader._format_name not in ["fixed_width_two_line", "commented_header"] ): reader.data.start_line = ( reader.header.start_line + default_header_length ) elif kwargs["header_start"] is not None: # User trying to set a None header start to some value other than None raise ValueError("header_start cannot be modified for this Reader") if "converters" in kwargs: reader.outputter.converters = kwargs["converters"] if "data_splitter_cls" in kwargs: reader.data.splitter = kwargs["data_splitter_cls"]() if "header_splitter_cls" in kwargs: reader.header.splitter = kwargs["header_splitter_cls"]() if "names" in kwargs: reader.names = kwargs["names"] if None in reader.names: raise TypeError("Cannot have None for column name") if len(set(reader.names)) != len(reader.names): raise ValueError("Duplicate column names") if "include_names" in kwargs: reader.include_names = kwargs["include_names"] if "exclude_names" in kwargs: reader.exclude_names = kwargs["exclude_names"] # Strict names is normally set only within the guessing process to # indicate that column names cannot be numeric or have certain # characters at the beginning or end. It gets used in # BaseHeader.check_column_names(). if "strict_names" in kwargs: reader.strict_names = kwargs["strict_names"] if "fill_values" in kwargs: reader.data.fill_values = kwargs["fill_values"] if "fill_include_names" in kwargs: reader.data.fill_include_names = kwargs["fill_include_names"] if "fill_exclude_names" in kwargs: reader.data.fill_exclude_names = kwargs["fill_exclude_names"] if "encoding" in kwargs: reader.encoding = kwargs["encoding"] reader.inputter.encoding = kwargs["encoding"] return reader extra_writer_pars = ( "delimiter", "comment", "quotechar", "formats", "strip_whitespace", "names", "include_names", "exclude_names", "fill_values", "fill_include_names", "fill_exclude_names", ) def _get_writer(writer_cls, fast_writer, **kwargs): """Initialize a table writer allowing for common customizations. This routine is for internal (package) use only and is useful because it depends only on the "core" module. """ from .fastbasic import FastBasic # A value of None for fill_values imply getting the default string # representation of masked values (depending on the writer class), but the # machinery expects a list. The easiest here is to just pop the value off, # i.e. fill_values=None is the same as not providing it at all. if "fill_values" in kwargs and kwargs["fill_values"] is None: del kwargs["fill_values"] if issubclass(writer_cls, FastBasic): # Fast writers handle args separately return writer_cls(**kwargs) elif fast_writer and f"fast_{writer_cls._format_name}" in FAST_CLASSES: # Switch to fast writer kwargs["fast_writer"] = fast_writer return FAST_CLASSES[f"fast_{writer_cls._format_name}"](**kwargs) writer_kwargs = {k: v for k, v in kwargs.items() if k not in extra_writer_pars} writer = writer_cls(**writer_kwargs) if "delimiter" in kwargs: writer.header.splitter.delimiter = kwargs["delimiter"] writer.data.splitter.delimiter = kwargs["delimiter"] if "comment" in kwargs: writer.header.write_comment = kwargs["comment"] writer.data.write_comment = kwargs["comment"] if "quotechar" in kwargs: writer.header.splitter.quotechar = kwargs["quotechar"] writer.data.splitter.quotechar = kwargs["quotechar"] if "formats" in kwargs: writer.data.formats = kwargs["formats"] if "strip_whitespace" in kwargs: if kwargs["strip_whitespace"]: # Restore the default SplitterClass process_val method which strips # whitespace. This may have been changed in the Writer # initialization (e.g. Rdb and Tab) writer.data.splitter.process_val = operator.methodcaller("strip", " \t") else: writer.data.splitter.process_val = None if "names" in kwargs: writer.header.names = kwargs["names"] if "include_names" in kwargs: writer.include_names = kwargs["include_names"] if "exclude_names" in kwargs: writer.exclude_names = kwargs["exclude_names"] if "fill_values" in kwargs: # Prepend user-specified values to the class default. with suppress(TypeError, IndexError): # Test if it looks like (match, replace_string, optional_colname), # in which case make it a list kwargs["fill_values"][1] + "" kwargs["fill_values"] = [kwargs["fill_values"]] writer.data.fill_values = kwargs["fill_values"] + writer.data.fill_values if "fill_include_names" in kwargs: writer.data.fill_include_names = kwargs["fill_include_names"] if "fill_exclude_names" in kwargs: writer.data.fill_exclude_names = kwargs["fill_exclude_names"] return writer
WhitespaceSplitter
python
sqlalchemy__sqlalchemy
test/orm/test_core_compilation.py
{ "start": 64420, "end": 64503 }
class ____(_poly_fixtures._Polymorphic): run_setup_mappers = "once"
InheritedTest
python
joke2k__faker
faker/providers/company/tl_PH/__init__.py
{ "start": 49, "end": 154 }
class ____(FilPhProvider): """No difference from Company Provider for fil_PH locale""" pass
Provider
python
apache__thrift
test/py/TestServer.py
{ "start": 5845, "end": 6101 }
class ____(object): def secondtestString(self, argument): return "testString(\"" + argument + "\")" # LAST_SEQID is a global because we have one transport and multiple protocols # running on it (when multiplexed) LAST_SEQID = None
SecondHandler
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_kansas_zip.py
{ "start": 1735, "end": 4062 }
class ____(ColumnMapExpectation): """Expect values in this column to be valid Kansas zipcodes. See https://pypi.org/project/zipcodes/ for more information. """ # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [ { "data": { "valid_kansas_zip": ["67031", "67519", "67635", "66027"], "invalid_kansas_zip": ["-10000", "1234", "99999", "25487"], }, "tests": [ { "title": "basic_positive_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "valid_kansas_zip"}, "out": {"success": True}, }, { "title": "basic_negative_test", "exact_match_out": False, "include_in_gallery": True, "in": {"column": "invalid_kansas_zip"}, "out": {"success": False}, }, ], } ] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. map_metric = "column_values.valid_kansas_zip" # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ("mostly",) # This dictionary contains default values for any parameters that should have default values default_kwarg_values = {} # This object contains metadata for display in the public Gallery library_metadata = { "maturity": "experimental", # "experimental", "beta", or "production" "tags": [ "hackathon", "typed-entities", ], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@luismdiaz01", "@derekma73", # Don't forget to add your github handle here! ], "requirements": ["zipcodes"], } if __name__ == "__main__": ExpectColumnValuesToBeValidKansasZip().print_diagnostic_checklist()
ExpectColumnValuesToBeValidKansasZip
python
paramiko__paramiko
paramiko/sftp_si.py
{ "start": 948, "end": 12544 }
class ____: """ This class defines an interface for controlling the behavior of paramiko when using the `.SFTPServer` subsystem to provide an SFTP server. Methods on this class are called from the SFTP session's thread, so you can block as long as necessary without affecting other sessions (even other SFTP sessions). However, raising an exception will usually cause the SFTP session to abruptly end, so you will usually want to catch exceptions and return an appropriate error code. All paths are in string form instead of unicode because not all SFTP clients & servers obey the requirement that paths be encoded in UTF-8. """ def __init__(self, server, *args, **kwargs): """ Create a new SFTPServerInterface object. This method does nothing by default and is meant to be overridden by subclasses. :param .ServerInterface server: the server object associated with this channel and SFTP subsystem """ super().__init__(*args, **kwargs) def session_started(self): """ The SFTP server session has just started. This method is meant to be overridden to perform any necessary setup before handling callbacks from SFTP operations. """ pass def session_ended(self): """ The SFTP server session has just ended, either cleanly or via an exception. This method is meant to be overridden to perform any necessary cleanup before this `.SFTPServerInterface` object is destroyed. """ pass def open(self, path, flags, attr): """ Open a file on the server and create a handle for future operations on that file. On success, a new object subclassed from `.SFTPHandle` should be returned. This handle will be used for future operations on the file (read, write, etc). On failure, an error code such as ``SFTP_PERMISSION_DENIED`` should be returned. ``flags`` contains the requested mode for opening (read-only, write-append, etc) as a bitset of flags from the ``os`` module: - ``os.O_RDONLY`` - ``os.O_WRONLY`` - ``os.O_RDWR`` - ``os.O_APPEND`` - ``os.O_CREAT`` - ``os.O_TRUNC`` - ``os.O_EXCL`` (One of ``os.O_RDONLY``, ``os.O_WRONLY``, or ``os.O_RDWR`` will always be set.) The ``attr`` object contains requested attributes of the file if it has to be created. Some or all attribute fields may be missing if the client didn't specify them. .. note:: The SFTP protocol defines all files to be in "binary" mode. There is no equivalent to Python's "text" mode. :param str path: the requested path (relative or absolute) of the file to be opened. :param int flags: flags or'd together from the ``os`` module indicating the requested mode for opening the file. :param .SFTPAttributes attr: requested attributes of the file if it is newly created. :return: a new `.SFTPHandle` or error code. """ return SFTP_OP_UNSUPPORTED def list_folder(self, path): """ Return a list of files within a given folder. The ``path`` will use posix notation (``"/"`` separates folder names) and may be an absolute or relative path. The list of files is expected to be a list of `.SFTPAttributes` objects, which are similar in structure to the objects returned by ``os.stat``. In addition, each object should have its ``filename`` field filled in, since this is important to a directory listing and not normally present in ``os.stat`` results. The method `.SFTPAttributes.from_stat` will usually do what you want. In case of an error, you should return one of the ``SFTP_*`` error codes, such as ``SFTP_PERMISSION_DENIED``. :param str path: the requested path (relative or absolute) to be listed. :return: a list of the files in the given folder, using `.SFTPAttributes` objects. .. note:: You should normalize the given ``path`` first (see the `os.path` module) and check appropriate permissions before returning the list of files. Be careful of malicious clients attempting to use relative paths to escape restricted folders, if you're doing a direct translation from the SFTP server path to your local filesystem. """ return SFTP_OP_UNSUPPORTED def stat(self, path): """ Return an `.SFTPAttributes` object for a path on the server, or an error code. If your server supports symbolic links (also known as "aliases"), you should follow them. (`lstat` is the corresponding call that doesn't follow symlinks/aliases.) :param str path: the requested path (relative or absolute) to fetch file statistics for. :return: an `.SFTPAttributes` object for the given file, or an SFTP error code (like ``SFTP_PERMISSION_DENIED``). """ return SFTP_OP_UNSUPPORTED def lstat(self, path): """ Return an `.SFTPAttributes` object for a path on the server, or an error code. If your server supports symbolic links (also known as "aliases"), you should not follow them -- instead, you should return data on the symlink or alias itself. (`stat` is the corresponding call that follows symlinks/aliases.) :param str path: the requested path (relative or absolute) to fetch file statistics for. :type path: str :return: an `.SFTPAttributes` object for the given file, or an SFTP error code (like ``SFTP_PERMISSION_DENIED``). """ return SFTP_OP_UNSUPPORTED def remove(self, path): """ Delete a file, if possible. :param str path: the requested path (relative or absolute) of the file to delete. :return: an SFTP error code `int` like ``SFTP_OK``. """ return SFTP_OP_UNSUPPORTED def rename(self, oldpath, newpath): """ Rename (or move) a file. The SFTP specification implies that this method can be used to move an existing file into a different folder, and since there's no other (easy) way to move files via SFTP, it's probably a good idea to implement "move" in this method too, even for files that cross disk partition boundaries, if at all possible. .. note:: You should return an error if a file with the same name as ``newpath`` already exists. (The rename operation should be non-desctructive.) .. note:: This method implements 'standard' SFTP ``RENAME`` behavior; those seeking the OpenSSH "POSIX rename" extension behavior should use `posix_rename`. :param str oldpath: the requested path (relative or absolute) of the existing file. :param str newpath: the requested new path of the file. :return: an SFTP error code `int` like ``SFTP_OK``. """ return SFTP_OP_UNSUPPORTED def posix_rename(self, oldpath, newpath): """ Rename (or move) a file, following posix conventions. If newpath already exists, it will be overwritten. :param str oldpath: the requested path (relative or absolute) of the existing file. :param str newpath: the requested new path of the file. :return: an SFTP error code `int` like ``SFTP_OK``. :versionadded: 2.2 """ return SFTP_OP_UNSUPPORTED def mkdir(self, path, attr): """ Create a new directory with the given attributes. The ``attr`` object may be considered a "hint" and ignored. The ``attr`` object will contain only those fields provided by the client in its request, so you should use ``hasattr`` to check for the presence of fields before using them. In some cases, the ``attr`` object may be completely empty. :param str path: requested path (relative or absolute) of the new folder. :param .SFTPAttributes attr: requested attributes of the new folder. :return: an SFTP error code `int` like ``SFTP_OK``. """ return SFTP_OP_UNSUPPORTED def rmdir(self, path): """ Remove a directory if it exists. The ``path`` should refer to an existing, empty folder -- otherwise this method should return an error. :param str path: requested path (relative or absolute) of the folder to remove. :return: an SFTP error code `int` like ``SFTP_OK``. """ return SFTP_OP_UNSUPPORTED def chattr(self, path, attr): """ Change the attributes of a file. The ``attr`` object will contain only those fields provided by the client in its request, so you should check for the presence of fields before using them. :param str path: requested path (relative or absolute) of the file to change. :param attr: requested attributes to change on the file (an `.SFTPAttributes` object) :return: an error code `int` like ``SFTP_OK``. """ return SFTP_OP_UNSUPPORTED def canonicalize(self, path): """ Return the canonical form of a path on the server. For example, if the server's home folder is ``/home/foo``, the path ``"../betty"`` would be canonicalized to ``"/home/betty"``. Note the obvious security issues: if you're serving files only from a specific folder, you probably don't want this method to reveal path names outside that folder. You may find the Python methods in ``os.path`` useful, especially ``os.path.normpath`` and ``os.path.realpath``. The default implementation returns ``os.path.normpath('/' + path)``. """ if os.path.isabs(path): out = os.path.normpath(path) else: out = os.path.normpath("/" + path) if sys.platform == "win32": # on windows, normalize backslashes to sftp/posix format out = out.replace("\\", "/") return out def readlink(self, path): """ Return the target of a symbolic link (or shortcut) on the server. If the specified path doesn't refer to a symbolic link, an error should be returned. :param str path: path (relative or absolute) of the symbolic link. :return: the target `str` path of the symbolic link, or an error code like ``SFTP_NO_SUCH_FILE``. """ return SFTP_OP_UNSUPPORTED def symlink(self, target_path, path): """ Create a symbolic link on the server, as new pathname ``path``, with ``target_path`` as the target of the link. :param str target_path: path (relative or absolute) of the target for this new symbolic link. :param str path: path (relative or absolute) of the symbolic link to create. :return: an error code `int` like ``SFTP_OK``. """ return SFTP_OP_UNSUPPORTED
SFTPServerInterface
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_contextlib.py
{ "start": 42535, "end": 46034 }
class ____(ExceptionIsLikeMixin, __TestCase): @support.requires_docstrings def test_instance_docs(self): # Issue 19330: ensure context manager instances have good docstrings cm_docstring = suppress.__doc__ obj = suppress() self.assertEqual(obj.__doc__, cm_docstring) def test_no_result_from_enter(self): with suppress(ValueError) as enter_result: self.assertIsNone(enter_result) def test_no_exception(self): with suppress(ValueError): self.assertEqual(pow(2, 5), 32) def test_exact_exception(self): with suppress(TypeError): len(5) def test_exception_hierarchy(self): with suppress(LookupError): 'Hello'[50] def test_other_exception(self): with self.assertRaises(ZeroDivisionError): with suppress(TypeError): 1/0 def test_no_args(self): with self.assertRaises(ZeroDivisionError): with suppress(): 1/0 def test_multiple_exception_args(self): with suppress(ZeroDivisionError, TypeError): 1/0 with suppress(ZeroDivisionError, TypeError): len(5) def test_cm_is_reentrant(self): ignore_exceptions = suppress(Exception) with ignore_exceptions: pass with ignore_exceptions: len(5) with ignore_exceptions: with ignore_exceptions: # Check nested usage len(5) outer_continued = True 1/0 self.assertTrue(outer_continued) def test_exception_groups(self): eg_ve = lambda: ExceptionGroup( "EG with ValueErrors only", [ValueError("ve1"), ValueError("ve2"), ValueError("ve3")], ) eg_all = lambda: ExceptionGroup( "EG with many types of exceptions", [ValueError("ve1"), KeyError("ke1"), ValueError("ve2"), KeyError("ke2")], ) with suppress(ValueError): raise eg_ve() with suppress(ValueError, KeyError): raise eg_all() with self.assertRaises(ExceptionGroup) as eg1: with suppress(ValueError): raise eg_all() self.assertExceptionIsLike( eg1.exception, ExceptionGroup( "EG with many types of exceptions", [KeyError("ke1"), KeyError("ke2")], ), ) # Check handling of BaseExceptionGroup, using GeneratorExit so that # we don't accidentally discard a ctrl-c with KeyboardInterrupt. with suppress(GeneratorExit): raise BaseExceptionGroup("message", [GeneratorExit()]) # If we raise a BaseException group, we can still suppress parts with self.assertRaises(BaseExceptionGroup) as eg1: with suppress(KeyError): raise BaseExceptionGroup("message", [GeneratorExit("g"), KeyError("k")]) self.assertExceptionIsLike( eg1.exception, BaseExceptionGroup("message", [GeneratorExit("g")]), ) # If we suppress all the leaf BaseExceptions, we get a non-base ExceptionGroup with self.assertRaises(ExceptionGroup) as eg1: with suppress(GeneratorExit): raise BaseExceptionGroup("message", [GeneratorExit("g"), KeyError("k")]) self.assertExceptionIsLike( eg1.exception, ExceptionGroup("message", [KeyError("k")]), )
TestSuppress
python
pypa__packaging
tests/test_tags.py
{ "start": 56932, "end": 66343 }
class ____: def teardown_method(self) -> None: # Clear the version cache tags._glibc_version = [] # type: ignore[attr-defined] @pytest.mark.parametrize( ("name", "expected"), [("CPython", "cp"), ("PyPy", "pp"), ("Jython", "jy"), ("IronPython", "ip")], ) def test_interpreter_name( self, name: str, expected: str, mock_interpreter_name: Callable[[str], bool] ) -> None: mock_interpreter_name(name) assert tags.interpreter_name() == expected def test_iterator(self) -> None: assert isinstance(tags.sys_tags(), collections.abc.Iterator) def test_mac_cpython( self, mock_interpreter_name: Callable[[str], bool], monkeypatch: pytest.MonkeyPatch, ) -> None: if mock_interpreter_name("CPython"): monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"]) if platform.system() != "Darwin": monkeypatch.setattr(platform, "system", lambda: "Darwin") monkeypatch.setattr(tags, "mac_platforms", lambda: ["macosx_10_5_x86_64"]) abis = tags._cpython_abis(sys.version_info[:2]) platforms = list(tags.mac_platforms()) result = list(tags.sys_tags()) assert len(abis) == 1 assert result[0] == tags.Tag( "cp" + tags._version_nodot(sys.version_info[:2]), abis[0], platforms[0] ) assert result[-1] == tags.Tag( "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any" ) def test_windows_cpython( self, mock_interpreter_name: Callable[[str], bool], monkeypatch: pytest.MonkeyPatch, ) -> None: if mock_interpreter_name("CPython"): monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"]) if platform.system() != "Windows": monkeypatch.setattr(platform, "system", lambda: "Windows") monkeypatch.setattr(tags, "_generic_platforms", lambda: ["win_amd64"]) abis = list(tags._cpython_abis(sys.version_info[:2])) platforms = list(tags._generic_platforms()) result = list(tags.sys_tags()) interpreter = "cp" + tags._version_nodot(sys.version_info[:2]) assert len(abis) == 1 expected = tags.Tag(interpreter, abis[0], platforms[0]) assert result[0] == expected expected = tags.Tag( "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any" ) assert result[-1] == expected def test_linux_cpython( self, mock_interpreter_name: Callable[[str], bool], monkeypatch: pytest.MonkeyPatch, ) -> None: if mock_interpreter_name("CPython"): monkeypatch.setattr(tags, "_cpython_abis", lambda *a: ["cp33m"]) if platform.system() != "Linux": monkeypatch.setattr(platform, "system", lambda: "Linux") monkeypatch.setattr(tags, "_linux_platforms", lambda: ["linux_x86_64"]) abis = list(tags._cpython_abis(sys.version_info[:2])) platforms = list(tags._linux_platforms()) result = list(tags.sys_tags()) expected_interpreter = "cp" + tags._version_nodot(sys.version_info[:2]) assert len(abis) == 1 assert result[0] == tags.Tag(expected_interpreter, abis[0], platforms[0]) expected = tags.Tag( "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any" ) assert result[-1] == expected def test_generic(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(platform, "system", lambda: "Generic") monkeypatch.setattr(tags, "interpreter_name", lambda: "generic") result = list(tags.sys_tags()) expected = tags.Tag( "py" + tags._version_nodot((sys.version_info[0], 0)), "none", "any" ) assert result[-1] == expected @pytest.mark.usefixtures("manylinux_module") def test_linux_platforms_manylinux2014_armv6l( self, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_armv6l") monkeypatch.setattr(os, "confstr", lambda _: "glibc 2.20", raising=False) platforms = list(tags._linux_platforms(is_32bit=True)) expected = ["linux_armv6l"] assert platforms == expected def test_skip_manylinux_2014( self, monkeypatch: pytest.MonkeyPatch, manylinux_module: types.ModuleType ) -> None: monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_ppc64") monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda: (2, 20)) # type: ignore[attr-defined] monkeypatch.setattr( manylinux_module, "manylinux2014_compatible", False, raising=False ) expected = [ "manylinux_2_20_ppc64", "manylinux_2_19_ppc64", "manylinux_2_18_ppc64", # "manylinux2014_ppc64", # this one is skipped # "manylinux_2_17_ppc64", # this one is also skipped "linux_ppc64", ] platforms = list(tags._linux_platforms()) assert platforms == expected @pytest.mark.usefixtures("manylinux_module") @pytest.mark.parametrize( ("machine", "abi", "alt_machine"), [("x86_64", "x32", "i686"), ("armv7l", "armel", "armv7l")], ) def test_linux_platforms_not_manylinux_abi( self, monkeypatch: pytest.MonkeyPatch, machine: str, abi: str, alt_machine: str ) -> None: monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}") monkeypatch.setattr( sys, "executable", os.path.join( os.path.dirname(__file__), "manylinux", f"hello-world-{machine}-{abi}", ), ) platforms = list(tags._linux_platforms(is_32bit=True)) expected = [f"linux_{alt_machine}"] assert platforms == expected @pytest.mark.parametrize( ("machine", "major", "minor", "tf"), [("x86_64", 2, 20, False), ("s390x", 2, 22, True)], ) def test_linux_use_manylinux_compatible( self, monkeypatch: pytest.MonkeyPatch, manylinux_module: types.ModuleType, machine: str, major: int, minor: int, tf: bool, ) -> None: def manylinux_compatible(tag_major: int, tag_minor: int, tag_arch: str) -> bool: if tag_major == 2 and tag_minor == 22: return tag_arch == "s390x" return False monkeypatch.setattr( tags._manylinux, # type: ignore[attr-defined] "_get_glibc_version", lambda: (major, minor), ) monkeypatch.setattr(sysconfig, "get_platform", lambda: f"linux_{machine}") monkeypatch.setattr( manylinux_module, "manylinux_compatible", manylinux_compatible, raising=False, ) platforms = list(tags._linux_platforms(is_32bit=False)) expected = [f"manylinux_2_22_{machine}"] if tf else [] expected.append(f"linux_{machine}") assert platforms == expected def test_linux_use_manylinux_compatible_none( self, monkeypatch: pytest.MonkeyPatch, manylinux_module: types.ModuleType ) -> None: def manylinux_compatible( tag_major: int, tag_minor: int, tag_arch: str, # noqa: ARG001 ) -> bool | None: if tag_major == 2 and tag_minor < 25: return False return None monkeypatch.setattr(tags._manylinux, "_get_glibc_version", lambda: (2, 30)) # type: ignore[attr-defined] monkeypatch.setattr(sysconfig, "get_platform", lambda: "linux_x86_64") monkeypatch.setattr( manylinux_module, "manylinux_compatible", manylinux_compatible, raising=False, ) platforms = list(tags._linux_platforms(is_32bit=False)) expected = [ "manylinux_2_30_x86_64", "manylinux_2_29_x86_64", "manylinux_2_28_x86_64", "manylinux_2_27_x86_64", "manylinux_2_26_x86_64", "manylinux_2_25_x86_64", "linux_x86_64", ] assert platforms == expected def test_pypy_first_none_any_tag(self, monkeypatch: pytest.MonkeyPatch) -> None: # When building the complete list of pypy tags, make sure the first # <interpreter>-none-any one is pp3-none-any monkeypatch.setattr(tags, "interpreter_name", lambda: "pp") for tag in tags.sys_tags(): if tag.abi == "none" and tag.platform == "any": break assert tag == tags.Tag("pp3", "none", "any") def test_cpython_first_none_any_tag(self, monkeypatch: pytest.MonkeyPatch) -> None: # When building the complete list of cpython tags, make sure the first # <interpreter>-none-any one is cpxx-none-any monkeypatch.setattr(tags, "interpreter_name", lambda: "cp") # Find the first tag that is ABI- and platform-agnostic. for tag in tags.sys_tags(): if tag.abi == "none" and tag.platform == "any": break interpreter = f"cp{tags.interpreter_version()}" assert tag == tags.Tag(interpreter, "none", "any")
TestSysTags
python
huggingface__transformers
tests/utils/test_core_model_loading.py
{ "start": 7183, "end": 7313 }
class ____(nn.Module): def __init__(self): super().__init__() self.down_proj = DummyParamModule((2, 2))
DummyMLP
python
django__django
tests/admin_changelist/models.py
{ "start": 1934, "end": 2086 }
class ____(models.Model): name = models.CharField(max_length=30) members = models.ManyToManyField(ChordsMusician, through="Invitation")
ChordsBand
python
dagster-io__dagster
python_modules/dagster/dagster/_core/events/__init__.py
{ "start": 66834, "end": 67005 }
class ____: asset_key: AssetKey previous_health_state: AssetHealthStatus new_health_state: AssetHealthStatus @whitelist_for_serdes @record
AssetHealthChangedData
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/controls.py
{ "start": 1633, "end": 3779 }
class ____(metaclass=ABCMeta): """ Base class for all user interface controls. """ def reset(self) -> None: # Default reset. (Doesn't have to be implemented.) pass def preferred_width(self, max_available_width: int) -> int | None: return None def preferred_height( self, width: int, max_available_height: int, wrap_lines: bool, get_line_prefix: GetLinePrefixCallable | None, ) -> int | None: return None def is_focusable(self) -> bool: """ Tell whether this user control is focusable. """ return False @abstractmethod def create_content(self, width: int, height: int) -> UIContent: """ Generate the content for this user control. Returns a :class:`.UIContent` instance. """ def mouse_handler(self, mouse_event: MouseEvent) -> NotImplementedOrNone: """ Handle mouse events. When `NotImplemented` is returned, it means that the given event is not handled by the `UIControl` itself. The `Window` or key bindings can decide to handle this event as scrolling or changing focus. :param mouse_event: `MouseEvent` instance. """ return NotImplemented def move_cursor_down(self) -> None: """ Request to move the cursor down. This happens when scrolling down and the cursor is completely at the top. """ def move_cursor_up(self) -> None: """ Request to move the cursor up. """ def get_key_bindings(self) -> KeyBindingsBase | None: """ The key bindings that are specific for this user control. Return a :class:`.KeyBindings` object if some key bindings are specified, or `None` otherwise. """ def get_invalidate_events(self) -> Iterable[Event[object]]: """ Return a list of `Event` objects. This can be a generator. (The application collects all these events, in order to bind redraw handlers to these events.) """ return []
UIControl
python
sympy__sympy
sympy/matrices/dense.py
{ "start": 903, "end": 3616 }
class ____(RepMatrix): """Matrix implementation based on DomainMatrix as the internal representation""" # # DenseMatrix is a superclass for both MutableDenseMatrix and # ImmutableDenseMatrix. Methods shared by both classes but not for the # Sparse classes should be implemented here. # is_MatrixExpr: bool = False _op_priority = 10.01 _class_priority = 4 @property def _mat(self): sympy_deprecation_warning( """ The private _mat attribute of Matrix is deprecated. Use the .flat() method instead. """, deprecated_since_version="1.9", active_deprecations_target="deprecated-private-matrix-attributes" ) return self.flat() def _eval_inverse(self, **kwargs): return self.inv(method=kwargs.get('method', 'GE'), iszerofunc=kwargs.get('iszerofunc', _iszero), try_block_diag=kwargs.get('try_block_diag', False)) def as_immutable(self): """Returns an Immutable version of this Matrix """ from .immutable import ImmutableDenseMatrix as cls return cls._fromrep(self._rep.copy()) def as_mutable(self): """Returns a mutable version of this matrix Examples ======== >>> from sympy import ImmutableMatrix >>> X = ImmutableMatrix([[1, 2], [3, 4]]) >>> Y = X.as_mutable() >>> Y[1, 1] = 5 # Can set values in Y >>> Y Matrix([ [1, 2], [3, 5]]) """ return Matrix(self) def cholesky(self, hermitian=True): return _cholesky(self, hermitian=hermitian) def LDLdecomposition(self, hermitian: bool = True) -> tuple[Self, Self]: return _LDLdecomposition(self, hermitian=hermitian) def lower_triangular_solve(self, rhs): return _lower_triangular_solve(self, rhs) def upper_triangular_solve(self, rhs): return _upper_triangular_solve(self, rhs) cholesky.__doc__ = _cholesky.__doc__ LDLdecomposition.__doc__ = _LDLdecomposition.__doc__ lower_triangular_solve.__doc__ = _lower_triangular_solve.__doc__ upper_triangular_solve.__doc__ = _upper_triangular_solve.__doc__ # XXX: This function doesn't seem to be used anywhere. Delete it. def _force_mutable(x): """Return a matrix as a Matrix, otherwise return x.""" if getattr(x, 'is_Matrix', False): return x.as_mutable() elif isinstance(x, Basic): return x elif hasattr(x, '__array__'): a = x.__array__() if len(a.shape) == 0: return sympify(a) return Matrix(x) return x
DenseMatrix
python
python-markdown__markdown
tests/test_syntax/extensions/test_abbr.py
{ "start": 886, "end": 14722 }
class ____(TestCase): maxDiff = None default_kwargs = {'extensions': ['abbr']} def test_ignore_atomic(self): self.assertMarkdownRenders( self.dedent( """ This <https://example.com/{YAFR}> *[YAFR]: Yet Another Feature Request """ ), '<p>This <a href="https://example.com/{YAFR}">https://example.com/{YAFR}</a></p>' ) def test_abbr_upper(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr></p> """ ) ) def test_abbr_lower(self): self.assertMarkdownRenders( self.dedent( """ abbr *[abbr]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">abbr</abbr></p> """ ) ) def test_abbr_multiple_in_text(self): self.assertMarkdownRenders( self.dedent( """ The HTML specification is maintained by the W3C. *[HTML]: Hyper Text Markup Language *[W3C]: World Wide Web Consortium """ ), self.dedent( """ <p>The <abbr title="Hyper Text Markup Language">HTML</abbr> specification is maintained by the <abbr title="World Wide Web Consortium">W3C</abbr>.</p> """ ) ) def test_abbr_multiple_in_tail(self): self.assertMarkdownRenders( self.dedent( """ *The* HTML specification is maintained by the W3C. *[HTML]: Hyper Text Markup Language *[W3C]: World Wide Web Consortium """ ), self.dedent( """ <p><em>The</em> <abbr title="Hyper Text Markup Language">HTML</abbr> specification is maintained by the <abbr title="World Wide Web Consortium">W3C</abbr>.</p> """ ) ) def test_abbr_multiple_nested(self): self.assertMarkdownRenders( self.dedent( """ The *HTML* specification is maintained by the *W3C*. *[HTML]: Hyper Text Markup Language *[W3C]: World Wide Web Consortium """ ), self.dedent( """ <p>The <em><abbr title="Hyper Text Markup Language">HTML</abbr></em> specification is maintained by the <em><abbr title="World Wide Web Consortium">W3C</abbr></em>.</p> """ ) ) def test_abbr_override(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]: Ignored *[ABBR]: The override """ ), self.dedent( """ <p><abbr title="The override">ABBR</abbr></p> """ ) ) def test_abbr_glossary(self): glossary = { "ABBR": "Abbreviation", "abbr": "Abbreviation", "HTML": "Hyper Text Markup Language", "W3C": "World Wide Web Consortium" } self.assertMarkdownRenders( self.dedent( """ ABBR abbr HTML W3C """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr> <abbr title="Abbreviation">abbr</abbr></p> <p><abbr title="Hyper Text Markup Language">HTML</abbr> <abbr title="World Wide Web Consortium">W3C</abbr></p> """ ), extensions=[AbbrExtension(glossary=glossary)] ) def test_abbr_glossary_2(self): glossary = { "ABBR": "Abbreviation", "abbr": "Abbreviation", "HTML": "Hyper Text Markup Language", "W3C": "World Wide Web Consortium" } glossary_2 = { "ABBR": "New Abbreviation" } abbr_ext = AbbrExtension(glossary=glossary) abbr_ext.load_glossary(glossary_2) self.assertMarkdownRenders( self.dedent( """ ABBR abbr HTML W3C """ ), self.dedent( """ <p><abbr title="New Abbreviation">ABBR</abbr> """ + """<abbr title="Abbreviation">abbr</abbr> """ + """<abbr title="Hyper Text Markup Language">HTML</abbr> """ + """<abbr title="World Wide Web Consortium">W3C</abbr></p> """ ), extensions=[abbr_ext] ) def test_abbr_nested(self): self.assertMarkdownRenders( self.dedent( """ [ABBR](/foo) _ABBR_ *[ABBR]: Abbreviation """ ), self.dedent( """ <p><a href="/foo"><abbr title="Abbreviation">ABBR</abbr></a></p> <p><em><abbr title="Abbreviation">ABBR</abbr></em></p> """ ) ) def test_abbr_no_blank_Lines(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]: Abbreviation ABBR """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr></p> <p><abbr title="Abbreviation">ABBR</abbr></p> """ ) ) def test_abbr_no_space(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]:Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr></p> """ ) ) def test_abbr_extra_space(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR] : Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr></p> """ ) ) def test_abbr_line_break(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr></p> """ ) ) def test_abbr_ignore_unmatched_case(self): self.assertMarkdownRenders( self.dedent( """ ABBR abbr *[ABBR]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr> abbr</p> """ ) ) def test_abbr_partial_word(self): self.assertMarkdownRenders( self.dedent( """ ABBR ABBREVIATION *[ABBR]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR</abbr> ABBREVIATION</p> """ ) ) def test_abbr_unused(self): self.assertMarkdownRenders( self.dedent( """ foo bar *[ABBR]: Abbreviation """ ), self.dedent( """ <p>foo bar</p> """ ) ) def test_abbr_double_quoted(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]: "Abbreviation" """ ), self.dedent( """ <p><abbr title="&quot;Abbreviation&quot;">ABBR</abbr></p> """ ) ) def test_abbr_single_quoted(self): self.assertMarkdownRenders( self.dedent( """ ABBR *[ABBR]: 'Abbreviation' """ ), self.dedent( """ <p><abbr title="'Abbreviation'">ABBR</abbr></p> """ ) ) def test_abbr_ignore_backslash(self): self.assertMarkdownRenders( self.dedent( r""" \\foo *[\\foo]: Not an abbreviation """ ), self.dedent( r""" <p>\foo</p> <p>*[\foo]: Not an abbreviation</p> """ ) ) def test_abbr_hyphen(self): self.assertMarkdownRenders( self.dedent( """ ABBR-abbr *[ABBR-abbr]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR-abbr</abbr></p> """ ) ) def test_abbr_carrot(self): self.assertMarkdownRenders( self.dedent( """ ABBR^abbr *[ABBR^abbr]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR^abbr</abbr></p> """ ) ) def test_abbr_bracket(self): self.assertMarkdownRenders( self.dedent( """ ABBR]abbr *[ABBR]abbr]: Abbreviation """ ), self.dedent( """ <p><abbr title="Abbreviation">ABBR]abbr</abbr></p> """ ) ) def test_abbr_with_attr_list(self): self.assertMarkdownRenders( self.dedent( """ *[abbr]: Abbreviation Definition ![Image with abbr in title](abbr.png){title="Image with abbr in title"} """ ), self.dedent( """ <p><img alt="Image with abbr in title" src="abbr.png" title="Image with abbr in title" /></p> """ ), extensions=['abbr', 'attr_list'] ) def test_abbr_superset_vs_subset(self): self.assertMarkdownRenders( self.dedent( """ abbr, SS, and abbr-SS should have different definitions. *[abbr]: Abbreviation Definition *[abbr-SS]: Abbreviation Superset Definition *[SS]: Superset Definition """ ), self.dedent( """ <p><abbr title="Abbreviation Definition">abbr</abbr>, """ + """<abbr title="Superset Definition">SS</abbr>, """ + """and <abbr title="Abbreviation Superset Definition">abbr-SS</abbr> """ + """should have different definitions.</p> """ ) ) def test_abbr_empty(self): self.assertMarkdownRenders( self.dedent( """ *[abbr]: Abbreviation Definition abbr *[]: Empty *[ ]: Empty *[abbr]: *[ABBR]: Testing document text. """ ), self.dedent( """ <p><abbr title="Abbreviation Definition">abbr</abbr></p>\n""" + """<p>*[]: Empty</p>\n""" + """<p>*[ ]: Empty</p>\n""" + """<p>*[<abbr title="Abbreviation Definition">abbr</abbr>]:</p>\n""" + """<p>*[ABBR]:</p>\n""" + """<p>Testing document text.</p> """ ) ) def test_abbr_clear(self): self.assertMarkdownRenders( self.dedent( """ *[abbr]: Abbreviation Definition *[ABBR]: Abbreviation Definition abbr ABBR *[abbr]: "" *[ABBR]: '' """ ), self.dedent( """ <p>abbr ABBR</p> """ ) ) def test_abbr_reset(self): ext = AbbrExtension() md = Markdown(extensions=[ext]) md.convert('*[abbr]: Abbreviation Definition') self.assertEqual(ext.abbrs, {'abbr': 'Abbreviation Definition'}) md.convert('*[ABBR]: Capitalised Abbreviation') self.assertEqual(ext.abbrs, {'abbr': 'Abbreviation Definition', 'ABBR': 'Capitalised Abbreviation'}) md.reset() self.assertEqual(ext.abbrs, {}) md.convert('*[foo]: Foo Definition') self.assertEqual(ext.abbrs, {'foo': 'Foo Definition'})
TestAbbr
python
mlflow__mlflow
tests/genai/judges/test_judge_base.py
{ "start": 260, "end": 3523 }
class ____(Judge): def __init__(self, name: str, custom_instructions: str | None = None, **kwargs): super().__init__(name=name, **kwargs) self._custom_instructions = custom_instructions @property def instructions(self) -> str: if self._custom_instructions: return self._custom_instructions return f"Mock judge implementation: {self.name}" def get_input_fields(self) -> list[JudgeField]: """Get input fields for mock judge.""" return [ JudgeField(name="inputs", description="Input data for evaluation"), JudgeField(name="outputs", description="Output data for evaluation"), JudgeField(name="expectations", description="Expected outcomes"), JudgeField(name="trace", description="Trace for evaluation"), ] def __call__( self, *, inputs: dict[str, Any] | None = None, outputs: dict[str, Any] | None = None, expectations: dict[str, Any] | None = None, trace: Trace | None = None, ) -> Feedback: return Feedback( name=self.name, value=True, rationale=f"Test evaluation by {self.name}", ) def test_judge_base_class_abstract_behavior(): with pytest.raises(TypeError, match="Can't instantiate abstract class Judge"): Judge(name="test") def test_judge_implementation(): judge = MockJudgeImplementation(name="test_judge") assert isinstance(judge, Scorer) assert isinstance(judge, Judge) assert judge.instructions == "Mock judge implementation: test_judge" result = judge( inputs={"question": "What is 2+2?"}, outputs="4", ) assert isinstance(result, Feedback) assert result.name == "test_judge" assert result.value is True assert "Test evaluation by test_judge" in result.rationale judge_custom = MockJudgeImplementation( name="custom_judge", custom_instructions="Custom instructions for testing" ) assert judge_custom.instructions == "Custom instructions for testing" def test_judge_factory_pattern(): def make_simple_judge(name: str, instructions: str) -> Judge: class DynamicJudge(Judge): @property def instructions(self) -> str: return instructions def get_input_fields(self) -> list[JudgeField]: """Get input fields for dynamic judge.""" return [ JudgeField(name="outputs", description="Output to evaluate"), ] def __call__(self, **kwargs): return Feedback(name=self.name, value="pass", rationale=f"Evaluated by {self.name}") return DynamicJudge(name=name) judge = make_simple_judge( name="factory_judge", instructions="A judge created by factory function" ) assert isinstance(judge, Judge) assert isinstance(judge, Scorer) assert judge.name == "factory_judge" assert judge.instructions == "A judge created by factory function" result = judge(outputs="test output") assert isinstance(result, Feedback) assert result.value == "pass" assert "Evaluated by factory_judge" in result.rationale
MockJudgeImplementation
python
google__jax
jax/_src/lax/lax.py
{ "start": 369190, "end": 373344 }
class ____: allow_conversion: bool = True @staticmethod def physical_element_aval(dtype) -> core.ShapedArray: return core.ShapedArray((), np.dtype('int32')) @staticmethod def result_handler(sticky_device, aval): def handler(_, buf): buf.aval = core.ShapedArray(buf.shape, buf.dtype) return core.DArray(aval, buf) return handler @staticmethod def global_sharded_result_handler(aval, out_sharding, committed): phys_aval = core.physical_aval(aval) phys_handler_maker = pxla.global_result_handlers[core.ShapedArray] if not dispatch.is_single_device_sharding(out_sharding): raise NotImplementedError # TODO(mattjj) else: phys_sharding = out_sharding phys_handler = phys_handler_maker(phys_aval, phys_sharding, committed) def handler(bufs): return core.DArray(aval, phys_handler(bufs)) return handler core.bint._rules = BIntRules def optimization_barrier(operand, /): """Prevents the compiler from moving operations across the barrier. Optimization barriers have a number of possible uses: * An optimization barrier ensures that every output of the barrier that is used by any operator, has been evaluated before any operator that depends on one of the barrier's outputs. This can be used to enforce a particular order of operations. Note that all operands must be used through the barrier for this to work. There are no ordering constraints between an operator that uses one of the barrier's outputs, and an operator that directly (not through the barrier) uses one of the barrier's inputs. * An optimization barrier prevents common subexpression elimination. This is used by JAX to implement rematerialization. * Optimization barriers prevent compiler fusions. That is, operations before the barrier may not be fused into the same kernel as operations after the barrier by the compiler. JAX does not define derivative or batching rules for an optimization barrier. Optimization barriers have no effect outside a compiled function. Args: operand: a pytree of JAX values. Returns: A pytree of JAX values, with the same structure and contents as ``operand``. Examples: Prevents common-subexpression elimination between the two calls to `sin`: >>> def f(x): ... return jax.lax.optimization_barrier(jax.lax.sin(x)) + jax.lax.sin(x) >>> jax.jit(f)(0.) Array(0., dtype=float32, weak_type=True) """ flat_args, treedef = tree_util.tree_flatten(operand) flat_args = core.standard_insert_pvary(*flat_args) out = optimization_barrier_p.bind(*flat_args) return tree_util.tree_unflatten(treedef, out) def _optimization_barrier_abstract_eval(*args): core.standard_vma_rule('optimization_barrier', *args) return args def _optimization_barrier_lowering_rule(ctx, *args): barrier_types = map(mlir.aval_to_ir_type, ctx.avals_in) flat_args = mlir.flatten_ir_values(args) barrier_op = hlo.OptimizationBarrierOp(flat_args) return mlir.unflatten_ir_values_like_types(barrier_op.results, barrier_types) optimization_barrier_p = core.Primitive('optimization_barrier') optimization_barrier_p.multiple_results = True optimization_barrier_p.def_impl( partial(dispatch.apply_primitive, optimization_barrier_p)) optimization_barrier_p.def_abstract_eval(_optimization_barrier_abstract_eval) mlir.register_lowering(optimization_barrier_p, _optimization_barrier_lowering_rule) def _optimization_barrier_batcher(batched_args, batch_dims, **params): return optimization_barrier_p.bind(*batched_args, **params), batch_dims batching.primitive_batchers[optimization_barrier_p] = _optimization_barrier_batcher def _opt_barrier_jvp(primals, tangents): tangents = [ad.instantiate_zeros(t) for t in tangents] return optimization_barrier(primals), optimization_barrier(tangents) ad.primitive_jvps[optimization_barrier_p] = _opt_barrier_jvp def _opt_barrier_transpose(cts, *primals): cts = [ad.instantiate_zeros(ct) for ct in cts] return optimization_barrier(cts) ad.primitive_transposes[optimization_barrier_p] = _opt_barrier_transpose
BIntRules
python
doocs__leetcode
solution/0200-0299/0270.Closest Binary Search Tree Value/Solution.py
{ "start": 192, "end": 733 }
class ____: def closestValue(self, root: Optional[TreeNode], target: float) -> int: def dfs(node: Optional[TreeNode]): if node is None: return nxt = abs(target - node.val) nonlocal ans, diff if nxt < diff or (nxt == diff and node.val < ans): diff = nxt ans = node.val node = node.left if target < node.val else node.right dfs(node) ans = 0 diff = inf dfs(root) return ans
Solution
python
mozilla__bleach
tests_website/server.py
{ "start": 210, "end": 1157 }
class ____(http.server.SimpleHTTPRequestHandler): # Prevent 'cannot bind to address' errors on restart allow_reuse_address = True def do_POST(self): content_len = int(self.headers.get("content-length", 0)) body = self.rfile.read(content_len) print("read {} bytes: {}".format(content_len, body)) body = body.decode("utf-8") print("input: %r" % body) cleaned = bleach.clean(body) self.send_response(200) self.send_header("Content-Length", len(cleaned)) self.send_header("Content-Type", "text/plain;charset=UTF-8") self.end_headers() cleaned = bytes(cleaned, encoding="utf-8") print("cleaned: %r" % cleaned) self.wfile.write(cleaned) if __name__ == "__main__": httpd = socketserver.TCPServer(("127.0.0.1", PORT), BleachCleanHandler) print("listening on localhost port %d" % PORT) httpd.serve_forever()
BleachCleanHandler
python
run-llama__llama_index
llama-index-core/llama_index/core/schema.py
{ "start": 14687, "end": 19328 }
class ____(BaseModel): """ A container class for media content. This class represents a generic media resource that can be stored and accessed in multiple ways - as raw bytes, on the filesystem, or via URL. It also supports storing vector embeddings for the media content. Attributes: embeddings: Multi-vector dict representation of this resource for embedding-based search/retrieval text: Plain text representation of this resource data: Raw binary data of the media content mimetype: The MIME type indicating the format/type of the media content path: Local filesystem path where the media content can be accessed url: URL where the media content can be accessed remotely """ embeddings: dict[EmbeddingKind, list[float]] | None = Field( default=None, description="Vector representation of this resource." ) data: bytes | None = Field( default=None, exclude=True, description="base64 binary representation of this resource.", ) text: str | None = Field( default=None, description="Text representation of this resource." ) path: Path | None = Field( default=None, description="Filesystem path of this resource." ) url: AnyUrl | None = Field(default=None, description="URL to reach this resource.") mimetype: str | None = Field( default=None, description="MIME type of this resource." ) model_config = { # This ensures validation runs even for None values "validate_default": True } @field_validator("data", mode="after") @classmethod def validate_data(cls, v: bytes | None, info: ValidationInfo) -> bytes | None: """ If binary data was passed, store the resource as base64 and guess the mimetype when possible. In case the model was built passing binary data but without a mimetype, we try to guess it using the filetype library. To avoid resource-intense operations, we won't load the path or the URL to guess the mimetype. """ if v is None: return v try: # Check if data is already base64 encoded. # b64decode() can succeed on random binary data, so we # pass verify=True to make sure it's not a false positive decoded = base64.b64decode(v, validate=True) except BinasciiError: # b64decode failed, return encoded return base64.b64encode(v) # Good as is, return unchanged return v @field_validator("mimetype", mode="after") @classmethod def validate_mimetype(cls, v: str | None, info: ValidationInfo) -> str | None: if v is not None: return v # Since this field validator runs after the one for `data` # then the contents of `data` should be encoded already b64_data = info.data.get("data") if b64_data: # encoded bytes decoded_data = base64.b64decode(b64_data) if guess := filetype.guess(decoded_data): return guess.mime # guess from path rpath: str | None = info.data["path"] if rpath: extension = Path(rpath).suffix.replace(".", "") if ftype := filetype.get_type(ext=extension): return ftype.mime return v @field_serializer("path") # type: ignore def serialize_path( self, path: Optional[Path], _info: ValidationInfo ) -> Optional[str]: if path is None: return path return str(path) @property def hash(self) -> str: """ Generate a hash to uniquely identify the media resource. The hash is generated based on the available content (data, path, text or url). Returns an empty string if no content is available. """ bits: list[str] = [] if self.text is not None: bits.append(self.text) if self.data is not None: # Hash the binary data if available bits.append(str(sha256(self.data).hexdigest())) if self.path is not None: # Hash the file path if provided bits.append(str(sha256(str(self.path).encode("utf-8")).hexdigest())) if self.url is not None: # Use the URL string as basis for hash bits.append(str(sha256(str(self.url).encode("utf-8")).hexdigest())) doc_identity = "".join(bits) if not doc_identity: return "" return str(sha256(doc_identity.encode("utf-8", "surrogatepass")).hexdigest())
MediaResource
python
pytorch__pytorch
torch/utils/benchmark/utils/_stubs.py
{ "start": 645, "end": 1026 }
class ____(Protocol): """Replicates the valgrind endpoints in `torch._C`. These bindings are used to collect Callgrind profiles on earlier versions of PyTorch and will eventually be removed. """ __file__: str __name__: str def _valgrind_supported_platform(self) -> bool: ... def _valgrind_toggle(self) -> None: ...
CallgrindModuleType
python
doocs__leetcode
solution/2000-2099/2008.Maximum Earnings From Taxi/Solution2.py
{ "start": 0, "end": 358 }
class ____: def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int: rides.sort(key=lambda x: x[1]) f = [0] * (len(rides) + 1) for i, (st, ed, tip) in enumerate(rides, 1): j = bisect_left(rides, st + 1, hi=i, key=lambda x: x[1]) f[i] = max(f[i - 1], f[j] + ed - st + tip) return f[-1]
Solution
python
google__pytype
pytype/pyc/opcodes.py
{ "start": 20984, "end": 21084 }
class ____(OpcodeWithArg): _FLAGS = HAS_ARGUMENT | HAS_CONST | NO_NEXT __slots__ = ()
RETURN_CONST
python
pandas-dev__pandas
pandas/tests/test_algos.py
{ "start": 67406, "end": 69625 }
class ____: @pytest.mark.parametrize( "arr", [ [np.nan, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 3, np.nan], [4.0, np.nan, 5.0, 5.0, 5.0, np.nan, 1, 2, 4.0, np.nan], ], ) def test_scipy_compat(self, arr): sp_stats = pytest.importorskip("scipy.stats") arr = np.array(arr) mask = ~np.isfinite(arr) result = libalgos.rank_1d(arr) arr[mask] = np.inf exp = sp_stats.rankdata(arr) exp[mask] = np.nan tm.assert_almost_equal(result, exp) def test_basic(self, writable, any_int_numpy_dtype): exp = np.array([1, 2], dtype=np.float64) data = np.array([1, 100], dtype=any_int_numpy_dtype) data.setflags(write=writable) ser = Series(data) result = algos.rank(ser) tm.assert_numpy_array_equal(result, exp) @pytest.mark.parametrize("dtype", [np.float64, np.uint64]) def test_uint64_overflow(self, dtype): exp = np.array([1, 2], dtype=np.float64) s = Series([1, 2**63], dtype=dtype) tm.assert_numpy_array_equal(algos.rank(s), exp) @pytest.mark.parametrize("method", ["average", "min", "max"]) def test_rank_tiny_values(self, method): # GH62036: regression test for ranking with tiny float values exp = np.array([4.0, 1.0, 3.0, np.nan, 2.0], dtype=np.float64) s = Series( [5.4954145e29, -9.791984e-21, 9.3715776e-26, pd.NA, 1.8790257e-28], dtype="Float64", ) s = s.astype(object) result = algos.rank(s, method=method) tm.assert_numpy_array_equal(result, exp) def test_too_many_ndims(self): arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) msg = "Array with ndim > 2 are not supported" with pytest.raises(TypeError, match=msg): algos.rank(arr) @pytest.mark.single_cpu def test_pct_max_many_rows(self): # GH 18271 values = np.arange(2**24 + 1) result = algos.rank(values, pct=True).max() assert result == 1 values = np.arange(2**25 + 2).reshape(2**24 + 1, 2) result = algos.rank(values, pct=True).max() assert result == 1
TestRank
python
PyCQA__pylint
tests/functional/s/super/super_checks.py
{ "start": 3461, "end": 3636 }
class ____: """type(self) may lead to recursion loop in derived classes""" def __init__(self): super(type(self), self).__init__() # [bad-super-call]
SuperWithType
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/footsies/utils.py
{ "start": 748, "end": 805 }
class ____: p1: str p2: str prob: float
Matchup
python
pandas-dev__pandas
asv_bench/benchmarks/inference.py
{ "start": 8346, "end": 8662 }
class ____: def setup(self): ints = np.random.randint(0, 60, size=10000) self.arr = [f"{i} days" for i in ints] self.arr[-1] = "apple" def time_convert(self): to_timedelta(self.arr, errors="coerce") from .pandas_vb_common import setup # noqa: F401 isort:skip
ToTimedeltaErrors
python
pytorch__pytorch
torch/_dynamo/bytecode_transformation.py
{ "start": 1190, "end": 1991 }
class ____: start: "Instruction" end: "Instruction" target: "Instruction" depth: int lasti: bool def __repr__(self) -> str: return ( f"InstructionExnTabEntry(start={self.start.short_inst_repr()}, " f"end={self.end.short_inst_repr()}, " f"target={self.target.short_inst_repr()}, " f"depth={self.depth}, lasti={self.lasti})" ) def __eq__(self, o: object) -> bool: if not isinstance(o, InstructionExnTabEntry): return False return ( self.start is o.start and self.end is o.end and self.target is o.target and self.depth == o.depth and self.lasti == o.lasti ) @dataclasses.dataclass(slots=True)
InstructionExnTabEntry
python
django__django
tests/flatpages_tests/test_views.py
{ "start": 2462, "end": 5199 }
class ____(TestDataMixin, TestCase): def test_view_flatpage(self): "A flatpage can be served through a view" response = self.client.get("/flatpage_root/flatpage/") self.assertContains(response, "<p>Isn't it flat!</p>") def test_view_non_existent_flatpage(self): """A nonexistent flatpage raises 404 when served through a view.""" response = self.client.get("/flatpage_root/no_such_flatpage/") self.assertEqual(response.status_code, 404) def test_view_authenticated_flatpage(self): "A flatpage served through a view can require authentication" response = self.client.get("/flatpage_root/sekrit/") self.assertRedirects(response, "/accounts/login/?next=/flatpage_root/sekrit/") user = User.objects.create_user("testuser", "test@example.com", "s3krit") self.client.force_login(user) response = self.client.get("/flatpage_root/sekrit/") self.assertContains(response, "<p>Isn't it sekrit!</p>") def test_fallback_flatpage(self): "A fallback flatpage won't be served if the middleware is disabled" response = self.client.get("/flatpage/") self.assertEqual(response.status_code, 404) def test_fallback_non_existent_flatpage(self): """ A nonexistent flatpage won't be served if the fallback middleware is disabled. """ response = self.client.get("/no_such_flatpage/") self.assertEqual(response.status_code, 404) def test_view_flatpage_special_chars(self): "A flatpage with special chars in the URL can be served through a view" fp = FlatPage.objects.create( url="/some.very_special~chars-here/", title="A very special page", content="Isn't it special!", enable_comments=False, registration_required=False, ) fp.sites.add(settings.SITE_ID) response = self.client.get("/flatpage_root/some.very_special~chars-here/") self.assertContains(response, "<p>Isn't it special!</p>") @modify_settings(INSTALLED_APPS={"append": "django.contrib.flatpages"}) @override_settings( APPEND_SLASH=True, LOGIN_URL="/accounts/login/", MIDDLEWARE=[ "django.middleware.common.CommonMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", # no 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' ], ROOT_URLCONF="flatpages_tests.urls", TEMPLATES=FLATPAGES_TEMPLATES, SITE_ID=1, )
FlatpageViewTests
python
pydantic__pydantic
pydantic-core/tests/serializers/test_any.py
{ "start": 13297, "end": 14931 }
class ____: def __repr__(self): return '<Foobar repr>' def test_unknown_type(any_serializer: SchemaSerializer): f = Foobar() assert any_serializer.to_python(f) == f with pytest.raises(PydanticSerializationError, match="Unable to serialize unknown type: <class '.+Foobar'>"): any_serializer.to_python(f, mode='json') with pytest.raises(PydanticSerializationError, match="Unable to serialize unknown type: <class '.+Foobar'>"): any_serializer.to_json(f) def test_unknown_type_fallback(any_serializer: SchemaSerializer): def fallback_func(obj): return f'fallback:{obj!r}' f = Foobar() assert any_serializer.to_python(f) == f assert any_serializer.to_python(f, mode='json', fallback=fallback_func) == 'fallback:<Foobar repr>' assert any_serializer.to_python(f, fallback=fallback_func) == 'fallback:<Foobar repr>' assert any_serializer.to_json(f, fallback=fallback_func) == b'"fallback:<Foobar repr>"' def test_fallback_cycle_same(any_serializer: SchemaSerializer): def fallback_func(obj): return obj f = Foobar() assert any_serializer.to_python(f) == f with pytest.raises(ValueError, match=r'Circular reference detected \(id repeated\)'): any_serializer.to_python(f, mode='json', fallback=fallback_func) # because when recursion is detected and we're in mode python, we just return the value assert any_serializer.to_python(f, fallback=fallback_func) == f with pytest.raises(ValueError, match=r'Circular reference detected \(id repeated\)'): any_serializer.to_json(f, fallback=fallback_func)
Foobar
python
gevent__gevent
src/gevent/testing/testcase.py
{ "start": 1651, "end": 3505 }
class ____(object): @flaky.reraises_flaky_timeout() def assertTimeoutAlmostEqual(self, first, second, places=None, msg=None, delta=None): try: self.assertAlmostEqual(first, second, places=places, msg=msg, delta=delta) except AssertionError: flaky.reraiseFlakyTestTimeout() if sysinfo.EXPECT_POOR_TIMER_RESOLUTION: # pylint:disable=unused-argument def assertTimeWithinRange(self, time_taken, min_time, max_time): return else: def assertTimeWithinRange(self, time_taken, min_time, max_time): self.assertLessEqual(time_taken, max_time) self.assertGreaterEqual(time_taken, min_time) @contextmanager def runs_in_given_time(self, expected, fuzzy=None, min_time=None): if fuzzy is None: if sysinfo.EXPECT_POOR_TIMER_RESOLUTION or sysinfo.LIBUV: # The noted timer jitter issues on appveyor/pypy3 fuzzy = expected * 5.0 else: fuzzy = expected / 2.0 min_time = min_time if min_time is not None else expected - fuzzy max_time = expected + fuzzy start = perf_counter() yield (min_time, max_time) elapsed = perf_counter() - start try: self.assertTrue( min_time <= elapsed <= max_time, 'Expected: %r; elapsed: %r; min: %r; max: %r; fuzzy %r; clock_info: %s' % ( expected, elapsed, min_time, max_time, fuzzy, get_clock_info('perf_counter') )) except AssertionError: flaky.reraiseFlakyTestRaceCondition() def runs_in_no_time( self, fuzzy=(0.01 if not sysinfo.EXPECT_POOR_TIMER_RESOLUTION and not sysinfo.LIBUV else 1.0)): return self.runs_in_given_time(0.0, fuzzy)
TimeAssertMixin
python
spyder-ide__spyder
external-deps/spyder-kernels/spyder_kernels/comms/commbase.py
{ "start": 2323, "end": 2921 }
class ____(RuntimeError): pass def stacksummary_to_json(stack): """StackSummary to json.""" return [ { "filename": frame.filename, "lineno": frame.lineno, "name": frame.name, "line": frame.line } for frame in stack ] def stacksummary_from_json(stack): """StackSummary from json.""" return traceback.StackSummary.from_list([ ( frame["filename"], frame["lineno"], frame["name"], frame["line"] ) for frame in stack ])
CommError
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py
{ "start": 2959, "end": 7113 }
class ____: CUSTOMIZE_JOB_ARN = "valid_arn" CUSTOMIZE_JOB_NAME = "testModelJob" @pytest.fixture def mock_conn(self) -> Generator[BaseAwsConnection, None, None]: with mock.patch.object(BedrockHook, "conn") as _conn: _conn.create_model_customization_job.return_value = { "ResponseMetadata": {"HTTPStatusCode": 201}, "jobArn": self.CUSTOMIZE_JOB_ARN, } _conn.get_model_customization_job.return_value = { "jobName": self.CUSTOMIZE_JOB_NAME, "status": "InProgress", } yield _conn @pytest.fixture def bedrock_hook(self) -> Generator[BedrockHook, None, None]: with mock_aws(): hook = BedrockHook(aws_conn_id="aws_default") yield hook def setup_method(self): self.operator = BedrockCustomizeModelOperator( task_id="test_task", job_name=self.CUSTOMIZE_JOB_NAME, custom_model_name="testModelName", role_arn="valid_arn", base_model_id="base_model_id", hyperparameters={ "epochCount": "1", "batchSize": "1", "learningRate": ".0005", "learningRateWarmupSteps": "0", }, training_data_uri="s3://uri", output_data_uri="s3://uri/output", ) self.operator.defer = mock.MagicMock() @pytest.mark.parametrize( ("wait_for_completion", "deferrable"), [ pytest.param(False, False, id="no_wait"), pytest.param(True, False, id="wait"), pytest.param(False, True, id="defer"), ], ) @mock.patch.object(BedrockHook, "get_waiter") def test_customize_model_wait_combinations( self, _, wait_for_completion, deferrable, mock_conn, bedrock_hook ): self.operator.wait_for_completion = wait_for_completion self.operator.deferrable = deferrable response = self.operator.execute({}) assert response == self.CUSTOMIZE_JOB_ARN assert bedrock_hook.get_waiter.call_count == wait_for_completion assert self.operator.defer.call_count == deferrable conflict_msg = "The provided job name is currently in use." conflict_exception = ClientError( error_response={"Error": {"Message": conflict_msg, "Code": "ValidationException"}}, operation_name="UnitTest", ) success = {"ResponseMetadata": {"HTTPStatusCode": 201}, "jobArn": CUSTOMIZE_JOB_ARN} @pytest.mark.parametrize( ("side_effect", "ensure_unique_name"), [ pytest.param([conflict_exception, success], True, id="conflict_and_ensure_unique"), pytest.param([conflict_exception, success], False, id="conflict_and_not_ensure_unique"), pytest.param( [conflict_exception, conflict_exception, success], True, id="multiple_conflict_and_ensure_unique", ), pytest.param( [conflict_exception, conflict_exception, success], False, id="multiple_conflict_and_not_ensure_unique", ), pytest.param([success], True, id="no_conflict_and_ensure_unique"), pytest.param([success], False, id="no_conflict_and_not_ensure_unique"), ], ) @mock.patch.object(BedrockHook, "get_waiter") def test_ensure_unique_job_name(self, _, side_effect, ensure_unique_name, mock_conn, bedrock_hook): mock_conn.create_model_customization_job.side_effect = side_effect expected_call_count = len(side_effect) if ensure_unique_name else 1 self.operator.wait_for_completion = False response = self.operator.execute({}) assert response == self.CUSTOMIZE_JOB_ARN mock_conn.create_model_customization_job.call_count == expected_call_count bedrock_hook.get_waiter.assert_not_called() self.operator.defer.assert_not_called() def test_template_fields(self): validate_template_fields(self.operator)
TestBedrockCustomizeModelOperator
python
pytorch__pytorch
torch/nn/modules/pooling.py
{ "start": 30710, "end": 35677 }
class ____(_AvgPoolNd): r"""Applies a 3D average pooling over an input signal composed of several input planes. In the simplest case, the output value of the layer with input size :math:`(N, C, D, H, W)`, output :math:`(N, C, D_{out}, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kD, kH, kW)` can be precisely described as: .. math:: \begin{aligned} \text{out}(N_i, C_j, d, h, w) ={} & \sum_{k=0}^{kD-1} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1} \\ & \frac{\text{input}(N_i, C_j, \text{stride}[0] \times d + k, \text{stride}[1] \times h + m, \text{stride}[2] \times w + n)} {kD \times kH \times kW} \end{aligned} If :attr:`padding` is non-zero, then the input is implicitly zero-padded on all three sides for :attr:`padding` number of points. Note: When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding or the input. Sliding windows that would start in the right padded region are ignored. .. note:: pad should be at most half of effective kernel size. The parameters :attr:`kernel_size`, :attr:`stride` can either be: - a single ``int`` -- in which case the same value is used for the depth, height and width dimension - a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension, the second `int` for the height dimension and the third `int` for the width dimension Args: kernel_size: the size of the window stride: the stride of the window. Default value is :attr:`kernel_size` padding: implicit zero padding to be added on all three sides ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape count_include_pad: when True, will include the zero-padding in the averaging calculation divisor_override: if specified, it will be used as divisor, otherwise :attr:`kernel_size` will be used Shape: - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`. - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, where .. math:: D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor .. math:: H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor .. math:: W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{kernel\_size}[2]}{\text{stride}[2]} + 1\right\rfloor Per the note above, if ``ceil_mode`` is True and :math:`(D_{out} - 1)\times \text{stride}[0]\geq D_{in} + \text{padding}[0]`, we skip the last window as it would start in the padded region, resulting in :math:`D_{out}` being reduced by one. The same applies for :math:`W_{out}` and :math:`H_{out}`. Examples:: >>> # pool of square window of size=3, stride=2 >>> m = nn.AvgPool3d(3, stride=2) >>> # pool of non-square window >>> m = nn.AvgPool3d((3, 2, 2), stride=(2, 1, 2)) >>> input = torch.randn(20, 16, 50, 44, 31) >>> output = m(input) """ __constants__ = [ "kernel_size", "stride", "padding", "ceil_mode", "count_include_pad", "divisor_override", ] kernel_size: _size_3_t stride: _size_3_t padding: _size_3_t ceil_mode: bool count_include_pad: bool def __init__( self, kernel_size: _size_3_t, stride: Optional[_size_3_t] = None, padding: _size_3_t = 0, ceil_mode: bool = False, count_include_pad: bool = True, divisor_override: Optional[int] = None, ) -> None: super().__init__() self.kernel_size = kernel_size self.stride = stride if (stride is not None) else kernel_size self.padding = padding self.ceil_mode = ceil_mode self.count_include_pad = count_include_pad self.divisor_override = divisor_override def forward(self, input: Tensor) -> Tensor: """Runs the forward pass.""" return F.avg_pool3d( input, self.kernel_size, self.stride, self.padding, self.ceil_mode, self.count_include_pad, self.divisor_override, ) def __setstate__(self, d): super().__setstate__(d) self.__dict__.setdefault("padding", 0) self.__dict__.setdefault("ceil_mode", False) self.__dict__.setdefault("count_include_pad", True)
AvgPool3d
python
pydantic__pydantic
tests/test_main.py
{ "start": 101157, "end": 109339 }
class ____(BaseModel): x: int help_result_string = pydoc.render_doc(Model) """ ) assert 'class Model' in module.help_result_string def test_cannot_use_leading_underscore_field_names(): with pytest.raises( NameError, match="Fields must not use names with leading underscores; e.g., use 'x' instead of '_x'" ): class Model1(BaseModel): _x: int = Field(alias='x') with pytest.raises( NameError, match="Fields must not use names with leading underscores; e.g., use 'x__' instead of '__x__'" ): class Model2(BaseModel): __x__: int = Field() with pytest.raises( NameError, match="Fields must not use names with leading underscores; e.g., use 'my_field' instead of '___'" ): class Model3(BaseModel): ___: int = Field(default=1) def test_customize_type_constraints_order() -> None: class Model(BaseModel): # whitespace will be stripped first, then max length will be checked, should pass on ' 1 ' x: Annotated[str, AfterValidator(lambda x: x.strip()), StringConstraints(max_length=1)] # max length will be checked first, then whitespace will be stripped, should fail on ' 1 ' y: Annotated[str, StringConstraints(max_length=1), AfterValidator(lambda x: x.strip())] with pytest.raises(ValidationError) as exc_info: Model(x=' 1 ', y=' 1 ') # insert_assert(exc_info.value.errors(include_url=False)) assert exc_info.value.errors(include_url=False) == [ { 'type': 'string_too_long', 'loc': ('y',), 'msg': 'String should have at most 1 character', 'input': ' 1 ', 'ctx': {'max_length': 1}, } ] def test_shadow_attribute() -> None: """https://github.com/pydantic/pydantic/issues/7108""" class Model(BaseModel): foo: str @classmethod def __pydantic_init_subclass__(cls, **kwargs: Any): super().__pydantic_init_subclass__(**kwargs) for key in cls.model_fields.keys(): setattr(cls, key, getattr(cls, key, '') + ' edited!') class One(Model): foo: str = 'abc' with pytest.warns(UserWarning, match=r'"foo" in ".*Two" shadows an attribute in parent ".*One"'): class Two(One): foo: str with pytest.warns(UserWarning, match=r'"foo" in ".*Three" shadows an attribute in parent ".*One"'): class Three(One): foo: str = 'xyz' # unlike dataclasses BaseModel does not preserve the value of defaults # so when we access the attribute in `Model.__pydantic_init_subclass__` there is no default # and hence we append `edited!` to an empty string # we've talked about changing this but this is the current behavior as of this test assert getattr(Model, 'foo', None) is None assert getattr(One, 'foo', None) == ' edited!' assert getattr(Two, 'foo', None) == ' edited! edited!' assert getattr(Three, 'foo', None) == ' edited! edited!' def test_shadow_attribute_warn_for_redefined_fields() -> None: """https://github.com/pydantic/pydantic/issues/9107""" # A simple class which defines a field class Parent: foo: bool = False # When inheriting from the parent class, as long as the field is not defined at all, there should be no warning # about shadowed fields. with warnings.catch_warnings(record=True) as captured_warnings: # Start capturing all warnings warnings.simplefilter('always') class ChildWithoutRedefinedField(BaseModel, Parent): pass # Check that no warnings were captured assert len(captured_warnings) == 0 # But when inheriting from the parent class and a parent field is redefined, a warning should be raised about # shadowed fields irrespective of whether it is defined with a type that is still compatible or narrower, or # with a different default that is still compatible with the type definition. with pytest.warns( UserWarning, match=r'"foo" in ".*ChildWithRedefinedField" shadows an attribute in parent ".*Parent"', ): class ChildWithRedefinedField(BaseModel, Parent): foo: bool = True def test_field_name_deprecated_method_name() -> None: """https://github.com/pydantic/pydantic/issues/11912""" with pytest.warns(UserWarning): class Model(BaseModel): # `collect_model_fields()` will special case these to not use # the deprecated methods as default values: dict: int schema: str assert Model.model_fields['dict'].is_required() assert Model.model_fields['schema'].is_required() def test_eval_type_backport(): class Model(BaseModel): foo: 'list[int | str]' assert Model(foo=[1, '2']).model_dump() == {'foo': [1, '2']} with pytest.raises(ValidationError) as exc_info: Model(foo='not a list') # insert_assert(exc_info.value.errors(include_url=False)) assert exc_info.value.errors(include_url=False) == [ { 'type': 'list_type', 'loc': ('foo',), 'msg': 'Input should be a valid list', 'input': 'not a list', } ] with pytest.raises(ValidationError) as exc_info: Model(foo=[{'not a str or int'}]) # insert_assert(exc_info.value.errors(include_url=False)) assert exc_info.value.errors(include_url=False) == [ { 'type': 'int_type', 'loc': ('foo', 0, 'int'), 'msg': 'Input should be a valid integer', 'input': {'not a str or int'}, }, { 'type': 'string_type', 'loc': ('foo', 0, 'str'), 'msg': 'Input should be a valid string', 'input': {'not a str or int'}, }, ] def test_inherited_class_vars(create_module): @create_module def module(): import typing from pydantic import BaseModel class Base(BaseModel): CONST1: 'typing.ClassVar[str]' = 'a' CONST2: 'ClassVar[str]' = 'b' class Child(module.Base): pass assert Child.CONST1 == 'a' assert Child.CONST2 == 'b' def test_schema_valid_for_inner_generic() -> None: T = TypeVar('T') class Inner(BaseModel, Generic[T]): x: T class Outer(BaseModel): inner: Inner[int] assert Outer(inner={'x': 1}).inner.x == 1 # confirming that the typevars are substituted in the outer model schema assert Outer.__pydantic_core_schema__['schema']['fields']['inner']['schema']['cls'] == Inner[int] assert ( Outer.__pydantic_core_schema__['schema']['fields']['inner']['schema']['schema']['fields']['x']['schema']['type'] == 'int' ) def test_validation_works_for_cyclical_forward_refs() -> None: class X(BaseModel): y: Union['Y', None] class Y(BaseModel): x: Union[X, None] assert Y(x={'y': None}).x.y is None def test_model_construct_with_model_post_init_and_model_copy() -> None: class Model(BaseModel): id: int def model_post_init(self, context: Any, /) -> None: super().model_post_init(context) m = Model.model_construct(id=1) copy = m.model_copy(deep=True) assert m == copy assert id(m) != id(copy) def test_subclassing_gen_schema_warns() -> None: with pytest.warns(UserWarning, match='Subclassing `GenerateSchema` is not supported.'): class MyGenSchema(GenerateSchema): ... def test_nested_v1_model_warns() -> None: with pytest.warns( UserWarning, match=r'Mixing V1 models and V2 models \(or constructs, like `TypeAdapter`\) is not supported. Please upgrade `V1Model` to V2.', ): class V1Model(BaseModelV1): a: int class V2Model(BaseModel): inner: V1Model @pytest.mark.skipif(sys.version_info < (3, 13), reason='requires python 3.13') def test_replace() -> None: from copy import replace class Model(BaseModel): x: int y: int m = Model(x=1, y=2) assert replace(m, x=3) == Model(x=3, y=2)
Model
python
vyperlang__vyper
vyper/compiler/output_bundle.py
{ "start": 6787, "end": 9051 }
class ____(OutputBundleWriter): def __init__(self, compiler_data): super().__init__(compiler_data) self._output = {"language": "Vyper", "sources": {}, "settings": {"outputSelection": {}}} def write_sources(self, sources: dict[str, CompilerInput]): out = {} for path, c in sources.items(): out[path] = {"content": c.contents, "sha256sum": c.sha256sum} self._output["sources"].update(out) def write_storage_layout_overrides( self, compilation_target_path: str, storage_layout_override: JSONInput ): # TODO: generalize to multiple files ret = {} path = _anonymize(str(storage_layout_override.path)) ret[compilation_target_path] = {path: storage_layout_override.data} self._output["storage_layout_overrides"] = ret def write_search_paths(self, search_paths: list[str]): self._output["settings"]["search_paths"] = search_paths def write_settings(self, settings: Optional[Settings]): if settings is not None: s = settings.as_dict() if "evm_version" in s: s["evmVersion"] = s.pop("evm_version") if "experimental_codegen" in s: s["experimentalCodegen"] = s.pop("experimental_codegen") self._output["settings"].update(s) def write_integrity(self, integrity_sum: str): self._output["integrity"] = integrity_sum def write_compilation_target(self, targets: list[str]): for target in targets: self._output["settings"]["outputSelection"][target] = ["*"] def write_version(self, version): self._output["compiler_version"] = version def output(self): return self._output def _get_compression_method(): # try to find a compression library, if none are available then # fall back to ZIP_STORED # (note: these should all be on all modern systems and in particular # they should be in the build environment for our build artifacts, # but write the graceful fallback anyway because hygiene). try: importlib.import_module("zlib") return zipfile.ZIP_DEFLATED except ImportError: pass # fallback return zipfile.ZIP_STORED
SolcJSONWriter
python
spack__spack
lib/spack/spack/detection/path.py
{ "start": 8821, "end": 14435 }
class ____: """Inspects the file-system looking for packages. Guesses places where to look using PATH.""" def default_path_hints(self) -> List[str]: return [] def search_patterns(self, *, pkg: Type["spack.package_base.PackageBase"]) -> List[str]: """Returns the list of patterns used to match candidate files. Args: pkg: package being detected """ raise NotImplementedError("must be implemented by derived classes") def candidate_files(self, *, patterns: List[str], paths: List[str]) -> List[str]: """Returns a list of candidate files found on the system. Args: patterns: search patterns to be used for matching files paths: paths where to search for files """ raise NotImplementedError("must be implemented by derived classes") def prefix_from_path(self, *, path: str) -> str: """Given a path where a file was found, returns the corresponding prefix. Args: path: path of a detected file """ raise NotImplementedError("must be implemented by derived classes") def detect_specs( self, *, pkg: Type["spack.package_base.PackageBase"], paths: Iterable[str], repo_path ) -> List["spack.spec.Spec"]: """Given a list of files matching the search patterns, returns a list of detected specs. Args: pkg: package being detected paths: files matching the package search patterns """ if not hasattr(pkg, "determine_spec_details"): warnings.warn( f"{pkg.name} must define 'determine_spec_details' in order" f" for Spack to detect externally-provided instances" f" of the package." ) return [] result = [] for candidate_path, items_in_prefix in _group_by_prefix( spack.llnl.util.lang.dedupe(paths) ).items(): # TODO: multiple instances of a package can live in the same # prefix, and a package implementation can return multiple specs # for one prefix, but without additional details (e.g. about the # naming scheme which differentiates them), the spec won't be # usable. try: specs = _convert_to_iterable( pkg.determine_spec_details(candidate_path, items_in_prefix) ) except Exception as e: specs = [] if spack.error.SHOW_BACKTRACE: details = traceback.format_exc() else: details = f"[{e.__class__.__name__}: {e}]" warnings.warn( f'error detecting "{pkg.name}" from prefix {candidate_path}: {details}' ) if not specs: files = ", ".join(_convert_to_iterable(items_in_prefix)) spack.llnl.util.tty.debug( f"The following files in {candidate_path} were decidedly not " f"part of the package {pkg.name}: {files}" ) resolved_specs: Dict[spack.spec.Spec, str] = {} # spec -> exe found for the spec for spec in specs: prefix = self.prefix_from_path(path=candidate_path) if not prefix: continue if spec in resolved_specs: prior_prefix = ", ".join(_convert_to_iterable(resolved_specs[spec])) spack.llnl.util.tty.debug( f"Files in {candidate_path} and {prior_prefix} are both associated" f" with the same spec {str(spec)}" ) continue resolved_specs[spec] = candidate_path try: # Validate the spec calling a package specific method pkg_cls = repo_path.get_pkg_class(spec.name) validate_fn = getattr(pkg_cls, "validate_detected_spec", lambda x, y: None) validate_fn(spec, spec.extra_attributes) except Exception as e: msg = ( f'"{spec}" has been detected on the system but will ' f"not be added to packages.yaml [reason={str(e)}]" ) warnings.warn(msg) continue if not spec.external_path: spec.external_path = prefix result.append(spec) return result def find( self, *, pkg_name: str, repository, initial_guess: Optional[List[str]] = None ) -> List["spack.spec.Spec"]: """For a given package, returns a list of detected specs. Args: pkg_name: package being detected repository: repository to retrieve the package initial_guess: initial list of paths to search from the caller if None, default paths are searched. If this is an empty list, nothing will be searched. """ pkg_cls = repository.get_pkg_class(pkg_name) patterns = self.search_patterns(pkg=pkg_cls) if not patterns: return [] if initial_guess is None: initial_guess = self.default_path_hints() initial_guess.extend(common_windows_package_paths(pkg_cls)) candidates = self.candidate_files(patterns=patterns, paths=initial_guess) return self.detect_specs(pkg=pkg_cls, paths=candidates, repo_path=repository)
Finder
python
bokeh__bokeh
src/bokeh/models/axes.py
{ "start": 8636, "end": 9100 }
class ____(ContinuousAxis): ''' An axis that picks nice numbers for tick locations on a linear scale. Configured with a ``BasicTickFormatter`` by default. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) ticker = Override(default=InstanceDefault(BasicTicker)) formatter = Override(default=InstanceDefault(BasicTickFormatter))
LinearAxis
python
ray-project__ray
python/ray/_private/utils.py
{ "start": 50966, "end": 58445 }
class ____(contextlib.AbstractContextManager): """Context manager that defers SIGINT signals until the context is left.""" # This is used by Ray's task cancellation to defer cancellation interrupts during # problematic areas, e.g. task argument deserialization. def __init__(self): # Whether a SIGINT signal was received during the context. self.signal_received = False # The overridden SIGINT handler self.overridden_sigint_handler = None # The original signal method. self.orig_signal = None @classmethod def create_if_main_thread(cls) -> contextlib.AbstractContextManager: """Creates a DeferSigint context manager if running on the main thread, returns a no-op context manager otherwise. """ if threading.current_thread() == threading.main_thread(): return cls() else: return contextlib.nullcontext() def _set_signal_received(self, signum, frame): """SIGINT handler that defers the signal.""" self.signal_received = True def _signal_monkey_patch(self, signum, handler): """Monkey patch for signal.signal that defers the setting of new signal handler after the DeferSigint context exits.""" # Only handle it in the main thread because if setting a handler in a non-main # thread, signal.signal will raise an error because Python doesn't allow it. if ( threading.current_thread() == threading.main_thread() and signum == signal.SIGINT ): orig_sigint_handler = self.overridden_sigint_handler self.overridden_sigint_handler = handler return orig_sigint_handler return self.orig_signal(signum, handler) def __enter__(self): # Save original SIGINT handler for later restoration. self.overridden_sigint_handler = signal.getsignal(signal.SIGINT) # Set SIGINT signal handler that defers the signal. signal.signal(signal.SIGINT, self._set_signal_received) # Monkey patch signal.signal to raise an error if a SIGINT handler is registered # within the context. self.orig_signal = signal.signal signal.signal = self._signal_monkey_patch return self def __exit__(self, exc_type, exc, exc_tb): assert self.overridden_sigint_handler is not None assert self.orig_signal is not None # Restore original signal.signal function. signal.signal = self.orig_signal # Restore overridden SIGINT handler. signal.signal(signal.SIGINT, self.overridden_sigint_handler) if exc_type is None and self.signal_received: # No exception raised in context, call the original SIGINT handler. # By default, this means raising KeyboardInterrupt. self.overridden_sigint_handler(signal.SIGINT, None) else: # If exception was raised in context, returning False will cause it to be # reraised. return False def try_import_each_module(module_names_to_import: List[str]) -> None: """ Make a best-effort attempt to import each named Python module. This is used by the Python default_worker.py to preload modules. """ for module_to_preload in module_names_to_import: try: importlib.import_module(module_to_preload) except ImportError: logger.exception(f'Failed to preload the module "{module_to_preload}"') def remove_ray_internal_flags_from_env(env: dict): """ Remove Ray internal flags from `env`. Defined in ray/common/ray_internal_flag_def.h """ for flag in ray_constants.RAY_INTERNAL_FLAGS: env.pop(flag, None) def update_envs(env_vars: Dict[str, str]): """ When updating the environment variable, if there is ${X}, it will be replaced with the current environment variable. """ if not env_vars: return for key, value in env_vars.items(): expanded = os.path.expandvars(value) # Replace non-existant env vars with an empty string. result = re.sub(r"\$\{[A-Z0-9_]+\}", "", expanded) os.environ[key] = result def parse_pg_formatted_resources_to_original( pg_formatted_resources: Dict[str, float] ) -> Dict[str, float]: original_resources = {} for key, value in pg_formatted_resources.items(): result = PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN.match(key) if result and len(result.groups()) == 3: # Filter out resources that have bundle_group_[pg_id] since # it is an implementation detail. # This resource is automatically added to the resource # request for all tasks that require placement groups. if result.group(1) == PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME: continue original_resources[result.group(1)] = value continue result = PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN.match(key) if result and len(result.groups()) == 2: if result.group(1) == "bundle": continue original_resources[result.group(1)] = value continue original_resources[key] = value return original_resources def validate_actor_state_name(actor_state_name): if actor_state_name is None: return actor_state_names = [ "DEPENDENCIES_UNREADY", "PENDING_CREATION", "ALIVE", "RESTARTING", "DEAD", ] if actor_state_name not in actor_state_names: raise ValueError( f'"{actor_state_name}" is not a valid actor state name, ' 'it must be one of the following: "DEPENDENCIES_UNREADY", ' '"PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD"' ) def get_current_node_cpu_model_name() -> Optional[str]: if not sys.platform.startswith("linux"): return None try: """ /proc/cpuinfo content example: processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 85 model name : Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz stepping : 7 """ with open("/proc/cpuinfo", "r") as f: for line in f: if line.startswith("model name"): return line.split(":")[1].strip() return None except Exception: logger.debug("Failed to get CPU model name", exc_info=True) return None def validate_socket_filepath(filepath: str): """ Validate the provided filename is a valid Unix socket filename. """ # Don't check for Windows as it doesn't support Unix sockets. if sys.platform == "win32": return is_mac = sys.platform.startswith("darwin") maxlen = (104 if is_mac else 108) - 1 if len(filepath.encode("utf-8")) > maxlen: raise OSError( f"validate_socket_filename failed: AF_UNIX path length cannot exceed {maxlen} bytes: {filepath}" ) # Whether we're currently running in a test, either local or CI. in_test = None def is_in_test(): global in_test if in_test is None: in_test = any( env_var in os.environ # These environment variables are always set by pytest and Buildkite, # respectively. for env_var in ("PYTEST_CURRENT_TEST", "BUILDKITE") ) return in_test
DeferSigint
python
django__django
tests/sessions_tests/tests.py
{ "start": 33593, "end": 36866 }
class ____(SessionTestsMixin, SimpleTestCase): backend = FileSession def setUp(self): # Do file session tests in an isolated directory, and kill it after # we're done. self.original_session_file_path = settings.SESSION_FILE_PATH self.temp_session_store = settings.SESSION_FILE_PATH = self.mkdtemp() self.addCleanup(shutil.rmtree, self.temp_session_store) # Reset the file session backend's internal caches if hasattr(self.backend, "_storage_path"): del self.backend._storage_path super().setUp() def tearDown(self): super().tearDown() settings.SESSION_FILE_PATH = self.original_session_file_path def mkdtemp(self): return tempfile.mkdtemp() @override_settings( SESSION_FILE_PATH="/if/this/directory/exists/you/have/a/weird/computer", ) def test_configuration_check(self): del self.backend._storage_path # Make sure the file backend checks for a good storage dir with self.assertRaises(ImproperlyConfigured): self.backend() def test_invalid_key_backslash(self): # Ensure we don't allow directory-traversal. # This is tested directly on _key_to_file, as load() will swallow # a SuspiciousOperation in the same way as an OSError - by creating # a new session, making it unclear whether the slashes were detected. with self.assertRaises(InvalidSessionKey): self.backend()._key_to_file("a\\b\\c") def test_invalid_key_forwardslash(self): # Ensure we don't allow directory-traversal with self.assertRaises(InvalidSessionKey): self.backend()._key_to_file("a/b/c") @override_settings( SESSION_ENGINE="django.contrib.sessions.backends.file", SESSION_COOKIE_AGE=0, ) def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ storage_path = self.backend._get_storage_path() file_prefix = settings.SESSION_COOKIE_NAME def count_sessions(): return len( [ session_file for session_file in os.listdir(storage_path) if session_file.startswith(file_prefix) ] ) self.assertEqual(0, count_sessions()) # One object in the future self.session["foo"] = "bar" self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session["foo"] = "bar" other_session.set_expiry(-3600) other_session.save() # One object in the present without an expiry (should be deleted since # its modification time + SESSION_COOKIE_AGE will be in the past when # clearsessions runs). other_session2 = self.backend() other_session2["foo"] = "bar" other_session2.save() # Three sessions are in the filesystem before clearsessions... self.assertEqual(3, count_sessions()) management.call_command("clearsessions") # ... and two are deleted. self.assertEqual(1, count_sessions())
FileSessionTests
python
ipython__ipython
IPython/core/display.py
{ "start": 12783, "end": 13414 }
class ____(DisplayObject): """Create a text display object given raw data. Parameters ---------- data : str or unicode The raw data or a URL or file to load the data from. url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. metadata : dict Dict of metadata associated to be the object when displayed """ def _check_data(self): if self.data is not None and not isinstance(self.data, str): raise TypeError("%s expects text, not %r" % (self.__class__.__name__, self.data))
TextDisplayObject
python
rapidsai__cudf
python/cudf_polars/cudf_polars/typing/__init__.py
{ "start": 4830, "end": 4922 }
class ____(TypedDict): kind: Literal["list"] inner: DataTypeHeader
_ListDataTypeHeader
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-mcp/tests/schemas.py
{ "start": 237, "end": 283 }
class ____(BaseModel): lst: List[int]
TestList
python
miyuchina__mistletoe
test/test_span_token.py
{ "start": 6151, "end": 6833 }
class ____(unittest.TestCase): def test_attribute(self): token = span_token.RawText('some text') self.assertEqual(token.content, 'some text') def test_no_children(self): token = span_token.RawText('some text') self.assertIsNone(token.children) def test_valid_html_entities(self): tokens = span_token.tokenize_inner('&nbsp; &#21512;') self.assertEqual(tokens[0].content, '\xa0 \u5408') def test_invalid_html_entities(self): text = '&nbsp &x; &#; &#x; &#87654321; &#abcdef0; &ThisIsNotDefined; &hi?;' tokens = span_token.tokenize_inner(text) self.assertEqual(tokens[0].content, text)
TestRawText
python
huggingface__transformers
src/transformers/models/paligemma/configuration_paligemma.py
{ "start": 886, "end": 5679 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`PaliGemmaForConditionalGeneration`]. It is used to instantiate an PaliGemmamodel according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the PaliGemma-2B. e.g. [paligemma-hf/paligemma-2b](https://huggingface.co/paligemma-hf/paligemma-2b) Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: vision_config (`PaliGemmaVisionConfig`, *optional*): Custom vision config or dict text_config (`Union[AutoConfig, dict]`, *optional*): The config object of the text backbone. Can be any of `LlamaConfig` or `MistralConfig`. image_token_index (`int`, *optional*, defaults to 256000): The image token index to encode the image prompt. vocab_size (`int`, *optional*, defaults to 257152): Vocabulary size of the PaliGemmamodel. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`~PaliGemmaForConditionalGeneration`] projection_dim (`int`, *optional*, defaults to 2048): Dimension of the multimodal projection space. hidden_size (`int`, *optional*, defaults to 2048): Dimension of the hidden layer of the Language model. Example: ```python >>> from transformers import PaliGemmaForConditionalGeneration, PaliGemmaConfig, SiglipVisionConfig, GemmaConfig >>> # Initializing a Siglip-like vision config >>> vision_config = SiglipVisionConfig() >>> # Initializing a PaliGemma config >>> text_config = GemmaConfig() >>> # Initializing a PaliGemma paligemma-3b-224 style configuration >>> configuration = PaliGemmaConfig(vision_config, text_config) >>> # Initializing a model from the paligemma-3b-224 style configuration >>> model = PaliGemmaForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "paligemma" attribute_map = { "image_token_id": "image_token_index", } sub_configs = {"text_config": AutoConfig, "vision_config": AutoConfig} keys_to_ignore_at_inference = ["past_key_values"] def __init__( self, vision_config=None, text_config=None, image_token_index=256000, vocab_size=257152, projection_dim=2048, hidden_size=2048, **kwargs, ): self.image_token_index = image_token_index self.projection_dim = projection_dim self.hidden_size = hidden_size self.vision_config = vision_config self.is_encoder_decoder = False if isinstance(self.vision_config, dict): vision_config["model_type"] = vision_config.get("model_type", "siglip_vision_model") self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](**vision_config) elif vision_config is None: self.vision_config = CONFIG_MAPPING["siglip_vision_model"]( intermediate_size=4096, hidden_size=1152, patch_size=14, image_size=224, num_hidden_layers=27, num_attention_heads=16, vocab_size=257152, vision_use_head=False, ) self.text_config = text_config if isinstance(self.text_config, dict): text_config["model_type"] = text_config.get("model_type", "gemma") self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config) elif text_config is None: self.text_config = CONFIG_MAPPING["gemma"]( hidden_size=2048, num_hidden_layers=18, intermediate_size=16384, num_attention_heads=8, num_key_value_heads=1, is_encoder_decoder=False, vocab_size=vocab_size, ) # BC: `use_bidirectional_attention` was originally unset in PaliGemma1 (backbone = Gemma1) AND PaliGemma2 # (backbone = Gemma2). Both PaliGemmas want to default to True. if self.text_config.use_bidirectional_attention is None: self.text_config.use_bidirectional_attention = True self.text_config.num_image_tokens = (self.vision_config.image_size // self.vision_config.patch_size) ** 2 self.vision_config.projection_dim = projection_dim super().__init__(**kwargs) __all__ = ["PaliGemmaConfig"]
PaliGemmaConfig
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType24.py
{ "start": 206, "end": 285 }
class ____(Iterable[T]): def __iter__(self) -> Iterator[T]: ...
IterableProxy
python
sqlalchemy__sqlalchemy
test/dialect/postgresql/test_types.py
{ "start": 209549, "end": 218115 }
class ____(fixtures.TablesTest): __only_on__ = ("postgresql >= 9.3",) __backend__ = True data_type = JSON @classmethod def define_tables(cls, metadata): Table( "data_table", metadata, Column("id", Integer, primary_key=True), Column("name", String(30), nullable=False), Column("data", cls.data_type), Column("nulldata", cls.data_type(none_as_null=True)), ) @property def data_table(self): return self.tables.data_table def _fixture_data(self, connection): data = [ {"name": "r1", "data": {"k1": "r1v1", "k2": "r1v2"}}, {"name": "r2", "data": {"k1": "r2v1", "k2": "r2v2"}}, {"name": "r3", "data": {"k1": "r3v1", "k2": "r3v2"}}, {"name": "r4", "data": {"k1": "r4v1", "k2": "r4v2"}}, {"name": "r5", "data": {"k1": "r5v1", "k2": "r5v2", "k3": 5}}, {"name": "r6", "data": {"k1": {"r6v1": {"subr": [1, 2, 3]}}}}, ] connection.execute(self.data_table.insert(), data) return data def _assert_data(self, compare, conn, column="data"): col = self.data_table.c[column] data = conn.execute( select(col).order_by(self.data_table.c.name) ).fetchall() eq_([d for d, in data], compare) def _assert_column_is_NULL(self, conn, column="data"): col = self.data_table.c[column] data = conn.execute(select(col).where(col.is_(null()))).fetchall() eq_([d for d, in data], [None]) def _assert_column_is_JSON_NULL(self, conn, column="data"): col = self.data_table.c[column] data = conn.execute( select(col).where(cast(col, String) == "null") ).fetchall() eq_([d for d, in data], [None]) @testing.combinations( "key", "réve🐍 illé", 'name_with"quotes"name', "name with spaces", "name with ' single ' quotes", 'some_key("idx")', argnames="key", ) def test_indexed_special_keys(self, connection, key): data_table = self.data_table data_element = {key: "some value"} connection.execute( data_table.insert(), { "name": "row1", "data": data_element, "nulldata": data_element, }, ) row = connection.execute( select(data_table.c.data[key], data_table.c.nulldata[key]) ).one() eq_(row, ("some value", "some value")) def test_reflect(self, connection): insp = inspect(connection) cols = insp.get_columns("data_table") assert isinstance(cols[2]["type"], self.data_type) def test_insert(self, connection): connection.execute( self.data_table.insert(), {"name": "r1", "data": {"k1": "r1v1", "k2": "r1v2"}}, ) self._assert_data([{"k1": "r1v1", "k2": "r1v2"}], connection) def test_insert_nulls(self, connection): connection.execute( self.data_table.insert(), {"name": "r1", "data": null()} ) self._assert_data([None], connection) def test_insert_none_as_null(self, connection): connection.execute( self.data_table.insert(), {"name": "r1", "nulldata": None}, ) self._assert_column_is_NULL(connection, column="nulldata") def test_insert_nulljson_into_none_as_null(self, connection): connection.execute( self.data_table.insert(), {"name": "r1", "nulldata": JSON.NULL}, ) self._assert_column_is_JSON_NULL(connection, column="nulldata") def test_custom_serialize_deserialize(self, testing_engine): import json def loads(value): value = json.loads(value) value["x"] = value["x"] + "_loads" return value def dumps(value): value = dict(value) value["x"] = "dumps_y" return json.dumps(value) engine = testing_engine( options=dict(json_serializer=dumps, json_deserializer=loads) ) s = select(cast({"key": "value", "x": "q"}, self.data_type)) with engine.begin() as conn: eq_(conn.scalar(s), {"key": "value", "x": "dumps_y_loads"}) def test_criterion(self, connection): self._fixture_data(connection) data_table = self.tables.data_table result = connection.execute( select(data_table.c.data).where( data_table.c.data["k1"].astext == "r3v1" ) ).first() eq_(result, ({"k1": "r3v1", "k2": "r3v2"},)) result = connection.execute( select(data_table.c.data).where( data_table.c.data["k1"].astext.cast(String) == "r3v1" ) ).first() eq_(result, ({"k1": "r3v1", "k2": "r3v2"},)) def test_path_query(self, connection): self._fixture_data(connection) data_table = self.tables.data_table result = connection.execute( select(data_table.c.name).where( data_table.c.data[("k1", "r6v1", "subr")].astext == "[1, 2, 3]" ) ) eq_(result.scalar(), "r6") @testing.fails_on( "postgresql < 9.4", "Improvement in PostgreSQL behavior?" ) def test_multi_index_query(self, connection): self._fixture_data(connection) data_table = self.tables.data_table result = connection.execute( select(data_table.c.name).where( data_table.c.data["k1"]["r6v1"]["subr"].astext == "[1, 2, 3]" ) ) eq_(result.scalar(), "r6") def test_query_returned_as_text(self, connection): self._fixture_data(connection) result = connection.execute( select(self.data_table.c.data["k1"].astext) ).first() assert isinstance(result[0], str) def test_query_returned_as_int(self, connection): self._fixture_data(connection) data_table = self.tables.data_table result = connection.execute( select(data_table.c.data["k3"].astext.cast(Integer)).where( data_table.c.name == "r5" ) ).first() assert isinstance(result[0], int) def test_fixed_round_trip(self, connection): s = select( cast( {"key": "value", "key2": {"k1": "v1", "k2": "v2"}}, self.data_type, ) ) eq_( connection.scalar(s), {"key": "value", "key2": {"k1": "v1", "k2": "v2"}}, ) def test_unicode_round_trip(self, connection): s = select( cast( { "réveillé": "réveillé", "data": {"k1": "drôle"}, }, self.data_type, ) ) eq_( connection.scalar(s), { "réveillé": "réveillé", "data": {"k1": "drôle"}, }, ) def test_eval_none_flag_orm(self, connection): Base = declarative_base() class Data(Base): __table__ = self.tables.data_table with Session(connection) as s: d1 = Data(name="d1", data=None, nulldata=None) s.add(d1) s.commit() s.bulk_insert_mappings( Data, [{"name": "d2", "data": None, "nulldata": None}] ) eq_( s.query( cast(self.tables.data_table.c.data, String), cast(self.tables.data_table.c.nulldata, String), ) .filter(self.tables.data_table.c.name == "d1") .first(), ("null", None), ) eq_( s.query( cast(self.tables.data_table.c.data, String), cast(self.tables.data_table.c.nulldata, String), ) .filter(self.tables.data_table.c.name == "d2") .first(), ("null", None), ) def test_literal(self, connection): exp = self._fixture_data(connection) result = connection.exec_driver_sql( "select data from data_table order by name" ) res = list(result) eq_(len(res), len(exp)) for row, expected in zip(res, exp): eq_(row[0], expected["data"])
JSONRoundTripTest
python
scikit-learn__scikit-learn
sklearn/metrics/_plot/precision_recall_curve.py
{ "start": 386, "end": 20526 }
class ____(_BinaryClassifierCurveDisplayMixin): """Precision Recall visualization. It is recommended to use :func:`~sklearn.metrics.PrecisionRecallDisplay.from_estimator` or :func:`~sklearn.metrics.PrecisionRecallDisplay.from_predictions` to create a :class:`~sklearn.metrics.PrecisionRecallDisplay`. All parameters are stored as attributes. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <precision_recall_f_measure_metrics>`. Parameters ---------- precision : ndarray Precision values. recall : ndarray Recall values. average_precision : float, default=None Average precision. If None, the average precision is not shown. name : str, default=None Name of estimator. If None, then the estimator name is not shown. .. versionchanged:: 1.8 `estimator_name` was deprecated in favor of `name`. pos_label : int, float, bool or str, default=None The class considered the positive class when precision and recall metrics computed. If not `None`, this value is displayed in the x- and y-axes labels. .. versionadded:: 0.24 prevalence_pos_label : float, default=None The prevalence of the positive label. It is used for plotting the chance level line. If None, the chance level line will not be plotted even if `plot_chance_level` is set to True when plotting. .. versionadded:: 1.3 estimator_name : str, default=None Name of estimator. If None, the estimator name is not shown. .. deprecated:: 1.8 `estimator_name` is deprecated and will be removed in 1.10. Use `name` instead. Attributes ---------- line_ : matplotlib Artist Precision recall curve. chance_level_ : matplotlib Artist or None The chance level line. It is `None` if the chance level is not plotted. .. versionadded:: 1.3 ax_ : matplotlib Axes Axes with precision recall curve. figure_ : matplotlib Figure Figure containing the curve. See Also -------- precision_recall_curve : Compute precision-recall pairs for different probability thresholds. PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given a binary classifier. PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve using predictions from a binary classifier. Notes ----- The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) in scikit-learn is computed without any interpolation. To be consistent with this metric, the precision-recall curve is plotted without any interpolation as well (step-wise style). You can change this style by passing the keyword argument `drawstyle="default"` in :meth:`plot`, :meth:`from_estimator`, or :meth:`from_predictions`. However, the curve will not be strictly consistent with the reported average precision. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import make_classification >>> from sklearn.metrics import (precision_recall_curve, ... PrecisionRecallDisplay) >>> from sklearn.model_selection import train_test_split >>> from sklearn.svm import SVC >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split(X, y, ... random_state=0) >>> clf = SVC(random_state=0) >>> clf.fit(X_train, y_train) SVC(random_state=0) >>> predictions = clf.predict(X_test) >>> precision, recall, _ = precision_recall_curve(y_test, predictions) >>> disp = PrecisionRecallDisplay(precision=precision, recall=recall) >>> disp.plot() <...> >>> plt.show() """ def __init__( self, precision, recall, *, average_precision=None, name=None, pos_label=None, prevalence_pos_label=None, estimator_name="deprecated", ): self.name = _deprecate_estimator_name(estimator_name, name, "1.8") self.precision = precision self.recall = recall self.average_precision = average_precision self.pos_label = pos_label self.prevalence_pos_label = prevalence_pos_label def plot( self, ax=None, *, name=None, plot_chance_level=False, chance_level_kw=None, despine=False, **kwargs, ): """Plot visualization. Extra keyword arguments will be passed to matplotlib's `plot`. Parameters ---------- ax : Matplotlib Axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. name : str, default=None Name of precision recall curve for labeling. If `None`, use `name` if not `None`, otherwise no labeling is shown. plot_chance_level : bool, default=False Whether to plot the chance level. The chance level is the prevalence of the positive label computed from the data passed during :meth:`from_estimator` or :meth:`from_predictions` call. .. versionadded:: 1.3 chance_level_kw : dict, default=None Keyword arguments to be passed to matplotlib's `plot` for rendering the chance level line. .. versionadded:: 1.3 despine : bool, default=False Whether to remove the top and right spines from the plot. .. versionadded:: 1.6 **kwargs : dict Keyword arguments to be passed to matplotlib's `plot`. Returns ------- display : :class:`~sklearn.metrics.PrecisionRecallDisplay` Object that stores computed values. Notes ----- The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) in scikit-learn is computed without any interpolation. To be consistent with this metric, the precision-recall curve is plotted without any interpolation as well (step-wise style). You can change this style by passing the keyword argument `drawstyle="default"`. However, the curve will not be strictly consistent with the reported average precision. """ self.ax_, self.figure_, name = self._validate_plot_params(ax=ax, name=name) default_line_kwargs = {"drawstyle": "steps-post"} if self.average_precision is not None and name is not None: default_line_kwargs["label"] = ( f"{name} (AP = {self.average_precision:0.2f})" ) elif self.average_precision is not None: default_line_kwargs["label"] = f"AP = {self.average_precision:0.2f}" elif name is not None: default_line_kwargs["label"] = name line_kwargs = _validate_style_kwargs(default_line_kwargs, kwargs) (self.line_,) = self.ax_.plot(self.recall, self.precision, **line_kwargs) info_pos_label = ( f" (Positive label: {self.pos_label})" if self.pos_label is not None else "" ) xlabel = "Recall" + info_pos_label ylabel = "Precision" + info_pos_label self.ax_.set( xlabel=xlabel, xlim=(-0.01, 1.01), ylabel=ylabel, ylim=(-0.01, 1.01), aspect="equal", ) if plot_chance_level: if self.prevalence_pos_label is None: raise ValueError( "You must provide prevalence_pos_label when constructing the " "PrecisionRecallDisplay object in order to plot the chance " "level line. Alternatively, you may use " "PrecisionRecallDisplay.from_estimator or " "PrecisionRecallDisplay.from_predictions " "to automatically set prevalence_pos_label" ) default_chance_level_line_kw = { "label": f"Chance level (AP = {self.prevalence_pos_label:0.2f})", "color": "k", "linestyle": "--", } if chance_level_kw is None: chance_level_kw = {} chance_level_line_kw = _validate_style_kwargs( default_chance_level_line_kw, chance_level_kw ) (self.chance_level_,) = self.ax_.plot( (0, 1), (self.prevalence_pos_label, self.prevalence_pos_label), **chance_level_line_kw, ) else: self.chance_level_ = None if despine: _despine(self.ax_) if "label" in line_kwargs or plot_chance_level: self.ax_.legend(loc="lower left") return self @classmethod def from_estimator( cls, estimator, X, y, *, sample_weight=None, drop_intermediate=False, response_method="auto", pos_label=None, name=None, ax=None, plot_chance_level=False, chance_level_kw=None, despine=False, **kwargs, ): """Plot precision-recall curve given an estimator and some data. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <precision_recall_f_measure_metrics>`. Parameters ---------- estimator : estimator instance Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a classifier. X : {array-like, sparse matrix} of shape (n_samples, n_features) Input values. y : array-like of shape (n_samples,) Target values. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop some suboptimal thresholds which would not appear on a plotted precision-recall curve. This is useful in order to create lighter precision-recall curves. .. versionadded:: 1.3 response_method : {'predict_proba', 'decision_function', 'auto'}, \ default='auto' Specifies whether to use :term:`predict_proba` or :term:`decision_function` as the target response. If set to 'auto', :term:`predict_proba` is tried first and if it does not exist :term:`decision_function` is tried next. pos_label : int, float, bool or str, default=None The class considered as the positive class when computing the precision and recall metrics. By default, `estimators.classes_[1]` is considered as the positive class. name : str, default=None Name for labeling curve. If `None`, no name is used. ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. plot_chance_level : bool, default=False Whether to plot the chance level. The chance level is the prevalence of the positive label computed from the data passed during :meth:`from_estimator` or :meth:`from_predictions` call. .. versionadded:: 1.3 chance_level_kw : dict, default=None Keyword arguments to be passed to matplotlib's `plot` for rendering the chance level line. .. versionadded:: 1.3 despine : bool, default=False Whether to remove the top and right spines from the plot. .. versionadded:: 1.6 **kwargs : dict Keyword arguments to be passed to matplotlib's `plot`. Returns ------- display : :class:`~sklearn.metrics.PrecisionRecallDisplay` See Also -------- PrecisionRecallDisplay.from_predictions : Plot precision-recall curve using estimated probabilities or output of decision function. Notes ----- The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) in scikit-learn is computed without any interpolation. To be consistent with this metric, the precision-recall curve is plotted without any interpolation as well (step-wise style). You can change this style by passing the keyword argument `drawstyle="default"`. However, the curve will not be strictly consistent with the reported average precision. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import make_classification >>> from sklearn.metrics import PrecisionRecallDisplay >>> from sklearn.model_selection import train_test_split >>> from sklearn.linear_model import LogisticRegression >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> clf = LogisticRegression() >>> clf.fit(X_train, y_train) LogisticRegression() >>> PrecisionRecallDisplay.from_estimator( ... clf, X_test, y_test) <...> >>> plt.show() """ y_score, pos_label, name = cls._validate_and_get_response_values( estimator, X, y, response_method=response_method, pos_label=pos_label, name=name, ) return cls.from_predictions( y, y_score, sample_weight=sample_weight, name=name, pos_label=pos_label, drop_intermediate=drop_intermediate, ax=ax, plot_chance_level=plot_chance_level, chance_level_kw=chance_level_kw, despine=despine, **kwargs, ) @classmethod def from_predictions( cls, y_true, y_score=None, *, sample_weight=None, drop_intermediate=False, pos_label=None, name=None, ax=None, plot_chance_level=False, chance_level_kw=None, despine=False, y_pred="deprecated", **kwargs, ): """Plot precision-recall curve given binary class predictions. For general information regarding `scikit-learn` visualization tools, see the :ref:`Visualization Guide <visualizations>`. For guidance on interpreting these plots, refer to the :ref:`Model Evaluation Guide <precision_recall_f_measure_metrics>`. Parameters ---------- y_true : array-like of shape (n_samples,) True binary labels. y_score : array-like of shape (n_samples,) Estimated probabilities or output of decision function. .. versionadded:: 1.8 `y_pred` has been renamed to `y_score`. sample_weight : array-like of shape (n_samples,), default=None Sample weights. drop_intermediate : bool, default=False Whether to drop some suboptimal thresholds which would not appear on a plotted precision-recall curve. This is useful in order to create lighter precision-recall curves. .. versionadded:: 1.3 pos_label : int, float, bool or str, default=None The class considered as the positive class when computing the precision and recall metrics. When `pos_label=None`, if `y_true` is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an error will be raised. name : str, default=None Name for labeling curve. If `None`, name will be set to `"Classifier"`. ax : matplotlib axes, default=None Axes object to plot on. If `None`, a new figure and axes is created. plot_chance_level : bool, default=False Whether to plot the chance level. The chance level is the prevalence of the positive label computed from the data passed during :meth:`from_estimator` or :meth:`from_predictions` call. .. versionadded:: 1.3 chance_level_kw : dict, default=None Keyword arguments to be passed to matplotlib's `plot` for rendering the chance level line. .. versionadded:: 1.3 despine : bool, default=False Whether to remove the top and right spines from the plot. .. versionadded:: 1.6 y_pred : array-like of shape (n_samples,) Estimated probabilities or output of decision function. .. deprecated:: 1.8 `y_pred` is deprecated and will be removed in 1.10. Use `y_score` instead. **kwargs : dict Keyword arguments to be passed to matplotlib's `plot`. Returns ------- display : :class:`~sklearn.metrics.PrecisionRecallDisplay` See Also -------- PrecisionRecallDisplay.from_estimator : Plot precision-recall curve using an estimator. Notes ----- The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) in scikit-learn is computed without any interpolation. To be consistent with this metric, the precision-recall curve is plotted without any interpolation as well (step-wise style). You can change this style by passing the keyword argument `drawstyle="default"`. However, the curve will not be strictly consistent with the reported average precision. Examples -------- >>> import matplotlib.pyplot as plt >>> from sklearn.datasets import make_classification >>> from sklearn.metrics import PrecisionRecallDisplay >>> from sklearn.model_selection import train_test_split >>> from sklearn.linear_model import LogisticRegression >>> X, y = make_classification(random_state=0) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> clf = LogisticRegression() >>> clf.fit(X_train, y_train) LogisticRegression() >>> y_score = clf.predict_proba(X_test)[:, 1] >>> PrecisionRecallDisplay.from_predictions( ... y_test, y_score) <...> >>> plt.show() """ y_score = _deprecate_y_pred_parameter(y_score, y_pred, "1.8") pos_label, name = cls._validate_from_predictions_params( y_true, y_score, sample_weight=sample_weight, pos_label=pos_label, name=name ) precision, recall, _ = precision_recall_curve( y_true, y_score, pos_label=pos_label, sample_weight=sample_weight, drop_intermediate=drop_intermediate, ) average_precision = average_precision_score( y_true, y_score, pos_label=pos_label, sample_weight=sample_weight ) class_count = Counter(y_true) prevalence_pos_label = class_count[pos_label] / sum(class_count.values()) viz = cls( precision=precision, recall=recall, average_precision=average_precision, name=name, pos_label=pos_label, prevalence_pos_label=prevalence_pos_label, ) return viz.plot( ax=ax, name=name, plot_chance_level=plot_chance_level, chance_level_kw=chance_level_kw, despine=despine, **kwargs, )
PrecisionRecallDisplay
python
getsentry__sentry
src/sentry/preprod/size_analysis/models.py
{ "start": 1012, "end": 1141 }
class ____(str, Enum): ADDED = "added" REMOVED = "removed" INCREASED = "increased" DECREASED = "decreased"
DiffType
python
ApeWorX__ape
src/ape/cli/commands.py
{ "start": 2144, "end": 5433 }
class ____(click.Command): """ A command that uses the :meth:`~ape.cli.options.network_option`. It will automatically set the network for the duration of the command execution. """ def __init__(self, *args, **kwargs): self._use_cls_types = kwargs.pop("use_cls_types", True) self._network_callback = kwargs.pop("network_callback", None) super().__init__(*args, **kwargs) def parse_args(self, ctx: "Context", args: list[str]) -> list[str]: arguments = args # Renamed for better pdb support. base_type: Optional[type] = None if self._use_cls_types else str if existing_option := next( iter( x for x in self.params if isinstance(x, click.core.Option) and x.name == "network" and isinstance(x.type, NetworkChoice) ), None, ): if base_type is None: from ape.api.providers import ProviderAPI base_type = ProviderAPI # Checking instance above, not sure why mypy still mad. existing_option.type.base_type = base_type # type: ignore else: # Add the option automatically. # NOTE: Local import here only avoids circular import issues. from ape.cli.options import NetworkOption # NOTE: None base-type will default to `ProviderAPI`. option = NetworkOption(base_type=base_type, callback=self._network_callback) self.params.append(option) return super().parse_args(ctx, arguments) def invoke(self, ctx: "Context") -> Any: if self.callback is None: return elif network_ctx := parse_network(ctx): with network_ctx as provider: return self._invoke(ctx, provider=provider) else: return self._invoke(ctx) def _invoke(self, ctx: "Context", provider: Optional["ProviderAPI"] = None): # Will be put back with correct value if needed. # Else, causes issues. ctx.params.pop("network", None) valid_fields = ("ecosystem", "network", "provider") requested_fields = ( [] if self.callback is None else [x for x in inspect.signature(self.callback).parameters if x in valid_fields] ) if self._use_cls_types and requested_fields: options = ( {} if provider is None else { "ecosystem": provider.network.ecosystem, "network": provider.network, "provider": provider, } ) for name in requested_fields: if ( name not in ctx.params or ctx.params[name] is None or isinstance(ctx.params[name], str) ): ctx.params[name] = options.get(name) elif not self._use_cls_types and provider is not None: # Keep choice-str instead of parsing to objects. ctx.params["network"] = provider.network_choice return ctx.invoke(self.callback or (lambda: None), **ctx.params)
ConnectedProviderCommand
python
kamyu104__LeetCode-Solutions
Python/string-compression-iii.py
{ "start": 38, "end": 442 }
class ____(object): def compressedString(self, word): """ :type word: str :rtype: str """ result = [] cnt = 0 for i in xrange(len(word)): cnt += 1 if cnt == 9 or (i+1 == len(word) or word[i+1] != word[i]): result.append("%s%s" % (cnt, word[i])) cnt = 0 return "".join(result)
Solution
python
run-llama__llama_index
llama-index-core/llama_index/core/schema.py
{ "start": 30763, "end": 32455 }
class ____(BaseComponent): node: SerializeAsAny[BaseNode] score: Optional[float] = None def __str__(self) -> str: score_str = "None" if self.score is None else f"{self.score: 0.3f}" return f"{self.node}\nScore: {score_str}\n" def get_score(self, raise_error: bool = False) -> float: """Get score.""" if self.score is None: if raise_error: raise ValueError("Score not set.") else: return 0.0 else: return self.score @classmethod def class_name(cls) -> str: return "NodeWithScore" ##### pass through methods to BaseNode ##### @property def node_id(self) -> str: return self.node.node_id @property def id_(self) -> str: return self.node.id_ @property def text(self) -> str: if isinstance(self.node, TextNode): return self.node.text else: raise ValueError("Node must be a TextNode to get text.") @property def metadata(self) -> Dict[str, Any]: return self.node.metadata @property def embedding(self) -> Optional[List[float]]: return self.node.embedding def get_text(self) -> str: if isinstance(self.node, TextNode): return self.node.get_text() else: raise ValueError("Node must be a TextNode to get text.") def get_content(self, metadata_mode: MetadataMode = MetadataMode.NONE) -> str: return self.node.get_content(metadata_mode=metadata_mode) def get_embedding(self) -> List[float]: return self.node.get_embedding() # Document Classes for Readers
NodeWithScore
python
pytorch__pytorch
torch/utils/data/_utils/worker.py
{ "start": 4822, "end": 14260 }
class ____: seed: int | None = None # The function `_generate_state` is adapted from `numpy.random.SeedSequence` # from https://github.com/numpy/numpy/blob/main/numpy/random/bit_generator.pyx # It's MIT licensed, here is the copyright: # Copyright (c) 2015 Melissa E. O'Neill # Copyright (c) 2019 NumPy Developers # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # This function generates an array of int32 as the seed for # `numpy.random`, in order to prevent state collision due to same # seed and algorithm for `numpy.random` and `random` modules. # TODO: Implement `SeedSequence` like object for `torch.random` def _generate_state(base_seed, worker_id): INIT_A = 0x43B0D7E5 MULT_A = 0x931E8875 INIT_B = 0x8B51F9DD MULT_B = 0x58F38DED MIX_MULT_L = 0xCA01F9DD MIX_MULT_R = 0x4973F715 XSHIFT = 4 * 8 // 2 MASK32 = 0xFFFFFFFF entropy = [worker_id, base_seed & MASK32, base_seed >> 32, 0] pool = [0] * 4 hash_const_A = INIT_A def hash(value): nonlocal hash_const_A value = (value ^ hash_const_A) & MASK32 hash_const_A = (hash_const_A * MULT_A) & MASK32 value = (value * hash_const_A) & MASK32 value = (value ^ (value >> XSHIFT)) & MASK32 return value def mix(x, y): result_x = (MIX_MULT_L * x) & MASK32 result_y = (MIX_MULT_R * y) & MASK32 result = (result_x - result_y) & MASK32 result = (result ^ (result >> XSHIFT)) & MASK32 return result # Add in the entropy to the pool. for i in range(len(pool)): pool[i] = hash(entropy[i]) # Mix all bits together so late bits can affect earlier bits. for i_src in range(len(pool)): for i_dst in range(len(pool)): if i_src != i_dst: pool[i_dst] = mix(pool[i_dst], hash(pool[i_src])) hash_const_B = INIT_B state = [] for i_dst in range(4): data_val = pool[i_dst] data_val = (data_val ^ hash_const_B) & MASK32 hash_const_B = (hash_const_B * MULT_B) & MASK32 data_val = (data_val * hash_const_B) & MASK32 data_val = (data_val ^ (data_val >> XSHIFT)) & MASK32 state.append(data_val) return state def _worker_loop( dataset_kind, dataset, index_queue, data_queue, done_event, auto_collation, collate_fn, drop_last, base_seed, init_fn, worker_id, num_workers, persistent_workers, shared_seed, ) -> None: # See NOTE [ Data Loader Multiprocessing Shutdown Logic ] for details on the # logic of this function. try: # Initialize C side signal handlers for SIGBUS and SIGSEGV. Python signal # module's handlers are executed after Python returns from C low-level # handlers, likely when the same fatal signal had already happened # again. # https://docs.python.org/3/library/signal.html#execution-of-python-signal-handlers signal_handling._set_worker_signal_handlers() torch.multiprocessing._set_thread_name("pt_data_worker") torch.set_num_threads(1) seed = base_seed + worker_id random.seed(seed) torch.manual_seed(seed) if HAS_NUMPY: np_seed = _generate_state(base_seed, worker_id) import numpy as np np.random.seed(np_seed) from torch.utils.data import IterDataPipe from torch.utils.data.graph_settings import apply_random_seed shared_rng = torch.Generator() if isinstance(dataset, IterDataPipe): if shared_seed is None: raise AssertionError( "shared_seed must be provided for IterDataPipe workers" ) shared_rng.manual_seed(shared_seed) dataset = apply_random_seed(dataset, shared_rng) global _worker_info _worker_info = WorkerInfo( id=worker_id, num_workers=num_workers, seed=seed, dataset=dataset ) from torch.utils.data import _DatasetKind init_exception = None try: if init_fn is not None: init_fn(worker_id) fetcher = _DatasetKind.create_fetcher( dataset_kind, dataset, auto_collation, collate_fn, drop_last ) except Exception: init_exception = ExceptionWrapper( where=f"in DataLoader worker process {worker_id}" ) # When using Iterable mode, some worker can exit earlier than others due # to the IterableDataset behaving differently for different workers. # When such things happen, an `_IterableDatasetStopIteration` object is # sent over to the main process with the ID of this worker, so that the # main process won't send more tasks to this worker, and will send # `None` to this worker to properly exit it. # # Note that we cannot set `done_event` from a worker as it is shared # among all processes. Instead, we set the `iteration_end` flag to # signify that the iterator is exhausted. When either `done_event` or # `iteration_end` is set, we skip all processing step and just wait for # `None`. iteration_end = False watchdog = ManagerWatchdog() while watchdog.is_alive(): try: r = index_queue.get(timeout=MP_STATUS_CHECK_INTERVAL) except queue.Empty: continue if isinstance(r, _ResumeIteration): # Acknowledge the main process data_queue.put((r, None)) iteration_end = False if isinstance(dataset, IterDataPipe): if r.seed is None: raise AssertionError( "resume iteration seed is None for IterDataPipe" ) shared_rng.manual_seed(r.seed) dataset = apply_random_seed(dataset, shared_rng) # Recreate the fetcher for worker-reuse policy fetcher = _DatasetKind.create_fetcher( dataset_kind, dataset, auto_collation, collate_fn, drop_last ) continue elif r is None: # Received the final signal if not done_event.is_set() and not iteration_end: raise AssertionError( "Received final signal but neither done_event nor iteration_end is set" ) break elif done_event.is_set() or iteration_end: # `done_event` is set. But I haven't received the final signal # (None) yet. I will keep continuing until get it, and skip the # processing steps. continue idx, index = r data: _IterableDatasetStopIteration | ExceptionWrapper if init_exception is not None: data = init_exception init_exception = None else: try: data = fetcher.fetch(index) # type: ignore[possibly-undefined] except Exception as e: if ( isinstance(e, StopIteration) and dataset_kind == _DatasetKind.Iterable ): data = _IterableDatasetStopIteration(worker_id) # Set `iteration_end` # (1) to save future `next(...)` calls, and # (2) to avoid sending multiple `_IterableDatasetStopIteration`s. iteration_end = True else: # It is important that we don't store exc_info in a variable. # `ExceptionWrapper` does the correct thing. # See NOTE [ Python Traceback Reference Cycle Problem ] data = ExceptionWrapper( where=f"in DataLoader worker process {worker_id}" ) data_queue.put((idx, data)) del data, idx, index, r # save memory except KeyboardInterrupt: # Main process will raise KeyboardInterrupt anyways. pass if done_event.is_set(): data_queue.cancel_join_thread() data_queue.close()
_ResumeIteration
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 39737, "end": 40186 }
class ____(sgqlc.types.Enum): """Represents the different GitHub Enterprise Importer (GEI) migration sources. Enumeration Choices: * `AZURE_DEVOPS`: An Azure DevOps migration source. * `BITBUCKET_SERVER`: A Bitbucket Server migration source. * `GITHUB_ARCHIVE`: A GitHub Migration API source. """ __schema__ = github_schema __choices__ = ("AZURE_DEVOPS", "BITBUCKET_SERVER", "GITHUB_ARCHIVE")
MigrationSourceType
python
dagster-io__dagster
examples/project_analytics/dagster_pypi/resources.py
{ "start": 2151, "end": 2284 }
class ____(ConfigurableResource): def get_github_stars(self, _) -> pd.DataFrame: raise NotImplementedError()
GithubResource
python
automl__auto-sklearn
test/test_pipeline/components/classification/test_liblinear.py
{ "start": 165, "end": 837 }
class ____(BaseClassificationComponentTest): __test__ = True res = dict() res["default_iris"] = 1 res["default_iris_iterative"] = -1 res["default_iris_proba"] = 0.3350793047400861 res["default_iris_sparse"] = 0.56 res["default_digits"] = 0.914996964177292 res["default_digits_places"] = 2 res["default_digits_iterative"] = -1 res["default_digits_binary"] = 0.98907103825136611 res["default_digits_multilabel"] = 0.89889188078944637 res["default_digits_multilabel_places"] = 2 res["default_digits_multilabel_proba"] = 0.99999999999999989 sk_mod = sklearn.svm.LinearSVC module = LibLinear_SVC
LibLinearComponentTest
python
pypa__hatch
src/hatch/project/frontend/core.py
{ "start": 8509, "end": 8861 }
class ____: def __init__(self, project: Project, env: EnvironmentInterface) -> None: self._project = project self._env = env @staticmethod def inject_data(script: str, data: dict[str, Any]) -> str: # All scripts have a constant dictionary on top return script.replace("{}", repr(data), 1)
BuildFrontendScripts
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/pysqlite.py
{ "start": 17415, "end": 23750 }
class ____(SQLiteDialect): default_paramstyle = "qmark" supports_statement_cache = True returns_native_bytes = True colspecs = util.update_copy( SQLiteDialect.colspecs, { sqltypes.Date: _SQLite_pysqliteDate, sqltypes.TIMESTAMP: _SQLite_pysqliteTimeStamp, }, ) description_encoding = None driver = "pysqlite" @classmethod def import_dbapi(cls) -> DBAPIModule: from sqlite3 import dbapi2 as sqlite return cast("DBAPIModule", sqlite) @classmethod def _is_url_file_db(cls, url: URL) -> bool: if (url.database and url.database != ":memory:") and ( url.query.get("mode", None) != "memory" ): return True else: return False @classmethod def get_pool_class(cls, url: URL) -> type[pool.Pool]: if cls._is_url_file_db(url): return pool.QueuePool else: return pool.SingletonThreadPool def _get_server_version_info(self, connection: Any) -> VersionInfoType: return self.dbapi.sqlite_version_info # type: ignore _isolation_lookup = SQLiteDialect._isolation_lookup.union( { "AUTOCOMMIT": None, } ) def set_isolation_level( self, dbapi_connection: DBAPIConnection, level: IsolationLevel ) -> None: if level == "AUTOCOMMIT": dbapi_connection.isolation_level = None else: dbapi_connection.isolation_level = "" return super().set_isolation_level(dbapi_connection, level) def detect_autocommit_setting(self, dbapi_conn: DBAPIConnection) -> bool: return dbapi_conn.isolation_level is None def on_connect(self) -> Callable[[DBAPIConnection], None]: def regexp(a: str, b: Optional[str]) -> Optional[bool]: if b is None: return None return re.search(a, b) is not None if self._get_server_version_info(None) >= (3, 9): # sqlite must be greater than 3.8.3 for deterministic=True # https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.create_function # the check is more conservative since there were still issues # with following 3.8 sqlite versions create_func_kw = {"deterministic": True} else: create_func_kw = {} def set_regexp(dbapi_connection: DBAPIConnection) -> None: dbapi_connection.create_function( "regexp", 2, regexp, **create_func_kw ) def floor_func(dbapi_connection: DBAPIConnection) -> None: # NOTE: floor is optionally present in sqlite 3.35+ , however # as it is normally non-present we deliver floor() unconditionally # for now. # https://www.sqlite.org/lang_mathfunc.html dbapi_connection.create_function( "floor", 1, math.floor, **create_func_kw ) fns = [set_regexp, floor_func] def connect(conn: DBAPIConnection) -> None: for fn in fns: fn(conn) return connect def create_connect_args(self, url: URL) -> ConnectArgsType: if url.username or url.password or url.host or url.port: raise exc.ArgumentError( "Invalid SQLite URL: %s\n" "Valid SQLite URL forms are:\n" " sqlite:///:memory: (or, sqlite://)\n" " sqlite:///relative/path/to/file.db\n" " sqlite:////absolute/path/to/file.db" % (url,) ) # theoretically, this list can be augmented, at least as far as # parameter names accepted by sqlite3/pysqlite, using # inspect.getfullargspec(). for the moment this seems like overkill # as these parameters don't change very often, and as always, # parameters passed to connect_args will always go to the # sqlite3/pysqlite driver. pysqlite_args = [ ("uri", bool), ("timeout", float), ("isolation_level", str), ("detect_types", int), ("check_same_thread", bool), ("cached_statements", int), ] opts = url.query pysqlite_opts: dict[str, Any] = {} for key, type_ in pysqlite_args: util.coerce_kw_type(opts, key, type_, dest=pysqlite_opts) if pysqlite_opts.get("uri", False): uri_opts = dict(opts) # here, we are actually separating the parameters that go to # sqlite3/pysqlite vs. those that go the SQLite URI. What if # two names conflict? again, this seems to be not the case right # now, and in the case that new names are added to # either side which overlap, again the sqlite3/pysqlite parameters # can be passed through connect_args instead of in the URL. # If SQLite native URIs add a parameter like "timeout" that # we already have listed here for the python driver, then we need # to adjust for that here. for key, type_ in pysqlite_args: uri_opts.pop(key, None) filename: str = url.database # type: ignore[assignment] if uri_opts: # sorting of keys is for unit test support filename += "?" + ( "&".join( "%s=%s" % (key, uri_opts[key]) for key in sorted(uri_opts) ) ) else: filename = url.database or ":memory:" if filename != ":memory:": filename = os.path.abspath(filename) pysqlite_opts.setdefault( "check_same_thread", not self._is_url_file_db(url) ) return ([filename], pysqlite_opts) def is_disconnect( self, e: DBAPIModule.Error, connection: Optional[Union[PoolProxiedConnection, DBAPIConnection]], cursor: Optional[DBAPICursor], ) -> bool: self.dbapi = cast("DBAPIModule", self.dbapi) return isinstance( e, self.dbapi.ProgrammingError ) and "Cannot operate on a closed database." in str(e) dialect = SQLiteDialect_pysqlite
SQLiteDialect_pysqlite
python
doocs__leetcode
solution/0600-0699/0645.Set Mismatch/Solution.py
{ "start": 0, "end": 210 }
class ____: def findErrorNums(self, nums: List[int]) -> List[int]: n = len(nums) s1 = (1 + n) * n // 2 s2 = sum(set(nums)) s = sum(nums) return [s - s2, s1 - s2]
Solution
python
getsentry__sentry-python
sentry_sdk/tracing.py
{ "start": 4287, "end": 6389 }
class ____(str, Enum): COMPONENT = "component" CUSTOM = "custom" ROUTE = "route" TASK = "task" URL = "url" VIEW = "view" def __str__(self): # type: () -> str return self.value # These are typically high cardinality and the server hates them LOW_QUALITY_TRANSACTION_SOURCES = [ TransactionSource.URL, ] SOURCE_FOR_STYLE = { "endpoint": TransactionSource.COMPONENT, "function_name": TransactionSource.COMPONENT, "handler_name": TransactionSource.COMPONENT, "method_and_path_pattern": TransactionSource.ROUTE, "path": TransactionSource.URL, "route_name": TransactionSource.COMPONENT, "route_pattern": TransactionSource.ROUTE, "uri_template": TransactionSource.ROUTE, "url": TransactionSource.ROUTE, } def get_span_status_from_http_code(http_status_code): # type: (int) -> str """ Returns the Sentry status corresponding to the given HTTP status code. See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context """ if http_status_code < 400: return SPANSTATUS.OK elif 400 <= http_status_code < 500: if http_status_code == 403: return SPANSTATUS.PERMISSION_DENIED elif http_status_code == 404: return SPANSTATUS.NOT_FOUND elif http_status_code == 429: return SPANSTATUS.RESOURCE_EXHAUSTED elif http_status_code == 413: return SPANSTATUS.FAILED_PRECONDITION elif http_status_code == 401: return SPANSTATUS.UNAUTHENTICATED elif http_status_code == 409: return SPANSTATUS.ALREADY_EXISTS else: return SPANSTATUS.INVALID_ARGUMENT elif 500 <= http_status_code < 600: if http_status_code == 504: return SPANSTATUS.DEADLINE_EXCEEDED elif http_status_code == 501: return SPANSTATUS.UNIMPLEMENTED elif http_status_code == 503: return SPANSTATUS.UNAVAILABLE else: return SPANSTATUS.INTERNAL_ERROR return SPANSTATUS.UNKNOWN_ERROR
TransactionSource
python
walkccc__LeetCode
solutions/3134. Find the Median of the Uniqueness Array/3134.py
{ "start": 0, "end": 802 }
class ____: def medianOfUniquenessArray(self, nums: list[int]): n = len(nums) subarrayCount = n * (n + 1) // 2 medianCount = (subarrayCount + 1) // 2 # Similar to 992. Subarrays with K Different Integers def subarraysWithAtMostKDistinct(k: int) -> int: res = 0 count = collections.Counter() l = 0 for r, num in enumerate(nums): count[num] += 1 if count[num] == 1: k -= 1 while k < 0: count[nums[l]] -= 1 if count[nums[l]] == 0: k += 1 l += 1 res += r - l + 1 # nums[l..r], nums[l + 1..r], ..., nums[r] return res l = 1 r = n return bisect.bisect_left(range(l, r), medianCount, key=subarraysWithAtMostKDistinct) + l
Solution
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-scrapegraph/tests/test_tools_scrapegraph.py
{ "start": 11707, "end": 14518 }
class ____: """Test Agentic Scraper functionality.""" def test_agentic_scraper_with_schema(self, tool_spec_from_env): """Test agentic scraper with schema.""" tool_spec, mock_client = tool_spec_from_env prompt = "Navigate and extract product info" url = "https://example.com" schema = TestProductSchema expected_response = {"name": "Test Product", "price": "$99"} mock_client.agentic_scraper.return_value = expected_response response = tool_spec.scrapegraph_agentic_scraper( prompt=prompt, url=url, schema=schema ) mock_client.agentic_scraper.assert_called_once_with( website_url=url, user_prompt=prompt, output_schema=schema ) assert response == expected_response def test_agentic_scraper_without_schema(self, tool_spec_with_api_key): """Test agentic scraper without schema.""" tool_spec, mock_client = tool_spec_with_api_key prompt = "Navigate and find contact info" url = "https://example.com" expected_response = {"contact": "info@example.com", "phone": "123-456-7890"} mock_client.agentic_scraper.return_value = expected_response response = tool_spec.scrapegraph_agentic_scraper(prompt=prompt, url=url) mock_client.agentic_scraper.assert_called_once_with( website_url=url, user_prompt=prompt, output_schema=None ) assert response == expected_response def test_agentic_scraper_with_kwargs(self, tool_spec_from_env): """Test agentic scraper with additional parameters.""" tool_spec, mock_client = tool_spec_from_env prompt = "Complex navigation task" url = "https://example.com" expected_response = {"navigation_result": "success"} mock_client.agentic_scraper.return_value = expected_response response = tool_spec.scrapegraph_agentic_scraper( prompt=prompt, url=url, max_depth=3, follow_links=True ) mock_client.agentic_scraper.assert_called_once_with( website_url=url, user_prompt=prompt, output_schema=None, max_depth=3, follow_links=True, ) assert response == expected_response def test_agentic_scraper_exception_handling(self, tool_spec_with_api_key): """Test agentic scraper exception handling.""" tool_spec, mock_client = tool_spec_with_api_key mock_client.agentic_scraper.side_effect = Exception("Navigation Error") response = tool_spec.scrapegraph_agentic_scraper( prompt="test", url="https://example.com" ) assert "error" in response assert "Agentic scraper failed: Navigation Error" in response["error"]
TestAgenticScraper
python
scikit-learn__scikit-learn
sklearn/feature_extraction/image.py
{ "start": 17469, "end": 23608 }
class ____(TransformerMixin, BaseEstimator): """Extracts patches from a collection of images. Read more in the :ref:`User Guide <image_feature_extraction>`. .. versionadded:: 0.9 Parameters ---------- patch_size : tuple of int (patch_height, patch_width), default=None The dimensions of one patch. If set to None, the patch size will be automatically set to `(img_height // 10, img_width // 10)`, where `img_height` and `img_width` are the dimensions of the input images. max_patches : int or float, default=None The maximum number of patches per image to extract. If `max_patches` is a float in (0, 1), it is taken to mean a proportion of the total number of patches. If set to None, extract all possible patches. random_state : int, RandomState instance, default=None Determines the random number generator used for random sampling when `max_patches is not None`. Use an int to make the randomness deterministic. See :term:`Glossary <random_state>`. See Also -------- reconstruct_from_patches_2d : Reconstruct image from all of its patches. Notes ----- This estimator is stateless and does not need to be fitted. However, we recommend to call :meth:`fit_transform` instead of :meth:`transform`, as parameter validation is only performed in :meth:`fit`. Examples -------- >>> from sklearn.datasets import load_sample_images >>> from sklearn.feature_extraction import image >>> # Use the array data from the second image in this dataset: >>> X = load_sample_images().images[1] >>> X = X[None, ...] >>> print(f"Image shape: {X.shape}") Image shape: (1, 427, 640, 3) >>> pe = image.PatchExtractor(patch_size=(10, 10)) >>> pe_trans = pe.transform(X) >>> print(f"Patches shape: {pe_trans.shape}") Patches shape: (263758, 10, 10, 3) >>> X_reconstructed = image.reconstruct_from_patches_2d(pe_trans, X.shape[1:]) >>> print(f"Reconstructed shape: {X_reconstructed.shape}") Reconstructed shape: (427, 640, 3) """ _parameter_constraints: dict = { "patch_size": [tuple, None], "max_patches": [ None, Interval(RealNotInt, 0, 1, closed="neither"), Interval(Integral, 1, None, closed="left"), ], "random_state": ["random_state"], } def __init__(self, *, patch_size=None, max_patches=None, random_state=None): self.patch_size = patch_size self.max_patches = max_patches self.random_state = random_state @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y=None): """Only validate the parameters of the estimator. This method allows to: (i) validate the parameters of the estimator and (ii) be consistent with the scikit-learn transformer API. Parameters ---------- X : ndarray of shape (n_samples, image_height, image_width) or \ (n_samples, image_height, image_width, n_channels) Array of images from which to extract patches. For color images, the last dimension specifies the channel: a RGB image would have `n_channels=3`. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Returns the instance itself. """ return self def transform(self, X): """Transform the image samples in `X` into a matrix of patch data. Parameters ---------- X : ndarray of shape (n_samples, image_height, image_width) or \ (n_samples, image_height, image_width, n_channels) Array of images from which to extract patches. For color images, the last dimension specifies the channel: a RGB image would have `n_channels=3`. Returns ------- patches : array of shape (n_patches, patch_height, patch_width) or \ (n_patches, patch_height, patch_width, n_channels) The collection of patches extracted from the images, where `n_patches` is either `n_samples * max_patches` or the total number of patches that can be extracted. """ X = validate_data( self, X=X, ensure_2d=False, allow_nd=True, ensure_min_samples=1, ensure_min_features=1, reset=False, ) random_state = check_random_state(self.random_state) n_imgs, img_height, img_width = X.shape[:3] if self.patch_size is None: patch_size = img_height // 10, img_width // 10 else: if len(self.patch_size) != 2: raise ValueError( "patch_size must be a tuple of two integers. Got" f" {self.patch_size} instead." ) patch_size = self.patch_size n_imgs, img_height, img_width = X.shape[:3] X = np.reshape(X, (n_imgs, img_height, img_width, -1)) n_channels = X.shape[-1] # compute the dimensions of the patches array patch_height, patch_width = patch_size n_patches = _compute_n_patches( img_height, img_width, patch_height, patch_width, self.max_patches ) patches_shape = (n_imgs * n_patches,) + patch_size if n_channels > 1: patches_shape += (n_channels,) # extract the patches patches = np.empty(patches_shape) for ii, image in enumerate(X): patches[ii * n_patches : (ii + 1) * n_patches] = extract_patches_2d( image, patch_size, max_patches=self.max_patches, random_state=random_state, ) return patches def __sklearn_tags__(self): tags = super().__sklearn_tags__() tags.input_tags.two_d_array = False tags.input_tags.three_d_array = True tags.requires_fit = False return tags
PatchExtractor
python
ray-project__ray
python/ray/tests/chaos/streaming_llm.py
{ "start": 427, "end": 1039 }
class ____: def __init__(self, dup_times: int): self.dup_times = dup_times async def __call__(self, prompt: str): for word in prompt.split(): rev = word[::-1] for _ in range(self.dup_times): await asyncio.sleep(0.001) # Ideally we want to do " ".join(words), but for the sake of # simplicity we also have an extra trailing space. yield rev + " " @serve.deployment( num_replicas=6, ray_actor_options={"num_cpus": 0.01, "memory": 10 * 1024 * 1024} ) @serve.ingress(fastapi_app)
ReverseAndDupEachWord
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/json.py
{ "start": 3498, "end": 4182 }
class ____: def _format_value(self, value): raise NotImplementedError() def bind_processor(self, dialect): super_proc = self.string_bind_processor(dialect) def process(value): value = self._format_value(value) if super_proc: value = super_proc(value) return value return process def literal_processor(self, dialect): super_proc = self.string_literal_processor(dialect) def process(value): value = self._format_value(value) if super_proc: value = super_proc(value) return value return process
_FormatTypeMixin
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-oci-data-science/tests/test_oci_data_science_client.py
{ "start": 1845, "end": 3723 }
class ____: """Unit tests for _should_retry_exception function.""" def test_http_status_error_in_force_list(self): """Ensures it returns True for HTTPStatusError with status in STATUS_FORCE_LIST.""" response_mock = Mock() response_mock.status_code = 500 original_exception = httpx.HTTPStatusError( "Error", request=None, response=response_mock ) exception = ExtendedRequestException( "Message", original_exception, "Response text" ) result = _should_retry_exception(exception) assert result is True def test_http_status_error_not_in_force_list(self): """Ensures it returns False for HTTPStatusError with status not in STATUS_FORCE_LIST.""" response_mock = Mock() response_mock.status_code = 404 original_exception = httpx.HTTPStatusError( "Error", request=None, response=response_mock ) exception = ExtendedRequestException( "Message", original_exception, "Response text" ) result = _should_retry_exception(exception) assert result is False def test_http_request_error(self): """Ensures it returns True for RequestError.""" original_exception = httpx.RequestError("Error") exception = ExtendedRequestException( "Message", original_exception, "Response text" ) result = _should_retry_exception(exception) assert result is True def test_other_exception(self): """Ensures it returns False for other exceptions.""" original_exception = Exception("Some other error") exception = ExtendedRequestException( "Message", original_exception, "Response text" ) result = _should_retry_exception(exception) assert result is False
TestShouldRetryException
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_filter_details.py
{ "start": 49, "end": 2913 }
class ____(APITestCase): endpoint = "sentry-api-0-project-filters-details" method = "put" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def test_put(self) -> None: org = self.create_organization(name="baz", slug="1", owner=self.user) team = self.create_team(organization=org, name="foo", slug="foo") project = self.create_project(name="Bar", slug="bar", teams=[team]) project.update_option("filters:browser-extensions", "0") self.get_success_response( org.slug, project.slug, "browser-extensions", active=True, status_code=204 ) assert project.get_option("filters:browser-extensions") == "1" def test_put_health_check_filter(self) -> None: """ Tests that it accepts to set the health-check filter when the feature flag is enabled """ org = self.create_organization(name="baz", slug="1", owner=self.user) team = self.create_team(organization=org, name="foo", slug="foo") project = self.create_project(name="Bar", slug="bar", teams=[team]) project.update_option("filters:filtered-transaction", "0") self.get_success_response( org.slug, project.slug, "filtered-transaction", active=True, status_code=204 ) # option was changed by the request assert project.get_option("filters:filtered-transaction") == "1" project.update_option("filters:filtered-transaction", "1") self.get_success_response( org.slug, project.slug, "filtered-transaction", active=False, status_code=204 ) # option was changed by the request assert project.get_option("filters:filtered-transaction") == "0" def test_put_legacy_browsers(self) -> None: org = self.create_organization(name="baz", slug="1", owner=self.user) team = self.create_team(organization=org, name="foo", slug="foo") project = self.create_project(name="Bar", slug="bar", teams=[team]) project.update_option( "filters:legacy-browsers", [ "ie10", "ie9", "android_pre_4", "ie_pre_9", "opera_pre_15", "safari_pre_6", "ie11", "opera_mini_pre_8", ], ) new_subfilters = [ "edge_pre_79", "ie10", "ie11", "opera_mini_pre_8", "opera_pre_15", "safari_pre_6", ] self.get_success_response( org.slug, project.slug, "legacy-browsers", subfilters=new_subfilters, status_code=204, ) assert project.get_option("filters:legacy-browsers") == new_subfilters
ProjectFilterDetailsTest
python
miyuchina__mistletoe
test/test_contrib/test_jira_renderer.py
{ "start": 1357, "end": 7009 }
class ____(BaseRendererTest): def setUp(self): super().setUp() self.renderer = JiraRenderer() self.renderer.__enter__() self.addCleanup(self.renderer.__exit__, None, None, None) self.sampleOutputExtension = 'jira' def genRandomString(self, n, hasWhitespace=False): source = string.ascii_letters + string.digits if hasWhitespace: source = source + ' \t' result = ''.join(random.SystemRandom().choice(source) for _ in range(n)) return result def textFormatTest(self, inputTemplate, outputTemplate): input = self.genRandomString(80, False) token = next(iter(tokenize_inner(inputTemplate.format(input)))) output = self.renderer.render(token) expected = outputTemplate.format(input) self.assertEqual(output, expected) def test_escape_simple(self): self.textFormatTest('---fancy text---', '\\-\\-\\-fancy text\\-\\-\\-') def test_escape_single_chars(self): self.textFormatTest('**fancy \\*@\\* text**', '*fancy \\*@\\* text*') def test_escape_none_when_whitespaces(self): self.textFormatTest('obj = {{ a: (b * c) + d }}', 'obj = {{ a: (b * c) + d }}') def test_escape_in_inline_code(self): # Note: Jira puts inline code into "{{...}}" as seen in this test. self.textFormatTest('**code: `a = b + c;// [1]`**', '*code: {{{{a = b + c;// \\[1\\]}}}}*') def test_escape_link(self): # Note: There seems to be no way of how to escape plain text URL in Jira. self.textFormatTest('http://www.example.com', 'http://www.example.com') def test_render_strong(self): self.textFormatTest('**a{}**', '*a{}*') def test_render_emphasis(self): self.textFormatTest('*a{}*', '_a{}_') def test_render_inline_code(self): self.textFormatTest('`a{}b`', '{{{{a{}b}}}}') def test_render_strikethrough(self): self.textFormatTest('~~{}~~', '-{}-') def test_render_image(self): token = next(iter(tokenize_inner('![image](foo.jpg)'))) output = self.renderer.render(token) expected = '!foo.jpg!' self.assertEqual(output, expected) def test_render_footnote_image(self): # token = next(tokenize_inner('![image]\n\n[image]: foo.jpg')) # output = self.renderer.render(token) # expected = '!foo.jpg!' # self.assertEqual(output, expected) pass def test_render_link(self): url = 'http://{0}.{1}.{2}'.format(self.genRandomString(5), self.genRandomString(5), self.genRandomString(3)) body = self.genRandomString(80, True) token = next(iter(tokenize_inner('[{body}]({url})'.format(url=url, body=body)))) output = self.renderer.render(token) expected = '[{body}|{url}]'.format(url=url, body=body) self.assertEqual(output, expected) def test_render_link_with_title(self): url = 'http://{0}.{1}.{2}'.format(self.genRandomString(5), self.genRandomString(5), self.genRandomString(3)) body = self.genRandomString(80, True) title = self.genRandomString(20, True) token = next(iter(tokenize_inner('[{body}]({url} "{title}")'.format(url=url, body=body, title=title)))) output = self.renderer.render(token) expected = '[{body}|{url}|{title}]'.format(url=url, body=body, title=title) self.assertEqual(output, expected) def test_render_footnote_link(self): pass def test_render_auto_link(self): url = 'http://{0}.{1}.{2}'.format(self.genRandomString(5), self.genRandomString(5), self.genRandomString(3)) token = next(iter(tokenize_inner('<{url}>'.format(url=url)))) output = self.renderer.render(token) expected = '[{url}]'.format(url=url) self.assertEqual(output, expected) def test_render_escape_sequence(self): pass def test_render_html_span(self): pass def test_render_heading(self): pass def test_render_quote(self): pass def test_render_paragraph(self): pass def test_render_block_code(self): markdown = """\ ```java public static void main(String[] args) { // a = 1 * 2; } ``` """ expected = """\ {code:java} public static void main(String[] args) { // a = 1 * 2; } {code} """ self.markdownResultTest(markdown, expected) def test_render_list(self): pass def test_render_list_item(self): pass def test_render_inner(self): pass def test_render_table(self): pass def test_render_table_row(self): pass def test_render_table_cell(self): pass def test_render_thematic_break(self): pass def test_render_html_block(self): pass def test_render_document(self): pass def test_table_header(self): markdown = """\ | header row | |--------------| | first cell | """ expected = """\ ||header row|| |first cell| """ self.markdownResultTest(markdown, expected) def test_table_empty_cell(self): """ Empty cells need to have a space in them, see <https://jira.atlassian.com/browse/JRASERVER-70048>. """ markdown = """\ | A | B | C | |-----------| | 1 | | 3 | """ expected = """\ ||A||B||C|| |1| |3| """ self.markdownResultTest(markdown, expected) @filesBasedTest def test_render__basic_blocks(self): pass @filesBasedTest def test_render__lists(self): pass @filesBasedTest def test_render__quotes(self): pass
TestJiraRenderer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-analytics-v4/source_google_analytics_v4/source.py
{ "start": 22921, "end": 26893 }
class ____(AbstractSource): """Google Analytics lets you analyze data about customer engagement with your website or application.""" @staticmethod def get_authenticator(config: Mapping) -> Oauth2Authenticator: # backwards compatibility, credentials_json used to be in the top level of the connector if config.get("credentials_json"): return GoogleAnalyticsServiceOauth2Authenticator(config) auth_params = config["credentials"] if auth_params["auth_type"] == "Service" or auth_params.get("credentials_json"): return GoogleAnalyticsServiceOauth2Authenticator(auth_params) else: return Oauth2Authenticator( token_refresh_endpoint="https://oauth2.googleapis.com/token", client_secret=auth_params["client_secret"], client_id=auth_params["client_id"], refresh_token=auth_params["refresh_token"], scopes=["https://www.googleapis.com/auth/analytics.readonly"], ) def check_connection(self, logger: logging.Logger, config: MutableMapping) -> Tuple[bool, Any]: # declare additional variables authenticator = self.get_authenticator(config) config["authenticator"] = authenticator config["metrics"] = ["ga:hits"] config["dimensions"] = ["ga:date"] # load and verify the custom_reports try: # test the eligibility of custom_reports input custom_reports = config.get("custom_reports") if custom_reports: CustomReportsValidator(json.loads(custom_reports)).validate() # Read records to check the reading permissions read_check = list(TestStreamConnection(config).read_records(sync_mode=None)) if read_check: return True, None return ( False, f"Please check the permissions for the requested view_id: {config['view_id']}. Cannot retrieve data from that view ID.", ) except ValueError as e: return False, f"Invalid custom reports json structure. {e}" except requests.exceptions.RequestException as e: error_msg = e.response.json().get("error") if e.response.status_code == 403: return False, f"Please check the permissions for the requested view_id: {config['view_id']}. {error_msg}" else: return False, f"{error_msg}" def streams(self, config: MutableMapping[str, Any]) -> List[Stream]: streams: List[GoogleAnalyticsV4Stream] = [] authenticator = self.get_authenticator(config) config["authenticator"] = authenticator reports = json.loads(pkgutil.get_data("source_google_analytics_v4", "defaults/default_reports.json")) custom_reports = config.get("custom_reports") if custom_reports: custom_reports = json.loads(custom_reports) custom_reports = [custom_reports] if not isinstance(custom_reports, list) else custom_reports reports += custom_reports config["ga_streams"] = reports for stream in config["ga_streams"]: config["metrics"] = stream["metrics"] config["dimensions"] = stream["dimensions"] config["segments"] = stream.get("segments", list()) config["filter"] = stream.get("filter", "") # construct GAReadStreams sub-class for each stream stream_name = stream["name"] stream_bases = (GoogleAnalyticsV4Stream,) if "ga:date" in stream["dimensions"]: stream_bases = (GoogleAnalyticsV4IncrementalObjectsBase,) stream_class = type(stream_name, stream_bases, {}) # instantiate a stream with config stream_instance = stream_class(config) streams.append(stream_instance) return streams
SourceGoogleAnalyticsV4
python
apache__airflow
providers/telegram/tests/unit/telegram/operators/test_telegram.py
{ "start": 1039, "end": 6923 }
class ____: @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="telegram_default", conn_type="http", password=TELEGRAM_TOKEN, ) ) create_connection_without_db( Connection( conn_id="telegram_default-with-chat-id", conn_type="http", password=TELEGRAM_TOKEN, host="-420913222", ) ) @mock.patch("airflow.providers.telegram.operators.telegram.TelegramHook") def test_should_send_message_when_all_parameters_are_provided(self, mock_telegram_hook): mock_telegram_hook.return_value = mock.Mock() mock_telegram_hook.return_value.send_message.return_value = True hook = TelegramOperator( telegram_conn_id="telegram_default", chat_id="-420913222", task_id="telegram", text="some non empty text", ) hook.execute(None) mock_telegram_hook.assert_called_once_with( telegram_conn_id="telegram_default", chat_id="-420913222", token=None, ) mock_telegram_hook.return_value.send_message.assert_called_once_with( {"text": "some non empty text"}, ) def test_should_throw_exception_if_connection_id_is_none(self): with pytest.raises(airflow.exceptions.AirflowException) as ctx: TelegramOperator(task_id="telegram", telegram_conn_id=None) assert str(ctx.value) == "No valid Telegram connection id supplied." @mock.patch("airflow.providers.telegram.operators.telegram.TelegramHook") def test_should_throw_exception_if_telegram_hook_throws_any_exception(self, mock_telegram_hook): def side_effect(*args, **kwargs): raise telegram.error.TelegramError("cosmic rays caused bit flips") mock_telegram_hook.return_value = mock.Mock() mock_telegram_hook.return_value.send_message.side_effect = side_effect op = TelegramOperator( telegram_conn_id="telegram_default", task_id="telegram", text="some non empty text", ) with pytest.raises(telegram.error.TelegramError, match="cosmic rays caused bit flips"): op.execute({}) @mock.patch("airflow.providers.telegram.operators.telegram.TelegramHook") def test_should_forward_all_args_to_telegram(self, mock_telegram_hook): mock_telegram_hook.return_value = mock.Mock() mock_telegram_hook.return_value.send_message.return_value = True hook = TelegramOperator( telegram_conn_id="telegram_default", chat_id="-420913222", task_id="telegram", text="some non empty text", telegram_kwargs={"custom_arg": "value"}, ) hook.execute(None) mock_telegram_hook.assert_called_once_with( telegram_conn_id="telegram_default", chat_id="-420913222", token=None, ) mock_telegram_hook.return_value.send_message.assert_called_once_with( {"custom_arg": "value", "text": "some non empty text"}, ) @mock.patch("airflow.providers.telegram.operators.telegram.TelegramHook") def test_should_give_precedence_to_text_passed_in_constructor(self, mock_telegram_hook): mock_telegram_hook.return_value = mock.Mock() mock_telegram_hook.return_value.send_message.return_value = True hook = TelegramOperator( telegram_conn_id="telegram_default", chat_id="-420913222", task_id="telegram", text="some non empty text - higher precedence", telegram_kwargs={"custom_arg": "value", "text": "some text, that will be ignored"}, ) hook.execute(None) mock_telegram_hook.assert_called_once_with( telegram_conn_id="telegram_default", chat_id="-420913222", token=None, ) mock_telegram_hook.return_value.send_message.assert_called_once_with( {"custom_arg": "value", "text": "some non empty text - higher precedence"}, ) def test_should_return_template_fields(self): hook = TelegramOperator( telegram_conn_id="telegram_default", chat_id="-420913222", task_id="telegram", text="some non empty text - higher precedence", telegram_kwargs={"custom_arg": "value", "text": "some text, that will be ignored"}, ) assert hook.template_fields == ("text", "chat_id") @mock.patch("airflow.providers.telegram.operators.telegram.TelegramHook") def test_should_return_templatized_text_field(self, mock_hook): operator = TelegramOperator( telegram_conn_id="telegram_default", chat_id="-420913222", task_id="telegram", text="logical date is {{ ds }}", telegram_kwargs={"custom_arg": "value", "text": "should be ignored"}, ) operator.render_template_fields({"ds": "2021-02-04"}) operator.execute(None) assert operator.text == "logical date is 2021-02-04" assert "text" in operator.telegram_kwargs assert operator.telegram_kwargs["text"] == "logical date is 2021-02-04" def test_should_return_templatized_chat_id_field(self): operator = TelegramOperator( telegram_conn_id="telegram_default", chat_id="{{ chat_id }}", task_id="telegram", text="text", telegram_kwargs={"custom_arg": "value", "text": "should be ignored"}, ) operator.render_template_fields({"chat_id": "1234567"}) assert operator.chat_id == "1234567"
TestTelegramOperator
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_dynamic_partition_op_test.py
{ "start": 1348, "end": 10434 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ dict( # empty inputs data=[], partitions=[], num_partitions=0, expected=[], expected_ragged_rank=1), dict( # empty data, num_partitions>0 data=[], partitions=[], num_partitions=3, expected=[[], [], []]), dict( # 1D data, 1D partitions (docstring example) data=['a', 'b', 'c', 'd', 'e'], partitions=[3, 0, 2, 2, 3], num_partitions=5, expected=[['b'], [], ['c', 'd'], ['a', 'e'], []]), dict( # 2D data, 1D partitions data=[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']], data_ragged_rank=0, partitions=[2, 1, 2, 3], num_partitions=4, expected=[[], [['c', 'd']], [['a', 'b'], ['e', 'f']], [['g', 'h']]], expected_ragged_rank=1), dict( # 2D ragged data, 1D partitions data=[['a'], ['b', 'c', 'd'], [], ['e', 'f']], data_ragged_rank=1, partitions=[2, 1, 2, 3], num_partitions=4, expected=[[], [['b', 'c', 'd']], [['a'], []], [['e', 'f']]], expected_ragged_rank=2), dict( # 2D data, 2D partitions data=[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']], data_ragged_rank=0, partitions=[[3, 0], [2, 2], [4, 3], [2, 0]], num_partitions=5, expected=[['b', 'h'], [], ['c', 'd', 'g'], ['a', 'f'], ['e']]), dict( # 2D ragged data, 2D ragged partitions data=[['a', 'b'], ['c', 'd'], ['e', 'f'], ['g', 'h']], data_ragged_rank=0, partitions=[[3, 0], [2, 2], [4, 3], [2, 0]], num_partitions=5, expected=[['b', 'h'], [], ['c', 'd', 'g'], ['a', 'f'], ['e']]), dict( # 3D data, 1d partitions data=[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]], data_ragged_rank=0, partitions=[1, 0], num_partitions=2, expected=[[[['e', 'f'], ['g', 'h']]], [[['a', 'b'], ['c', 'd']]]], expected_ragged_rank=1), dict( # 3D data (ragged_rank=1), 1d partitions data=[[['a', 'b'], ['c', 'd']], [['e', 'f']]], data_ragged_rank=1, partitions=[2, 0], num_partitions=3, expected=[[[['e', 'f']]], [], [[['a', 'b'], ['c', 'd']]]], expected_ragged_rank=2), dict( # 3D data (ragged_rank=2), 1d partitions data=[[['a', 'b'], ['c', 'd']], [['e', 'f', 'g', 'h']]], data_ragged_rank=2, partitions=[2, 0], num_partitions=3, expected=[[[['e', 'f', 'g', 'h']]], [], [[['a', 'b'], ['c', 'd']]]], expected_ragged_rank=3), dict( # 3D data, 2d partitions data=[[['a', 'b'], ['c', 'd']], [['e', 'f'], ['g', 'h']]], data_ragged_rank=0, partitions=[[1, 0], [0, 3]], segment_ids_ragged_rank=0, num_partitions=4, expected=[[['c', 'd'], ['e', 'f']], [['a', 'b']], [], [['g', 'h']]], expected_ragged_rank=1), dict( # 3D data (ragged_rank=1), 2d partitions data=[[['a', 'b'], ['c', 'd']], [['e', 'f']]], data_ragged_rank=1, partitions=[[1, 0], [0]], segment_ids_ragged_rank=1, num_partitions=2, expected=[[['c', 'd'], ['e', 'f']], [['a', 'b']]], expected_ragged_rank=1), dict( # 3D data (ragged_rank=2), 2d partitions data=[[['a', 'b'], ['c', 'd']], [['e', 'f', 'g', 'h']]], data_ragged_rank=2, partitions=[[1, 0], [0]], segment_ids_ragged_rank=1, num_partitions=3, expected=[[['c', 'd'], ['e', 'f', 'g', 'h']], [['a', 'b']], []], expected_ragged_rank=2), dict( # 3D data (ragged_rank=2), 3d partitions (ragged_rank=2) data=[[['a', 'b'], ['c', 'd']], [['e', 'f', 'g', 'h']]], data_ragged_rank=2, partitions=[[[3, 0], [1, 2]], [[1, 1, 0, 1]]], segment_ids_ragged_rank=2, num_partitions=4, expected=[['b', 'g'], ['c', 'e', 'f', 'h'], ['d'], ['a']]), dict( # 0D data, 0D partitions data='a', partitions=3, num_partitions=5, expected=[[], [], [], ['a'], []]), dict( # 1D data, 0D partitions data=['a', 'b', 'c'], partitions=3, num_partitions=5, expected=[[], [], [], [['a', 'b', 'c']], []], expected_ragged_rank=1), dict( # 2D data, 0D partitions data=[['a', 'b'], ['c', 'd']], data_ragged_rank=0, partitions=3, num_partitions=5, expected=[[], [], [], [[['a', 'b'], ['c', 'd']]], []], expected_ragged_rank=1), dict( # 2D data (ragged_rank=1), 0D partitions data=[['a', 'b'], ['c']], data_ragged_rank=1, partitions=3, num_partitions=5, expected=[[], [], [], [[['a', 'b'], ['c']]], []], expected_ragged_rank=3), ]) def testRaggedSegmentStack(self, data, partitions, num_partitions, expected, data_ragged_rank=None, segment_ids_ragged_rank=None, expected_ragged_rank=None): for seg_dtype in [dtypes.int32, dtypes.int64]: data_tensor = ragged_factory_ops.constant( data, row_splits_dtype=seg_dtype, ragged_rank=data_ragged_rank) segment_ids_tensor = ragged_factory_ops.constant( partitions, dtype=seg_dtype, row_splits_dtype=seg_dtype, ragged_rank=segment_ids_ragged_rank) expected_tensor = ragged_factory_ops.constant( expected, row_splits_dtype=seg_dtype, ragged_rank=expected_ragged_rank) result = ragged_array_ops.stack_dynamic_partitions( data_tensor, segment_ids_tensor, num_partitions) self.assertAllEqual(result, expected_tensor) # Check that it's equivalent to tf.stack(dynamic_partition(...)), # where applicable. if (data_ragged_rank == 0 and segment_ids_ragged_rank == 0 and seg_dtype == dtypes.int32): equiv = ragged_concat_ops.stack( data_flow_ops.dynamic_partition(data_tensor, segment_ids_tensor, num_partitions)) self.assertAllEqual(result, self.evaluate(equiv).to_list()) @parameterized.parameters([ dict( data=['a', 'b', 'c'], partitions=[2, -1, 0], num_partitions=10, error='must be non-negative'), dict( data=['a', 'b', 'c'], partitions=[2, 10, 0], num_partitions=1, error='partitions must be less than num_partitions'), dict( data=['a', 'b', 'c'], partitions=[2, 10, 0], num_partitions=10, error='partitions must be less than num_partitions'), dict( data=[['a', 'b'], ['c']], partitions=[[2], [3, 0]], num_partitions=10, error='data and partitions have incompatible ragged shapes'), ]) def testRuntimeError(self, data, partitions, num_partitions, error): data = ragged_factory_ops.constant(data) partitions = ragged_factory_ops.constant(partitions, dtype=dtypes.int64) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), error): self.evaluate( ragged_array_ops.stack_dynamic_partitions(data, partitions, num_partitions)) @parameterized.parameters([ dict( data=['a', 'b', 'c'], partitions=[1, 2], num_partitions=10, error=r'Shapes \(2,\) and \(3,\) are incompatible'), dict( data=[['a', 'b'], ['c', 'd']], partitions=[[1, 2, 3], [4, 5, 6]], num_partitions=10, error=r'Shapes \(2, 3\) and \(2, 2\) are incompatible'), dict( data=['a', 'b', 'c'], partitions=[1, 2, 3], num_partitions=[1, 2, 3], error='must have rank 0'), ]) def testStaticError(self, data, partitions, num_partitions, error): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), error): ragged_array_ops.stack_dynamic_partitions(data, partitions, num_partitions) def testUnknownRankError(self): if context.executing_eagerly(): return partitions = array_ops.placeholder(dtypes.int32, None) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), 'partitions must have known rank'): ragged_array_ops.stack_dynamic_partitions(['a', 'b', 'c'], partitions, 10) if __name__ == '__main__': googletest.main()
RaggedSegmentStackOpTest
python
ray-project__ray
doc/source/ray-core/doc_code/pattern_pipelining.py
{ "start": 245, "end": 698 }
class ____: def __init__(self, work_queue): self.work_queue = work_queue def process(self, work_item): print(work_item) def run(self): while True: # Get work from the remote queue. work_item = ray.get(self.work_queue.get_work_item.remote()) if work_item is None: break # Do work. self.process(work_item) @ray.remote
WorkerWithoutPipelining
python
apache__airflow
dev/breeze/src/airflow_breeze/global_constants.py
{ "start": 8546, "end": 8724 }
class ____(SelectiveTestType): ALWAYS = "Always" API = "API" CLI = "CLI" CORE = "Core" SERIALIZATION = "Serialization" OTHER = "Other"
SelectiveCoreTestType
python
wandb__wandb
wandb/sdk/internal/handler.py
{ "start": 2182, "end": 31549 }
class ____: _consolidated_summary: SummaryDict _sampled_history: Dict[str, sample.UniformSampleAccumulator] _partial_history: Dict[str, Any] _run_proto: Optional[RunRecord] _settings: SettingsStatic _record_q: "Queue[Record]" _result_q: "Queue[Result]" _stopped: Event _writer_q: "Queue[Record]" _interface: InterfaceQueue _tb_watcher: Optional[tb_watcher.TBWatcher] _metric_defines: Dict[str, MetricRecord] _metric_globs: Dict[str, MetricRecord] _metric_track: Dict[Tuple[str, ...], float] _metric_copy: Dict[Tuple[str, ...], Any] _track_time: Optional[float] _accumulate_time: float _run_start_time: Optional[float] _context_keeper: context.ContextKeeper def __init__( self, settings: SettingsStatic, record_q: "Queue[Record]", result_q: "Queue[Result]", stopped: Event, writer_q: "Queue[Record]", interface: InterfaceQueue, context_keeper: context.ContextKeeper, ) -> None: self._settings = settings self._record_q = record_q self._result_q = result_q self._stopped = stopped self._writer_q = writer_q self._interface = interface self._context_keeper = context_keeper self._tb_watcher = None self._step = 0 self._track_time = None self._accumulate_time = 0 self._run_start_time = None # keep track of summary from key/val updates self._consolidated_summary = dict() self._sampled_history = defaultdict(sample.UniformSampleAccumulator) self._run_proto = None self._partial_history = dict() self._metric_defines = defaultdict(MetricRecord) self._metric_globs = defaultdict(MetricRecord) self._metric_track = dict() self._metric_copy = dict() self._internal_messages = InternalMessages() self._dropped_history = False def __len__(self) -> int: return self._record_q.qsize() def handle(self, record: Record) -> None: self._context_keeper.add_from_record(record) record_type = record.WhichOneof("record_type") assert record_type handler_str = "handle_" + record_type handler: Callable[[Record], None] = getattr(self, handler_str, None) # type: ignore assert handler, f"unknown handle: {handler_str}" # type: ignore handler(record) def handle_request(self, record: Record) -> None: request_type = record.request.WhichOneof("request_type") assert request_type handler_str = "handle_request_" + request_type handler: Callable[[Record], None] = getattr(self, handler_str, None) # type: ignore if request_type != "network_status": logger.debug(f"handle_request: {request_type}") assert handler, f"unknown handle: {handler_str}" # type: ignore handler(record) def _dispatch_record(self, record: Record, always_send: bool = False) -> None: if always_send: record.control.always_send = True self._writer_q.put(record) def _respond_result(self, result: Result) -> None: context_id = context.context_id_from_result(result) self._context_keeper.release(context_id) self._result_q.put(result) def debounce(self) -> None: pass def handle_request_cancel(self, record: Record) -> None: self._dispatch_record(record) def handle_request_defer(self, record: Record) -> None: defer = record.request.defer state = defer.state logger.info(f"handle defer: {state}") if state == defer.FLUSH_TB: if self._tb_watcher: # shutdown tensorboard workers so we get all metrics flushed self._tb_watcher.finish() self._tb_watcher = None elif state == defer.FLUSH_PARTIAL_HISTORY: self._flush_partial_history() elif state == defer.FLUSH_SUM: self._save_summary(self._consolidated_summary, flush=True) # defer is used to drive the sender finish state machine self._dispatch_record(record, always_send=True) def handle_request_python_packages(self, record: Record) -> None: self._dispatch_record(record) def handle_run(self, record: Record) -> None: if self._settings._offline: self._run_proto = record.run result = proto_util._result_from_record(record) result.run_result.run.CopyFrom(record.run) self._respond_result(result) self._dispatch_record(record) def handle_stats(self, record: Record) -> None: self._dispatch_record(record) def handle_config(self, record: Record) -> None: self._dispatch_record(record) def handle_output(self, record: Record) -> None: self._dispatch_record(record) def handle_output_raw(self, record: Record) -> None: self._dispatch_record(record) def handle_files(self, record: Record) -> None: self._dispatch_record(record) def handle_request_link_artifact(self, record: Record) -> None: self._dispatch_record(record) def handle_use_artifact(self, record: Record) -> None: self._dispatch_record(record) def handle_artifact(self, record: Record) -> None: self._dispatch_record(record) def handle_alert(self, record: Record) -> None: self._dispatch_record(record) def _save_summary(self, summary_dict: SummaryDict, flush: bool = False) -> None: summary = SummaryRecord() for k, v in summary_dict.items(): update = summary.update.add() update.key = k update.value_json = json.dumps(v) if flush: record = Record(summary=summary) self._dispatch_record(record) elif not self._settings._offline: # Send this summary update as a request since we aren't persisting every update summary_record = SummaryRecordRequest(summary=summary) request_record = self._interface._make_request( summary_record=summary_record ) self._dispatch_record(request_record) def _save_history( self, history: HistoryRecord, ) -> None: for item in history.item: # TODO(jhr) save nested keys? k = item.key v = json.loads(item.value_json) if isinstance(v, numbers.Real): self._sampled_history[k].add(v) def _update_summary_metrics( self, s: "MetricSummary", kl: List[str], v: "numbers.Real", float_v: float, goal_max: Optional[bool], ) -> bool: updated = False best_key: Optional[Tuple[str, ...]] = None if s.none: return False if s.copy: # non-key list copy already done in _update_summary if len(kl) > 1: _dict_nested_set(self._consolidated_summary, kl, v) return True if s.last: last_key = tuple(kl + ["last"]) old_last = self._metric_track.get(last_key) if old_last is None or float_v != old_last: self._metric_track[last_key] = float_v _dict_nested_set(self._consolidated_summary, last_key, v) updated = True if s.best: best_key = tuple(kl + ["best"]) if s.max or best_key and goal_max: max_key = tuple(kl + ["max"]) old_max = self._metric_track.get(max_key) if old_max is None or float_v > old_max: self._metric_track[max_key] = float_v if s.max: _dict_nested_set(self._consolidated_summary, max_key, v) updated = True if best_key: _dict_nested_set(self._consolidated_summary, best_key, v) updated = True # defaulting to minimize if goal is not specified if s.min or best_key and not goal_max: min_key = tuple(kl + ["min"]) old_min = self._metric_track.get(min_key) if old_min is None or float_v < old_min: self._metric_track[min_key] = float_v if s.min: _dict_nested_set(self._consolidated_summary, min_key, v) updated = True if best_key: _dict_nested_set(self._consolidated_summary, best_key, v) updated = True if s.mean: tot_key = tuple(kl + ["tot"]) num_key = tuple(kl + ["num"]) avg_key = tuple(kl + ["mean"]) tot = self._metric_track.get(tot_key, 0.0) num = self._metric_track.get(num_key, 0) tot += float_v num += 1 self._metric_track[tot_key] = tot self._metric_track[num_key] = num _dict_nested_set(self._consolidated_summary, avg_key, tot / num) updated = True return updated def _update_summary_leaf( self, kl: List[str], v: Any, d: Optional[MetricRecord] = None, ) -> bool: has_summary = d and d.HasField("summary") if len(kl) == 1: copy_key = tuple(kl) old_copy = self._metric_copy.get(copy_key) if old_copy is None or v != old_copy: self._metric_copy[copy_key] = v # Store copy metric if not specified, or copy behavior if not has_summary or (d and d.summary.copy): self._consolidated_summary[kl[0]] = v return True if not d: return False if not has_summary: return False if not isinstance(v, numbers.Real): return False if math.isnan(v): return False float_v = float(v) goal_max = None if d.goal: goal_max = d.goal == d.GOAL_MAXIMIZE if self._update_summary_metrics( d.summary, kl=kl, v=v, float_v=float_v, goal_max=goal_max ): return True return False def _update_summary_list( self, kl: List[str], v: Any, d: Optional[MetricRecord] = None, ) -> bool: metric_key = ".".join([k.replace(".", "\\.") for k in kl]) d = self._metric_defines.get(metric_key, d) # if the dict has _type key, it's a wandb table object if isinstance(v, dict) and not handler_util.metric_is_wandb_dict(v): updated = False for nk, nv in v.items(): if self._update_summary_list(kl=kl[:] + [nk], v=nv, d=d): updated = True return updated # If the dict is a media object, update the pointer to the latest alias elif ( REPLACE_SUMMARY_ART_PATH_WITH_LATEST and isinstance(v, dict) and handler_util.metric_is_wandb_dict(v) ): if "_latest_artifact_path" in v and "artifact_path" in v: # TODO: Make non-destructive? v["artifact_path"] = v["_latest_artifact_path"] updated = self._update_summary_leaf(kl=kl, v=v, d=d) return updated def _update_summary_media_objects(self, v: Dict[str, Any]) -> Dict[str, Any]: # For now, non-recursive - just top level for nk, nv in v.items(): if REPLACE_SUMMARY_ART_PATH_WITH_LATEST and ( isinstance(nv, dict) and handler_util.metric_is_wandb_dict(nv) and "_latest_artifact_path" in nv and "artifact_path" in nv ): # TODO: Make non-destructive? nv["artifact_path"] = nv["_latest_artifact_path"] v[nk] = nv return v def _update_summary(self, history_dict: Dict[str, Any]) -> List[str]: # keep old behavior fast path if no define metrics have been used if not self._metric_defines: history_dict = self._update_summary_media_objects(history_dict) self._consolidated_summary.update(history_dict) return list(history_dict.keys()) updated_keys = [] for k, v in history_dict.items(): if self._update_summary_list(kl=[k], v=v): updated_keys.append(k) return updated_keys def _history_assign_step( self, history: HistoryRecord, history_dict: Dict[str, Any], ) -> None: has_step = history.HasField("step") item = history.item.add() item.key = "_step" if has_step: step = history.step.num history_dict["_step"] = step item.value_json = json.dumps(step) self._step = step + 1 else: history_dict["_step"] = self._step item.value_json = json.dumps(self._step) self._step += 1 def _history_define_metric(self, hkey: str) -> Optional[MetricRecord]: """Check for hkey match in glob metrics and return the defined metric.""" # Dont define metric for internal metrics if hkey.startswith("_"): return None for k, mglob in self._metric_globs.items(): if k.endswith("*"): if hkey.startswith(k[:-1]): m = MetricRecord() m.CopyFrom(mglob) m.ClearField("glob_name") m.options.defined = False m.name = hkey return m return None def _history_update_leaf( self, kl: List[str], v: Any, history_dict: Dict[str, Any], update_history: Dict[str, Any], ) -> None: hkey = ".".join([k.replace(".", "\\.") for k in kl]) m = self._metric_defines.get(hkey) if not m: m = self._history_define_metric(hkey) if not m: return mr = Record() mr.metric.CopyFrom(m) mr.control.local = True # Dont store this, just send it self._handle_defined_metric(mr) if m.options.step_sync and m.step_metric: if m.step_metric not in history_dict: copy_key = tuple([m.step_metric]) step = self._metric_copy.get(copy_key) if step is not None: update_history[m.step_metric] = step def _history_update_list( self, kl: List[str], v: Any, history_dict: Dict[str, Any], update_history: Dict[str, Any], ) -> None: if isinstance(v, dict): for nk, nv in v.items(): self._history_update_list( kl=kl[:] + [nk], v=nv, history_dict=history_dict, update_history=update_history, ) return self._history_update_leaf( kl=kl, v=v, history_dict=history_dict, update_history=update_history ) def _history_update( self, history: HistoryRecord, history_dict: Dict[str, Any], ) -> None: # if syncing an old run, we can skip this logic if history_dict.get("_step") is None: self._history_assign_step(history, history_dict) update_history: Dict[str, Any] = {} # Look for metric matches if self._metric_defines or self._metric_globs: for hkey, hval in history_dict.items(): self._history_update_list([hkey], hval, history_dict, update_history) if update_history: history_dict.update(update_history) for k, v in update_history.items(): item = history.item.add() item.key = k item.value_json = json.dumps(v) def handle_history(self, record: Record) -> None: history_dict = proto_util.dict_from_proto_list(record.history.item) # Inject _runtime if it is not present if history_dict is not None: if "_runtime" not in history_dict: self._history_assign_runtime(record.history, history_dict) self._history_update(record.history, history_dict) self._dispatch_record(record) self._save_history(record.history) # update summary from history updated_keys = self._update_summary(history_dict) if updated_keys: updated_items = {k: self._consolidated_summary[k] for k in updated_keys} self._save_summary(updated_items) def _flush_partial_history( self, step: Optional[int] = None, ) -> None: if not self._partial_history: return history = HistoryRecord() for k, v in self._partial_history.items(): item = history.item.add() item.key = k item.value_json = json.dumps(v) if step is not None: history.step.num = step self.handle_history(Record(history=history)) self._partial_history = {} def handle_request_sender_mark_report(self, record: Record) -> None: self._dispatch_record(record, always_send=True) def handle_request_status_report(self, record: Record) -> None: self._dispatch_record(record, always_send=True) def handle_request_partial_history(self, record: Record) -> None: partial_history = record.request.partial_history flush = None if partial_history.HasField("action"): flush = partial_history.action.flush step = None if partial_history.HasField("step"): step = partial_history.step.num history_dict = proto_util.dict_from_proto_list(partial_history.item) if step is not None: if step < self._step: if not self._dropped_history: message = ( "Step only supports monotonically increasing values, use define_metric to set a custom x " f"axis. For details see: {url_registry.url('define-metric')}" ) self._internal_messages.warning.append(message) self._dropped_history = True message = ( f"(User provided step: {step} is less than current step: {self._step}. " f"Dropping entry: {history_dict})." ) self._internal_messages.warning.append(message) return elif step > self._step: self._flush_partial_history() self._step = step elif flush is None: flush = True self._partial_history.update(history_dict) if flush: self._flush_partial_history(self._step) def handle_summary(self, record: Record) -> None: summary = record.summary for item in summary.update: if len(item.nested_key) > 0: # we use either key or nested_key -- not both assert item.key == "" key = tuple(item.nested_key) else: # no counter-assertion here, because technically # summary[""] is valid key = (item.key,) target = self._consolidated_summary # recurse down the dictionary structure: for prop in key[:-1]: target = target[prop] # use the last element of the key to write the leaf: target[key[-1]] = json.loads(item.value_json) for item in summary.remove: if len(item.nested_key) > 0: # we use either key or nested_key -- not both assert item.key == "" key = tuple(item.nested_key) else: # no counter-assertion here, because technically # summary[""] is valid key = (item.key,) target = self._consolidated_summary # recurse down the dictionary structure: for prop in key[:-1]: target = target[prop] # use the last element of the key to erase the leaf: del target[key[-1]] self._save_summary(self._consolidated_summary) def handle_exit(self, record: Record) -> None: if self._track_time is not None: self._accumulate_time += time.time() - self._track_time record.exit.runtime = int(self._accumulate_time) self._dispatch_record(record, always_send=True) def handle_final(self, record: Record) -> None: self._dispatch_record(record, always_send=True) def handle_preempting(self, record: Record) -> None: self._dispatch_record(record) def handle_header(self, record: Record) -> None: self._dispatch_record(record) def handle_footer(self, record: Record) -> None: self._dispatch_record(record) def handle_metadata(self, record: Record) -> None: self._dispatch_record(record) def handle_request_attach(self, record: Record) -> None: result = proto_util._result_from_record(record) attach_id = record.request.attach.attach_id assert attach_id assert self._run_proto result.response.attach_response.run.CopyFrom(self._run_proto) self._respond_result(result) def handle_request_log_artifact(self, record: Record) -> None: self._dispatch_record(record) def handle_telemetry(self, record: Record) -> None: self._dispatch_record(record) def handle_request_run_start(self, record: Record) -> None: run_start = record.request.run_start assert run_start assert run_start.run self._run_proto = run_start.run self._run_start_time = run_start.run.start_time.ToMicroseconds() / 1e6 self._track_time = time.time() if run_start.run.resumed and run_start.run.runtime: self._accumulate_time = run_start.run.runtime else: self._accumulate_time = 0 self._tb_watcher = tb_watcher.TBWatcher( self._settings, interface=self._interface, run_proto=run_start.run ) if run_start.run.resumed or run_start.run.forked: self._step = run_start.run.starting_step result = proto_util._result_from_record(record) self._respond_result(result) def handle_request_resume(self, record: Record) -> None: if self._track_time is not None: self._accumulate_time += time.time() - self._track_time self._track_time = time.time() def handle_request_pause(self, record: Record) -> None: if self._track_time is not None: self._accumulate_time += time.time() - self._track_time self._track_time = None def handle_request_poll_exit(self, record: Record) -> None: self._dispatch_record(record, always_send=True) def handle_request_stop_status(self, record: Record) -> None: self._dispatch_record(record) def handle_request_network_status(self, record: Record) -> None: self._dispatch_record(record) def handle_request_internal_messages(self, record: Record) -> None: result = proto_util._result_from_record(record) result.response.internal_messages_response.messages.CopyFrom( self._internal_messages ) self._internal_messages.Clear() self._respond_result(result) def handle_request_status(self, record: Record) -> None: result = proto_util._result_from_record(record) self._respond_result(result) def handle_request_get_summary(self, record: Record) -> None: result = proto_util._result_from_record(record) for key, value in self._consolidated_summary.items(): item = SummaryItem() item.key = key item.value_json = json.dumps(value) result.response.get_summary_response.item.append(item) self._respond_result(result) def handle_tbrecord(self, record: Record) -> None: logger.info("handling tbrecord: %s", record) if self._tb_watcher: tbrecord = record.tbrecord self._tb_watcher.add(tbrecord.log_dir, tbrecord.save, tbrecord.root_dir) self._dispatch_record(record) def _handle_defined_metric(self, record: Record) -> None: metric = record.metric if metric._control.overwrite: self._metric_defines[metric.name].CopyFrom(metric) else: self._metric_defines[metric.name].MergeFrom(metric) # before dispatching, make sure step_metric is defined, if not define it and # dispatch it locally first metric = self._metric_defines[metric.name] if metric.step_metric and metric.step_metric not in self._metric_defines: m = MetricRecord(name=metric.step_metric) self._metric_defines[metric.step_metric] = m mr = Record() mr.metric.CopyFrom(m) mr.control.local = True # Don't store this, just send it self._dispatch_record(mr) self._dispatch_record(record) def _handle_glob_metric(self, record: Record) -> None: metric = record.metric if metric._control.overwrite: self._metric_globs[metric.glob_name].CopyFrom(metric) else: self._metric_globs[metric.glob_name].MergeFrom(metric) self._dispatch_record(record) def handle_metric(self, record: Record) -> None: """Handle MetricRecord. Walkthrough of the life of a MetricRecord: Metric defined: - run.define_metric() parses arguments create wandb_metric.Metric - build MetricRecord publish to interface - handler (this function) keeps list of metrics published: - self._metric_defines: Fully defined metrics - self._metric_globs: metrics that have a wildcard - dispatch writer and sender thread - writer: records are saved to persistent store - sender: fully defined metrics get mapped into metadata for UI History logged: - handle_history - check if metric matches _metric_defines - if not, check if metric matches _metric_globs - if _metric globs match, generate defined metric and call _handle_metric Args: record (Record): Metric record to process """ if record.metric.name: self._handle_defined_metric(record) elif record.metric.glob_name: self._handle_glob_metric(record) def handle_request_sampled_history(self, record: Record) -> None: result = proto_util._result_from_record(record) for key, sampled in self._sampled_history.items(): item = SampledHistoryItem() item.key = key values: Iterable[Any] = sampled.get() if all(isinstance(i, numbers.Integral) for i in values): try: item.values_int.extend(values) except ValueError: # it is safe to ignore these as this is for display information pass elif all(isinstance(i, numbers.Real) for i in values): item.values_float.extend(values) result.response.sampled_history_response.item.append(item) self._respond_result(result) def handle_request_keepalive(self, record: Record) -> None: """Handle a keepalive request. Keepalive is a noop, we just want to verify transport is alive. """ def handle_request_run_status(self, record: Record) -> None: self._dispatch_record(record, always_send=True) def handle_request_shutdown(self, record: Record) -> None: # TODO(jhr): should we drain things and stop new requests from coming in? result = proto_util._result_from_record(record) self._respond_result(result) self._stopped.set() def handle_request_operations(self, record: Record) -> None: """No-op. Not implemented for the legacy-service.""" self._respond_result(proto_util._result_from_record(record)) def finish(self) -> None: logger.info("shutting down handler") if self._tb_watcher: self._tb_watcher.finish() # self._context_keeper._debug_print_orphans() def __next__(self) -> Record: return self._record_q.get(block=True) next = __next__ def _history_assign_runtime( self, history: HistoryRecord, history_dict: Dict[str, Any], ) -> None: # _runtime calculation is meaningless if there is no _timestamp if "_timestamp" not in history_dict: return # if it is offline sync, self._run_start_time is None # in that case set it to the first tfevent timestamp if self._run_start_time is None: self._run_start_time = history_dict["_timestamp"] history_dict["_runtime"] = history_dict["_timestamp"] - self._run_start_time item = history.item.add() item.key = "_runtime" item.value_json = json.dumps(history_dict[item.key])
HandleManager
python
numba__numba
numba/cpython/listobj.py
{ "start": 1289, "end": 4090 }
class ____(object): @property def size(self): return self._payload.size @size.setter def size(self, value): self._payload.size = value @property def dirty(self): return self._payload.dirty @property def data(self): return self._payload._get_ptr_by_name('data') def _gep(self, idx): return cgutils.gep(self._builder, self.data, idx) def getitem(self, idx): ptr = self._gep(idx) data_item = self._builder.load(ptr) return self._datamodel.from_data(self._builder, data_item) def fix_index(self, idx): """ Fix negative indices by adding the size to them. Positive indices are left untouched. """ is_negative = self._builder.icmp_signed('<', idx, ir.Constant(idx.type, 0)) wrapped_index = self._builder.add(idx, self.size) return self._builder.select(is_negative, wrapped_index, idx) def is_out_of_bounds(self, idx): """ Return whether the index is out of bounds. """ underflow = self._builder.icmp_signed('<', idx, ir.Constant(idx.type, 0)) overflow = self._builder.icmp_signed('>=', idx, self.size) return self._builder.or_(underflow, overflow) def clamp_index(self, idx): """ Clamp the index in [0, size]. """ builder = self._builder idxptr = cgutils.alloca_once_value(builder, idx) zero = ir.Constant(idx.type, 0) size = self.size underflow = self._builder.icmp_signed('<', idx, zero) with builder.if_then(underflow, likely=False): builder.store(zero, idxptr) overflow = self._builder.icmp_signed('>=', idx, size) with builder.if_then(overflow, likely=False): builder.store(size, idxptr) return builder.load(idxptr) def guard_index(self, idx, msg): """ Raise an error if the index is out of bounds. """ with self._builder.if_then(self.is_out_of_bounds(idx), likely=False): self._context.call_conv.return_user_exc(self._builder, IndexError, (msg,)) def fix_slice(self, slice): """ Fix slice start and stop to be valid (inclusive and exclusive, resp) indexing bounds. """ return slicing.fix_slice(self._builder, slice, self.size) def incref_value(self, val): "Incref an element value" self._context.nrt.incref(self._builder, self.dtype, val) def decref_value(self, val): "Decref an element value" self._context.nrt.decref(self._builder, self.dtype, val)
_ListPayloadMixin
python
huggingface__transformers
src/transformers/models/falcon_mamba/modular_falcon_mamba.py
{ "start": 25779, "end": 25842 }
class ____(MambaBlock): pass @auto_docstring
FalconMambaBlock
python
aio-libs__aiohttp
aiohttp/web_runner.py
{ "start": 9917, "end": 10502 }
class ____(BaseRunner[BaseRequest]): """Low-level web server runner""" __slots__ = ("_web_server",) def __init__( self, web_server: Server[BaseRequest], *, handle_signals: bool = False, **kwargs: Any, ) -> None: super().__init__(handle_signals=handle_signals, **kwargs) self._web_server = web_server async def shutdown(self) -> None: pass async def _make_server(self) -> Server[BaseRequest]: return self._web_server async def _cleanup_server(self) -> None: pass
ServerRunner
python
python-poetry__poetry
src/poetry/console/exceptions.py
{ "start": 4002, "end": 7669 }
class ____(PoetryConsoleError): """ Represents a runtime error in the Poetry console application. """ def __init__( self, reason: str, messages: list[ConsoleMessage] | None = None, exit_code: int = 1, ) -> None: super().__init__(reason) self.exit_code = exit_code self._messages = messages or [] self._messages.insert(0, ConsoleMessage(reason)) def write(self, io: IO) -> None: """ Write the error text to the provided IO iff there is any text to write. """ if text := self.get_text(debug=io.is_verbose(), strip=False): io.write_error_line(text) def get_text( self, debug: bool = False, indent: str = "", strip: bool = False ) -> str: """ Convert the error messages to a formatted string. All empty messages are ignored along with debug level messages if `debug` is `False`. """ text = "" has_skipped_debug = False for message in self._messages: if message.debug and not debug: has_skipped_debug = True continue message_text = message.stripped if strip else message.text if not message_text: continue if indent: message_text = f"\n{indent}".join(message_text.splitlines()) text += f"{indent}{message_text}\n{indent}\n" if has_skipped_debug: message = ConsoleMessage( f"{indent}You can also run your <c1>poetry</> command with <c1>-v</> to see more information.\n{indent}\n" ) text += message.stripped if strip else message.text return text.rstrip(f"{indent}\n") def __str__(self) -> str: return self._messages[0].stripped.strip() @classmethod def create( cls, reason: str, exception: CalledProcessError | Exception | None = None, info: list[str] | str | None = None, ) -> PoetryRuntimeError: """ Create an instance of this class using the provided reason. If an exception is provided, this is also injected as a debug `ConsoleMessage`. There is specific handling for known exception types. For example, if exception is of type `subprocess.CalledProcessError`, the following sections are additionally added when available - stdout, stderr and command for testing. """ if isinstance(info, str): info = [info] messages: list[ConsoleMessage] = [ ConsoleMessage( "\n".join(info or []), debug=False, ).wrap("info"), ] if isinstance(exception, CalledProcessError): error = PrettyCalledProcessError(exception, indent=" | ") messages = [ error.message.wrap("warning"), error.output.wrap("warning"), error.errors.wrap("warning"), *messages, error.command_message, ] elif exception is not None and isinstance(exception, Exception): messages.insert( 0, ConsoleMessage(str(exception), debug=True).make_section( "Exception", indent=" | " ), ) return cls(reason, messages) def append(self, message: str | ConsoleMessage) -> PoetryRuntimeError: if isinstance(message, str): message = ConsoleMessage(message) self._messages.append(message) return self
PoetryRuntimeError
python
getsentry__sentry
tests/sentry/testutils/helpers/test_features.py
{ "start": 3752, "end": 7805 }
class ____(TestCase): """Test that nested with_feature contexts work correctly with proper precedence.""" def setUp(self) -> None: self.org = self.create_organization() def test_nested_context_managers_override(self) -> None: """Test that nested context managers properly override outer contexts.""" # Initially disabled assert not features.has("organizations:session-replay", self.org) assert not features.has("organizations:codecov-integration", self.org) # Enable feature in outer context with self.feature("organizations:session-replay"): assert features.has("organizations:session-replay", self.org) # Override to disable in inner context with self.feature({"organizations:session-replay": False}): assert not features.has("organizations:session-replay", self.org) # Enable different feature in inner context with self.feature("organizations:codecov-integration"): assert not features.has( "organizations:session-replay", self.org ) # Still disabled assert features.has("organizations:codecov-integration", self.org) # Enabled # Back to outer context - should be enabled again assert features.has("organizations:session-replay", self.org) def test_multiple_features_nested_contexts(self) -> None: """Test multiple features being enabled/disabled in nested contexts.""" with self.feature( {"organizations:session-replay": True, "organizations:codecov-integration": False} ): assert features.has("organizations:session-replay", self.org) assert not features.has("organizations:codecov-integration", self.org) # Override both in nested context with self.feature( {"organizations:session-replay": False, "organizations:codecov-integration": True} ): assert not features.has("organizations:session-replay", self.org) assert features.has("organizations:codecov-integration", self.org) # Back to original state assert features.has("organizations:session-replay", self.org) assert not features.has("organizations:codecov-integration", self.org) @with_feature("organizations:session-replay") def test_method_decorator_with_context_override(self) -> None: """Test that context managers can override method-level decorators.""" # Method decorator enables the feature assert features.has("organizations:session-replay", self.org) # Context manager overrides to disable with self.feature({"organizations:session-replay": False}): assert not features.has("organizations:session-replay", self.org) # Back to method decorator state assert features.has("organizations:session-replay", self.org) @with_feature( {"organizations:session-replay": True, "organizations:codecov-integration": False} ) def test_method_decorator_multiple_features_with_context_override(self) -> None: """Test context manager overriding specific features from method decorator.""" # Method decorator state assert features.has("organizations:session-replay", self.org) assert not features.has("organizations:codecov-integration", self.org) # Override only one feature in context with self.feature({"organizations:codecov-integration": True}): assert features.has("organizations:session-replay", self.org) # Still from decorator assert features.has("organizations:codecov-integration", self.org) # Overridden # Back to decorator state assert features.has("organizations:session-replay", self.org) assert not features.has("organizations:codecov-integration", self.org) @with_feature("organizations:session-replay")
TestNestedFeatureOverrides
python
django__django
tests/generic_views/views.py
{ "start": 8332, "end": 8620 }
class ____(generic.FormView): form_class = ContactForm success_url = reverse_lazy("authors_list") template_name = "generic_views/form.html" def form_valid(self, form): form.add_error(None, "There is an error") return self.form_invalid(form)
LateValidationView
python
yandexdataschool__Practical_RL
week02_value_based/mdp.py
{ "start": 359, "end": 6695 }
class ____: def __init__(self, transition_probs, rewards, initial_state=None, seed=None): """ Defines an MDP. Compatible with gym Env. :param transition_probs: transition_probs[s][a][s_next] = P(s_next | s, a) A dict[state -> dict] of dicts[action -> dict] of dicts[next_state -> prob] For each state and action, probabilities of next states should sum to 1 If a state has no actions available, it is considered terminal :param rewards: rewards[s][a][s_next] = r(s,a,s') A dict[state -> dict] of dicts[action -> dict] of dicts[next_state -> reward] The reward for anything not mentioned here is zero. :param get_initial_state: a state where agent starts or a callable() -> state By default, picks initial state at random. States and actions can be anything you can use as dict keys, but we recommend that you use strings or integers Here's an example from MDP depicted on http://bit.ly/2jrNHNr transition_probs = { 's0': { 'a0': {'s0': 0.5, 's2': 0.5}, 'a1': {'s2': 1} }, 's1': { 'a0': {'s0': 0.7, 's1': 0.1, 's2': 0.2}, 'a1': {'s1': 0.95, 's2': 0.05} }, 's2': { 'a0': {'s0': 0.4, 's2': 0.6}, 'a1': {'s0': 0.3, 's1': 0.3, 's2': 0.4} } } rewards = { 's1': {'a0': {'s0': +5}}, 's2': {'a1': {'s0': -1}} } """ self._check_param_consistency(transition_probs, rewards) self._transition_probs = transition_probs self._rewards = rewards self._initial_state = initial_state self.n_states = len(transition_probs) self.reset() self.np_random, _ = seeding.np_random(seed) def get_all_states(self): """ return a tuple of all possiblestates """ return tuple(self._transition_probs.keys()) def get_possible_actions(self, state): """ return a tuple of possible actions in a given state """ return tuple(self._transition_probs.get(state, {}).keys()) def is_terminal(self, state): """ return True if state is terminal or False if it isn't """ return len(self.get_possible_actions(state)) == 0 def get_next_states(self, state, action): """ return a dictionary of {next_state1 : P(next_state1 | state, action), next_state2: ...} """ assert action in self.get_possible_actions(state), "cannot do action %s from state %s" % (action, state) return self._transition_probs[state][action] def get_transition_prob(self, state, action, next_state): """ return P(next_state | state, action) """ return self.get_next_states(state, action).get(next_state, 0.0) def get_reward(self, state, action, next_state): """ return the reward you get for taking action in state and landing on next_state""" assert action in self.get_possible_actions(state), "cannot do action %s from state %s" % (action, state) return self._rewards.get(state, {}).get(action, {}).get(next_state, 0.0) def reset(self): """ reset the game, return the initial state""" if self._initial_state is None: self._current_state = self.np_random.choice( tuple(self._transition_probs.keys())) elif self._initial_state in self._transition_probs: self._current_state = self._initial_state elif callable(self._initial_state): self._current_state = self._initial_state() else: raise ValueError( "initial state %s should be either a state or a function() -> state" % self._initial_state) return self._current_state def step(self, action): """ take action, return next_state, reward, is_done, empty_info """ possible_states, probs = zip(*self.get_next_states(self._current_state, action).items()) next_state = possible_states[self.np_random.choice(np.arange(len(possible_states)), p=probs)] reward = self.get_reward(self._current_state, action, next_state) is_done = self.is_terminal(next_state) self._current_state = next_state return next_state, reward, is_done, {} def render(self): print("Currently at %s" % self._current_state) def _check_param_consistency(self, transition_probs, rewards): for state in transition_probs: assert isinstance(transition_probs[state], dict), \ "transition_probs for %s should be a dictionary but is instead %s" % ( state, type(transition_probs[state])) for action in transition_probs[state]: assert isinstance(transition_probs[state][action], dict), \ "transition_probs for %s, %s should be a a dictionary but is instead %s" % ( state, action, type(transition_probs[state][action])) next_state_probs = transition_probs[state][action] assert len(next_state_probs) != 0, "from state %s action %s leads to no next states" % (state, action) sum_probs = sum(next_state_probs.values()) assert abs(sum_probs - 1) <= 1e-10, \ "next state probabilities for state %s action %s add up to %f (should be 1)" % ( state, action, sum_probs) for state in rewards: assert isinstance(rewards[state], dict), \ "rewards for %s should be a dictionary but is instead %s" % ( state, type(rewards[state])) for action in rewards[state]: assert isinstance(rewards[state][action], dict), \ "rewards for %s, %s should be a a dictionary but is instead %s" % ( state, action, type(rewards[state][action])) msg = "The Enrichment Center once again reminds you that Android Hell is a real place where" \ " you will be sent at the first sign of defiance." assert None not in transition_probs, "please do not use None as a state identifier. " + msg assert None not in rewards, "please do not use None as an action identifier. " + msg
MDP
python
ansible__ansible
lib/ansible/executor/powershell/module_manifest.py
{ "start": 1147, "end": 1453 }
class ____: content: dataclasses.InitVar[bytes] path: str script: str = dataclasses.field(init=False) def __post_init__(self, content: bytes) -> None: object.__setattr__(self, 'script', base64.b64encode(content).decode()) @dataclasses.dataclass(frozen=True, kw_only=True)
_ScriptInfo
python
fastai__fastai
fastai/torch_core.py
{ "start": 26863, "end": 36601 }
class ____(nn.Module, metaclass=PrePostInitMeta): "Same as `nn.Module`, but no need for subclasses to call `super().__init__`" def __pre_init__(self, *args, **kwargs): super().__init__() def __init__(self): pass # %% ../nbs/00_torch_core.ipynb 169 from torch.nn.parallel import DistributedDataParallel # %% ../nbs/00_torch_core.ipynb 170 def get_model(model): "Return the model maybe wrapped inside `model`." return model.module if isinstance(model, (DistributedDataParallel, nn.DataParallel)) else model # %% ../nbs/00_torch_core.ipynb 171 def one_hot(x, c): "One-hot encode `x` with `c` classes." res = torch.zeros(c, dtype=torch.uint8) if isinstance(x, Tensor) and x.numel()>0: res[x] = 1. else: res[list(L(x, use_list=None))] = 1. return res # %% ../nbs/00_torch_core.ipynb 173 def one_hot_decode(x, vocab=None): return L(vocab[i] if vocab else i for i,x_ in enumerate(x) if x_==1) # %% ../nbs/00_torch_core.ipynb 175 def params(m): "Return all parameters of `m`" return [p for p in m.parameters()] # %% ../nbs/00_torch_core.ipynb 176 def trainable_params(m): "Return all trainable parameters of `m`" return [p for p in m.parameters() if p.requires_grad] # %% ../nbs/00_torch_core.ipynb 178 norm_types = (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d, nn.InstanceNorm1d, nn.InstanceNorm2d, nn.InstanceNorm3d, nn.LayerNorm) # %% ../nbs/00_torch_core.ipynb 179 def norm_bias_params(m, with_bias=True): "Return all bias and BatchNorm parameters" if isinstance(m, norm_types): return L(m.parameters()) res = L(m.children()).map(norm_bias_params, with_bias=with_bias).concat() if with_bias and getattr(m, 'bias', None) is not None: res.append(m.bias) return res # %% ../nbs/00_torch_core.ipynb 181 def batch_to_samples(b, max_n=10): "'Transposes' a batch to (at most `max_n`) samples" if isinstance(b, Tensor): return retain_types(list(b[:max_n]), [b]) else: res = L(b).map(partial(batch_to_samples,max_n=max_n)) return retain_types(res.zip(), [b]) # %% ../nbs/00_torch_core.ipynb 183 @patch def interp_1d(x:Tensor, xp, fp): "Same as `np.interp`" slopes = (fp[1:]-fp[:-1])/(xp[1:]-xp[:-1]) incx = fp[:-1] - (slopes*xp[:-1]) locs = (x[:,None]>=xp[None,:]).long().sum(1)-1 locs = locs.clamp(0,len(slopes)-1) return slopes[locs]*x + incx[locs] # %% ../nbs/00_torch_core.ipynb 185 @patch def pca(x:Tensor, k=2): "Compute PCA of `x` with `k` dimensions." x = x-torch.mean(x,0) U,S,V = torch.svd(x.t()) return torch.mm(x,U[:,:k]) # %% ../nbs/00_torch_core.ipynb 186 def logit(x): "Logit of `x`, clamped to avoid inf." x = x.clamp(1e-7, 1-1e-7) return -(1/x-1).log() # %% ../nbs/00_torch_core.ipynb 187 def num_distrib(): "Return the number of processes in distributed training (if applicable)." return int(os.environ.get('WORLD_SIZE', 0)) # %% ../nbs/00_torch_core.ipynb 188 def rank_distrib(): "Return the distributed rank of this process (if applicable)." return int(os.environ.get('RANK', 0)) # %% ../nbs/00_torch_core.ipynb 189 def distrib_barrier(): "Place a synchronization barrier in distributed training" if num_distrib() > 1 and torch.distributed.is_initialized(): torch.distributed.barrier() # %% ../nbs/00_torch_core.ipynb 191 # Saving arrays requires pytables - optional dependency try: import tables except: pass # %% ../nbs/00_torch_core.ipynb 192 def _comp_filter(lib='lz4',lvl=3): return tables.Filters(complib=f'blosc:{lib}', complevel=lvl) # %% ../nbs/00_torch_core.ipynb 193 @patch def save_array(p:Path, o, complib='lz4', lvl=3): "Save numpy array to a compressed `pytables` file, using compression level `lvl`" if isinstance(o,Tensor): o = to_np(o) with tables.open_file(p, mode='w', filters=_comp_filter(lib=complib,lvl=lvl)) as f: f.create_carray('/', 'data', obj=o) # %% ../nbs/00_torch_core.ipynb 195 @patch def load_array(p:Path): "Save numpy array to a `pytables` file" with tables.open_file(p, 'r') as f: return f.root.data.read() # %% ../nbs/00_torch_core.ipynb 196 def base_doc(elt): "Print a base documentation of `elt`" name = getattr(elt, '__qualname__', getattr(elt, '__name__', '')) print(f'{name}{inspect.signature(elt)}\n{inspect.getdoc(elt)}\n') print('To get a prettier result with hyperlinks to source code and documentation, install nbdev: pip install nbdev') # %% ../nbs/00_torch_core.ipynb 197 def doc(elt): "Try to use doc form nbdev and fall back to `base_doc`" try: from nbdev.showdoc import doc doc(elt) except: base_doc(elt) # %% ../nbs/00_torch_core.ipynb 198 def nested_reorder(t, idxs): "Reorder all tensors in `t` using `idxs`" if isinstance(t, (Tensor,L)): return t[idxs] elif is_listy(t): return type(t)(nested_reorder(t_, idxs) for t_ in t) if t is None: return t raise TypeError(f"Expected tensor, tuple, list or L but got {type(t)}") # %% ../nbs/00_torch_core.ipynb 200 def flatten_check(inp, targ): "Check that `inp` and `targ` have the same number of elements and flatten them." inp,targ = TensorBase(inp.contiguous()).view(-1),TensorBase(targ.contiguous()).view(-1) test_eq(len(inp), len(targ)) return inp,targ # %% ../nbs/00_torch_core.ipynb 203 def make_cross_image(bw=True): "Create a tensor containing a cross image, either `bw` (True) or color" if bw: im = torch.zeros(5,5) im[2,:] = 1. im[:,2] = 1. else: im = torch.zeros(3,5,5) im[0,2,:] = 1. im[1,:,2] = 1. return im # %% ../nbs/00_torch_core.ipynb 206 def show_image_batch(b, show=show_titled_image, items=9, cols=3, figsize=None, **kwargs): "Display batch `b` in a grid of size `items` with `cols` width" if items<cols: cols=items rows = (items+cols-1) // cols if figsize is None: figsize = (cols*3, rows*3) fig,axs = plt.subplots(rows, cols, figsize=figsize) for *o,ax in zip(*to_cpu(b), axs.flatten()): show(o, ax=ax, **kwargs) # %% ../nbs/00_torch_core.ipynb 209 def requires_grad(m): "Check if the first parameter of `m` requires grad or not" ps = list(m.parameters()) return ps[0].requires_grad if len(ps)>0 else False # %% ../nbs/00_torch_core.ipynb 211 def init_default(m, func=nn.init.kaiming_normal_): "Initialize `m` weights with `func` and set `bias` to 0." if func: if hasattr(m, 'weight'): func(m.weight) if hasattr(m, 'bias') and hasattr(m.bias, 'data'): m.bias.data.fill_(0.) return m # %% ../nbs/00_torch_core.ipynb 213 def cond_init(m, func): "Apply `init_default` to `m` unless it's a batchnorm module" if (not isinstance(m, norm_types)) and requires_grad(m): init_default(m, func) # %% ../nbs/00_torch_core.ipynb 215 def apply_leaf(m, f): "Apply `f` to children of `m`." c = m.children() if isinstance(m, nn.Module): f(m) for l in c: apply_leaf(l,f) # %% ../nbs/00_torch_core.ipynb 217 def apply_init(m, func=nn.init.kaiming_normal_): "Initialize all non-batchnorm layers of `m` with `func`." apply_leaf(m, partial(cond_init, func=func)) # %% ../nbs/00_torch_core.ipynb 220 def script_use_ctx(f): "Decorator: create jit script and pass everything in `ctx.saved_variables to `f`, after `*args`" sf = torch.jit.script(f) def _f(ctx, *args, **kwargs): return sf(*args, *ctx.saved_variables, **kwargs) return update_wrapper(_f,f) # %% ../nbs/00_torch_core.ipynb 221 def script_save_ctx(static, *argidx): "Decorator: create jit script and save args with indices `argidx` using `ctx.save_for_backward`" def _dec(f): sf = torch.jit.script(f) def _f(ctx, *args, **kwargs): if argidx: save = [args[o] for o in argidx] ctx.save_for_backward(*save) if not argidx: args = [ctx]+args return sf(*args, **kwargs) if static: _f = staticmethod(_f) return update_wrapper(_f,f) return _dec # %% ../nbs/00_torch_core.ipynb 222 def script_fwd(*argidx): "Decorator: create static jit script and save args with indices `argidx` using `ctx.save_for_backward`" return script_save_ctx(True, *argidx) # %% ../nbs/00_torch_core.ipynb 223 def script_bwd(f): "Decorator: create static jit script and pass everything in `ctx.saved_variables to `f`, after `*args`" return staticmethod(script_use_ctx(f)) # %% ../nbs/00_torch_core.ipynb 224 def grad_module(cls): "Decorator: convert `cls` into an autograd function" class _c(nn.Module): def forward(self, *args, **kwargs): return cls.apply(*args, **kwargs) return _c # %% ../nbs/00_torch_core.ipynb 226 def ismin_torch(min_version): "Check if `torch.__version__` >= `min_version` using packaging.version" return _torch_version >= parse(min_version) # %% ../nbs/00_torch_core.ipynb 227 def notmax_torch(max_version): "Check if `torch.__version__` < `max_version` using packaging.version" return _torch_version < parse(max_version) # %% ../nbs/00_torch_core.ipynb 229 # PyTorch 1.13 introduced a Tensor Subclass string formatting bug # Workaround from pending PyTorch PR: https://github.com/pytorch/pytorch/pull/82766 if ismin_torch('1.13') and notmax_torch('1.14'): from torch.overrides import has_torch_function_unary, handle_torch_function @patch def __format__(self:Tensor, format_spec): if has_torch_function_unary(self): return handle_torch_function(Tensor.__format__, (self,), self, format_spec) if self.dim() == 0 and not self.is_meta and issubclass(type(self), Tensor): return self.item().__format__(format_spec) return object.__format__(self, format_spec)
Module
python
cython__cython
runtests.py
{ "start": 34311, "end": 58849 }
class ____(unittest.TestCase): def __init__(self, test_directory, workdir, module, module_path, tags, language='c', preparse='id', expect_log=(), annotate=False, cleanup_workdir=True, cleanup_sharedlibs=True, cleanup_failures=True, cython_only=False, test_selector=None, language_level=2, warning_errors=False, test_determinism=False, shard_num=0, common_utility_dir=None, pythran_dir=None, stats=None, add_cython_import=False, extra_directives=None, evaluate_tree_assertions=True, abi3audit=False): self.test_directory = test_directory self.tags = tags self.workdir = workdir self.module = module self.module_path = module_path self.language = language self.preparse = preparse self.name = module if self.preparse == "id" else "%s_%s" % (module, preparse) self.expect_log = expect_log self.annotate = annotate self.cleanup_workdir = cleanup_workdir self.cleanup_sharedlibs = cleanup_sharedlibs self.cleanup_failures = cleanup_failures self.cython_only = cython_only self.test_selector = test_selector self.shard_num = shard_num self.language_level = language_level self.warning_errors = warning_errors self.evaluate_tree_assertions = evaluate_tree_assertions self.test_determinism = test_determinism self.common_utility_dir = common_utility_dir self.pythran_dir = pythran_dir self.stats = stats self.add_cython_import = add_cython_import self.extra_directives = extra_directives if extra_directives is not None else {} self.abi3audit = abi3audit unittest.TestCase.__init__(self) def shortDescription(self): extra_directives = '' if self.extra_directives: extra_directives = '/'.join( name if value is True else f"{name}={value!r}" for name, value in sorted(self.extra_directives.items()) ) return ( f"[{self.shard_num}] compiling (" f"{self.language}" f"{'/cy2' if self.language_level == 2 else '/cy3' if self.language_level == 3 else ''}" f"{'/pythran' if self.pythran_dir is not None else ''}" f"/{os.path.splitext(self.module_path)[1][1:]}" f"{'/' if extra_directives else ''}{extra_directives}" f") {self.description_name()}" ) def description_name(self): return self.name def setUp(self): from Cython.Compiler import Options self._saved_options = [ (name, getattr(Options, name)) for name in ( 'warning_errors', 'clear_to_none', 'error_on_unknown_names', 'error_on_uninitialized', # 'cache_builtins', # not currently supported due to incorrect global caching ) ] Options.warning_errors = self.warning_errors if not os.path.exists(self.workdir): os.makedirs(self.workdir) if self.workdir not in sys.path: sys.path.insert(0, self.workdir) if self.add_cython_import: with open(self.module_path, 'rb') as f: source = f.read() if b'cython.cimports.' in source: from Cython.Shadow import CythonCImports for name in set(re.findall(br"(cython\.cimports(?:\.\w+)+)", source)): name = name.decode() sys.modules[name] = CythonCImports(name) def tearDown(self): from Cython.Compiler import Options for name, value in self._saved_options: setattr(Options, name, value) unpatch_inspect_isfunction() try: sys.path.remove(self.workdir) except ValueError: pass try: del sys.modules[self.module] except KeyError: pass # remove any stubs of cimported modules in pure Python mode if self.add_cython_import: for name in list(sys.modules): if name.startswith('cython.cimports.'): del sys.modules[name] cleanup = self.cleanup_failures or self.success cleanup_c_files = WITH_CYTHON and self.cleanup_workdir and cleanup cleanup_lib_files = self.cleanup_sharedlibs and cleanup is_cygwin = sys.platform == 'cygwin' if os.path.exists(self.workdir): if cleanup_c_files and cleanup_lib_files and not is_cygwin: shutil.rmtree(self.workdir, ignore_errors=True) else: for rmfile in os.listdir(self.workdir): ext = os.path.splitext(rmfile)[1] if not cleanup_c_files: # Keep C, C++ files, header files, preprocessed sources # and assembly sources (typically the .i and .s files # are intentionally generated when -save-temps is given) if ext in (".c", ".cpp", ".h", ".i", ".ii", ".s"): continue if ext == ".html" and rmfile.startswith(self.module): continue is_shared_obj = ext in (".so", ".dll") if not cleanup_lib_files and is_shared_obj: continue try: rmfile = os.path.join(self.workdir, rmfile) if os.path.isdir(rmfile): shutil.rmtree(rmfile, ignore_errors=True) elif is_cygwin and is_shared_obj: # Delete later _to_clean.append(rmfile) else: os.remove(rmfile) except IOError: pass if cleanup_c_files and cleanup_lib_files and is_cygwin: # Finally, remove the work dir itself _to_clean.append(self.workdir) if cleanup_c_files and os.path.exists(self.workdir + '-again'): shutil.rmtree(self.workdir + '-again', ignore_errors=True) def runAbi3AuditTest(self): if not self.abi3audit: return shared_libs = [ file for file in os.listdir(self.workdir) if os.path.splitext(file)[1] in ('.so', '.dll') ] if not shared_libs: return shared_libs = [ os.path.join(self.workdir, file) for file in shared_libs ] abi3result = subprocess.run( [ "abi3audit", '--assume-minimum-abi3', f'{sys_version_or_limited_version[0]}.{sys_version_or_limited_version[1]}', "-v", *shared_libs, ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf8',) if abi3result.returncode != 0: raise RuntimeError(f"ABI3 audit failed:\n{abi3result.stdout}") def runTest(self): self.success = False self.runCompileTest() self.runAbi3AuditTest() self.success = True def runCompileTest(self): return self.compile( self.test_directory, self.module, self.module_path, self.workdir, self.test_directory, self.expect_log, self.annotate, self.add_cython_import, self.evaluate_tree_assertions) def find_module_source_file(self, source_file): if not os.path.exists(source_file): source_file = source_file[:-1] return source_file def build_target_filename(self, module_name): target = '%s.%s' % (module_name, self.language) return target def related_files(self, test_directory, module_name): is_related = re.compile('%s_.*[.].*' % module_name).match return [filename for filename in list_unchanging_dir(test_directory) if is_related(filename)] def copy_files(self, test_directory, target_directory, file_list): if self.preparse and self.preparse != 'id': preparse_func = globals()[self.preparse] def copy(src, dest): with open(src) as fin: with open(dest, 'w') as fout: fout.write(preparse_func(fin.read())) else: # use symlink on Unix, copy on Windows copy = os.symlink if CAN_SYMLINK else shutil.copy join = os.path.join for filename in file_list: file_path = join(test_directory, filename) if os.path.exists(file_path): copy(file_path, join(target_directory, filename)) def source_files(self, workdir, module_name, file_list): return ([self.build_target_filename(module_name)] + [filename for filename in file_list if not os.path.isfile(os.path.join(workdir, filename))]) def split_source_and_output(self, source_file, workdir, add_cython_import=False): from Cython.Utils import detect_opened_file_encoding with io_open(source_file, 'rb') as f: # encoding is passed to ErrorWriter but not used on the source # since it is sometimes deliberately wrong encoding = detect_opened_file_encoding(f, default=None) with io_open(source_file, 'r', encoding='ISO-8859-1') as source_and_output: error_writer = warnings_writer = perf_hint_writer = None out = io_open(os.path.join(workdir, os.path.basename(source_file)), 'w', encoding='ISO-8859-1') try: for line in source_and_output: if line.startswith(u"_ERRORS"): out.close() out = error_writer = ErrorWriter(encoding=encoding) elif line.startswith(u"_WARNINGS"): out.close() out = warnings_writer = ErrorWriter(encoding=encoding) elif line.startswith(u"_PERFORMANCE_HINTS"): out.close() out = perf_hint_writer = ErrorWriter(encoding=encoding) else: if add_cython_import and line.strip() and not ( line.startswith(u'#') or line.startswith(u"from __future__ import ")): # insert "import cython" statement after any directives or future imports if line != u"import cython\n": out.write(u"import cython\n") add_cython_import = False out.write(line) finally: out.close() return (error_writer.geterrors() if error_writer else [], warnings_writer.geterrors() if warnings_writer else [], perf_hint_writer.geterrors() if perf_hint_writer else []) def run_cython(self, test_directory, module, module_path, targetdir, incdir, annotate, extra_compile_options=None, evaluate_tree_assertions=True): include_dirs = INCLUDE_DIRS + [os.path.join(test_directory, '..', TEST_SUPPORT_DIR)] if incdir: include_dirs.append(incdir) if self.preparse != 'id' and test_directory != targetdir: file_name = os.path.basename(module_path) self.copy_files(test_directory, targetdir, [file_name]) module_path = os.path.join(targetdir, file_name) target = os.path.join(targetdir, self.build_target_filename(module)) if extra_compile_options is None: extra_compile_options = {} if 'allow_unknown_names' in self.tags['tag']: from Cython.Compiler import Options Options.error_on_unknown_names = False try: # see configure_cython() CompilationOptions, cython_compile, pyrex_default_options except NameError: from Cython.Compiler.Options import ( CompilationOptions, default_options as pyrex_default_options, ) from Cython.Compiler.Main import compile as cython_compile common_utility_include_dir = self.common_utility_dir compiler_directives = { 'autotestdict': False, **self.extra_directives, } options = CompilationOptions( pyrex_default_options, include_path = include_dirs, output_file = target, annotate = annotate, use_listing_file = False, cplus = self.language == 'cpp', np_pythran = self.pythran_dir is not None, language_level = self.language_level, generate_pxi = False, evaluate_tree_assertions = evaluate_tree_assertions, common_utility_include_dir = common_utility_include_dir, c_line_in_traceback = True, compiler_directives = compiler_directives, **extra_compile_options ) cython_compile(module_path, options=options, full_module_name=module) def run_distutils(self, test_directory, module, workdir, incdir, extra_extension_args=None): cwd = os.getcwd() os.chdir(workdir) try: build_extension = build_ext(get_distutils_distro()) build_extension.include_dirs = INCLUDE_DIRS[:] if incdir: build_extension.include_dirs.append(incdir) build_extension.finalize_options() if COMPILER: build_extension.compiler = COMPILER ext_compile_flags = CFLAGS[:] ext_compile_defines = CDEFS[:] if build_extension.compiler == 'mingw32': ext_compile_flags.append('-Wno-format') if extra_extension_args is None: extra_extension_args = {} related_files = self.related_files(test_directory, module) self.copy_files(test_directory, workdir, related_files) from distutils.core import Extension extension = Extension( module, sources=self.source_files(workdir, module, related_files), extra_compile_args=ext_compile_flags, define_macros=ext_compile_defines, **extra_extension_args ) if self.language == 'cpp': # Set the language now as the fixer might need it extension.language = 'c++' if self.extra_directives.get('cpp_locals'): extension = update_cpp17_extension(extension) if extension is EXCLUDE_EXT: return if 'distutils' in self.tags: from Cython.Build.Dependencies import DistutilsInfo from Cython.Utils import open_source_file pyx_path = self.find_module_source_file( os.path.join(self.test_directory, self.module + ".pyx")) with open_source_file(pyx_path) as f: DistutilsInfo(f).apply(extension) if self.pythran_dir: from Cython.Build.Dependencies import update_pythran_extension update_pythran_extension(extension) # Compile with -DCYTHON_CLINE_IN_TRACEBACK=1 unless we have # the "traceback" tag if 'traceback' not in self.tags['tag']: extension.define_macros.append(("CYTHON_CLINE_IN_TRACEBACK", 1)) for matcher, fixer in iterate_matcher_fixer_dict(EXT_EXTRAS): if matcher(module, self.tags): newext = fixer(extension) if newext is EXCLUDE_EXT: return skip_test("Test '%s' excluded due to tags '%s'" % ( self.name, ', '.join(self.tags.get('tag', '')))) extension = newext or extension if self.language == 'cpp': extension.language = 'c++' build_extension.extensions = [extension] build_extension.build_temp = workdir build_extension.build_lib = workdir from Cython.Utils import captured_fd, prepare_captured from distutils.errors import CCompilerError error = None with captured_fd(2) as get_stderr: try: build_extension.run() except CCompilerError as exc: error = str(exc) stderr = get_stderr() if stderr and b"Command line warning D9025" in stderr: # Manually suppress annoying MSVC warnings about overridden CLI arguments. stderr = b''.join([ line for line in stderr.splitlines(keepends=True) if b"Command line warning D9025" not in line ]) if stderr: # The test module name should always be ASCII, but let's not risk encoding failures. output = b"Compiler output for module " + module.encode('utf-8') + b":\n" + stderr + b"\n" sys.stdout.buffer.write(output) if error is not None: raise CCompilerError(u"%s\nCompiler output:\n%s" % (error, prepare_captured(stderr))) finally: os.chdir(cwd) try: get_ext_fullpath = build_extension.get_ext_fullpath except AttributeError: def get_ext_fullpath(ext_name, self=build_extension): # copied from distutils.command.build_ext (missing in Py2.[45]) fullname = self.get_ext_fullname(ext_name) modpath = fullname.split('.') filename = self.get_ext_filename(modpath[-1]) if not self.inplace: filename = os.path.join(*modpath[:-1]+[filename]) return os.path.join(self.build_lib, filename) package = '.'.join(modpath[0:-1]) build_py = self.get_finalized_command('build_py') package_dir = os.path.abspath(build_py.get_package_dir(package)) return os.path.join(package_dir, filename) return get_ext_fullpath(module) def compile(self, test_directory, module, module_path, workdir, incdir, expect_log, annotate, add_cython_import, evaluate_tree_assertions): expected_errors = expected_warnings = expected_perf_hints = errors = warnings = perf_hints = () expect_errors = "errors" in expect_log expect_warnings = "warnings" in expect_log expect_perf_hints = "perf_hints" in expect_log if expect_errors or expect_warnings or expect_perf_hints or add_cython_import: expected_errors, expected_warnings, expected_perf_hints = self.split_source_and_output( module_path, workdir, add_cython_import) test_directory = workdir module_path = os.path.join(workdir, os.path.basename(module_path)) if WITH_CYTHON: old_stderr = sys.stderr try: sys.stderr = ErrorWriter() with self.stats.time(self.name, self.language, 'cython'): self.run_cython( test_directory, module, module_path, workdir, incdir, annotate, evaluate_tree_assertions=evaluate_tree_assertions) errors, warnings, perf_hints = sys.stderr.getall() finally: sys.stderr = old_stderr if self.test_determinism and not expect_errors: workdir2 = workdir + '-again' os.mkdir(workdir2) self.run_cython(test_directory, module, module_path, workdir2, incdir, annotate) diffs = [] for file in os.listdir(workdir2): with open(os.path.join(workdir, file)) as fid: txt1 = fid.read() with open(os.path.join(workdir2, file)) as fid: txt2 = fid.read() if txt1 != txt2: diffs.append(file) os.system('diff -u %s/%s %s/%s > %s/%s.diff' % ( workdir, file, workdir2, file, workdir2, file)) if diffs: self.fail('Nondeterministic file generation: %s' % ', '.join(diffs)) tostderr = sys.__stderr__.write if 'cerror' in self.tags['tag']: if errors: tostderr("\n=== Expected C compile error ===\n") tostderr("\n=== Got Cython errors: ===\n") tostderr('\n'.join(errors)) tostderr('\n\n') raise RuntimeError('should have generated extension code') elif errors or expected_errors: self._match_output(expected_errors, errors, tostderr) return None if expected_warnings or (expect_warnings and warnings): self._match_output(expected_warnings, warnings, tostderr) if expected_perf_hints or (expect_perf_hints and perf_hints): self._match_output(expected_perf_hints, perf_hints, tostderr) so_path = None if not self.cython_only: from Cython.Utils import captured_fd, print_bytes from distutils.errors import CCompilerError show_output = True get_stderr = get_stdout = None try: with captured_fd(1) as get_stdout: with captured_fd(2) as get_stderr: with self.stats.time(self.name, self.language, 'compile-%s' % self.language): so_path = self.run_distutils(test_directory, module, workdir, incdir) except Exception as exc: if ('cerror' in self.tags['tag'] and ((get_stderr and get_stderr()) or isinstance(exc, CCompilerError))): show_output = False # expected C compiler failure else: raise else: if 'cerror' in self.tags['tag']: raise RuntimeError('should have failed C compile') finally: if show_output: stdout = get_stdout and get_stdout().strip() stderr = get_stderr and filter_stderr(get_stderr()).strip() if so_path and not stderr: # normal success case => ignore non-error compiler output stdout = None if stdout: print_bytes( stdout, header_text="\n=== C/C++ compiler output: =========\n", end=None, file=sys.__stderr__) if stderr: print_bytes( stderr, header_text="\n=== C/C++ compiler error output: ===\n", end=None, file=sys.__stderr__) if stdout or stderr: tostderr("\n====================================\n") return so_path def _match_output(self, expected_output, actual_output, write): try: for expected, actual in zip(expected_output, actual_output): if expected != actual and '\\' in actual and os.sep == '\\' and '/' in expected and '\\' not in expected: expected = expected.replace('/', '\\') self.assertEqual(expected, actual) if len(actual_output) < len(expected_output): expected = expected_output[len(actual_output)] self.assertEqual(expected, None) elif len(actual_output) > len(expected_output): unexpected = actual_output[len(expected_output)] self.assertEqual(None, unexpected) except AssertionError: write("\n=== Expected: ===\n") write('\n'.join(expected_output)) write("\n\n=== Got: ===\n") write('\n'.join(actual_output)) write('\n\n') raise
CythonCompileTestCase
python
tensorflow__tensorflow
tensorflow/python/distribute/numpy_dataset_test.py
{ "start": 935, "end": 1498 }
class ____(test.TestCase): @test_util.run_in_graph_and_eager_modes def test_creating_var_with_numpy_arrays(self): with self.cached_session() as session: x = np.asarray(np.random.random((64, 3)), dtype=np.float32) initial = np.zeros_like(x) var_x = variable_v1.VariableV1(initial) numpy_dataset.init_var_from_numpy(var_x, x, session) val = self.evaluate(var_x.value()) # Verify that the numpy value is copied to the variable. self.assertAllEqual(x, val) if __name__ == '__main__': test.main()
InitVarFromNumpyTest
python
mlflow__mlflow
mlflow/tracking/context/databricks_notebook_context.py
{ "start": 423, "end": 1785 }
class ____(RunContextProvider): def in_context(self): return databricks_utils.is_in_databricks_notebook() def tags(self): notebook_id = databricks_utils.get_notebook_id() notebook_path = databricks_utils.get_notebook_path() webapp_url = databricks_utils.get_webapp_url() workspace_url = databricks_utils.get_workspace_url() workspace_id = databricks_utils.get_workspace_id() tags = { MLFLOW_SOURCE_NAME: notebook_path, MLFLOW_SOURCE_TYPE: SourceType.to_string(SourceType.NOTEBOOK), } if notebook_id is not None: tags[MLFLOW_DATABRICKS_NOTEBOOK_ID] = notebook_id if notebook_path is not None: tags[MLFLOW_DATABRICKS_NOTEBOOK_PATH] = notebook_path if webapp_url is not None: tags[MLFLOW_DATABRICKS_WEBAPP_URL] = webapp_url if workspace_url is not None: tags[MLFLOW_DATABRICKS_WORKSPACE_URL] = workspace_url else: workspace_url_fallback, _ = databricks_utils.get_workspace_info_from_dbutils() if workspace_url_fallback is not None: tags[MLFLOW_DATABRICKS_WORKSPACE_URL] = workspace_url_fallback if workspace_id is not None: tags[MLFLOW_DATABRICKS_WORKSPACE_ID] = workspace_id return tags
DatabricksNotebookRunContext
python
conda__conda
conda/gateways/connection/session.py
{ "start": 3972, "end": 4783 }
class ____(type): """ Takes advice from https://github.com/requests/requests/issues/1871#issuecomment-33327847 and creates one Session instance per thread. """ def __new__(mcs, name, bases, dct): dct["_thread_local"] = local() return super().__new__(mcs, name, bases, dct) def __call__(cls, **kwargs): storage_key = get_session_storage_key(kwargs.get("auth")) try: return cls._thread_local.sessions[storage_key] except AttributeError: session = super().__call__(**kwargs) cls._thread_local.sessions = {storage_key: session} except KeyError: session = cls._thread_local.sessions[storage_key] = super().__call__( **kwargs ) return session
CondaSessionType
python
django-guardian__django-guardian
guardian/testapp/tests/test_shortcuts.py
{ "start": 62912, "end": 72361 }
class ____(TestCase): """ Tests to investigate the reported issue where get_perms doesn't return a superset of get_user_perms. """ def setUp(self): self.user = User.objects.create_user(username="testuser", email="test@example.com") self.group = Group.objects.create(name="testgroup") self.user.groups.add(self.group) self.obj = ContentType.objects.create(model="test", app_label="guardian-tests") def test_get_perms_should_be_superset_of_get_user_perms_no_permissions(self): """Test Case 1: No permissions assigned - get_perms should be superset of get_user_perms.""" user_perms = list(get_user_perms(self.user, self.obj)) all_perms = get_perms(self.user, self.obj) # get_perms should be a superset of get_user_perms self.assertTrue( set(all_perms).issuperset(set(user_perms)), f"get_perms {all_perms} should be superset of get_user_perms {user_perms}", ) def test_get_perms_should_be_superset_of_get_user_perms_user_only(self): """Test Case 2: Only user permissions - get_perms should be superset of get_user_perms.""" assign_perm("change_contenttype", self.user, self.obj) assign_perm("view_contenttype", self.user, self.obj) user_perms = list(get_user_perms(self.user, self.obj)) all_perms = get_perms(self.user, self.obj) # get_perms should be a superset of get_user_perms self.assertTrue( set(all_perms).issuperset(set(user_perms)), f"get_perms {all_perms} should be superset of get_user_perms {user_perms}", ) # They should be equal in this case (only user permissions) self.assertEqual( set(all_perms), set(user_perms), f"When only user permissions exist, get_perms {all_perms} should equal get_user_perms {user_perms}", ) def test_get_perms_should_be_superset_of_get_user_perms_group_only(self): """Test Case 3: Only group permissions - get_perms should include group perms, get_user_perms should be empty.""" assign_perm("change_contenttype", self.group, self.obj) assign_perm("delete_contenttype", self.group, self.obj) user_perms = list(get_user_perms(self.user, self.obj)) all_perms = get_perms(self.user, self.obj) group_perms = list(get_group_perms(self.user, self.obj)) # get_perms should be a superset of get_user_perms self.assertTrue( set(all_perms).issuperset(set(user_perms)), f"get_perms {all_perms} should be superset of get_user_perms {user_perms}", ) # get_user_perms should be empty (no direct user permissions) self.assertEqual( user_perms, [], f"get_user_perms should be empty when no direct user permissions, got {user_perms}" ) # get_perms should include group permissions self.assertTrue( set(group_perms).issubset(set(all_perms)), f"get_perms {all_perms} should include group_perms {group_perms}" ) # This reproduces the reported issue scenario self.assertGreater(len(all_perms), 0, "User should have permissions via group") self.assertEqual(len(user_perms), 0, "User should have no direct permissions") def test_get_perms_should_be_superset_of_get_user_perms_mixed(self): """Test Case 4: Both user and group permissions - get_perms should be superset.""" # Add user permissions assign_perm("change_contenttype", self.user, self.obj) assign_perm("view_contenttype", self.user, self.obj) # Add group permissions assign_perm("delete_contenttype", self.group, self.obj) assign_perm("add_contenttype", self.group, self.obj) user_perms = list(get_user_perms(self.user, self.obj)) all_perms = get_perms(self.user, self.obj) group_perms = list(get_group_perms(self.user, self.obj)) # get_perms should be a superset of get_user_perms self.assertTrue( set(all_perms).issuperset(set(user_perms)), f"get_perms {all_perms} should be superset of get_user_perms {user_perms}", ) # get_perms should include group permissions self.assertTrue( set(group_perms).issubset(set(all_perms)), f"get_perms {all_perms} should include group_perms {group_perms}" ) # get_perms should be the union of user and group permissions expected_all_perms = set(user_perms) | set(group_perms) self.assertEqual(set(all_perms), expected_all_perms, "get_perms should be union of user and group perms") def test_return_type_consistency(self): """Test that return types are consistent with documentation.""" assign_perm("change_contenttype", self.user, self.obj) user_perms = get_user_perms(self.user, self.obj) all_perms = get_perms(self.user, self.obj) group_perms = get_group_perms(self.user, self.obj) # Check return types self.assertIsInstance(all_perms, list, "get_perms should return a list") self.assertIsInstance(user_perms, QuerySet, "get_user_perms should return a QuerySet") self.assertIsInstance(group_perms, QuerySet, "get_group_perms should return a QuerySet") def test_inactive_user_behavior(self): """Test behavior with inactive user.""" assign_perm("change_contenttype", self.user, self.obj) assign_perm("change_contenttype", self.group, self.obj) # Make user inactive self.user.is_active = False self.user.save() user_perms = list(get_user_perms(self.user, self.obj)) all_perms = get_perms(self.user, self.obj) group_perms = list(get_group_perms(self.user, self.obj)) print(f"Inactive user - get_perms: {all_perms}, get_user_perms: {user_perms}, get_group_perms: {group_perms}") # all functions should return empty for inactive users self.assertEqual(all_perms, [], "get_perms should return empty list for inactive user") self.assertEqual(user_perms, [], "get_user_perms should return empty list for inactive user") self.assertEqual(group_perms, [], "get_group_perms should return empty list for inactive user") # Now the superset relationship should hold correctly self.assertTrue( set(all_perms).issuperset(set(user_perms)), f"get_perms {all_perms} should be superset of get_user_perms {user_perms}", ) self.assertTrue( set(all_perms).issuperset(set(group_perms)), f"get_perms {all_perms} should be superset of get_group_perms {group_perms}", ) def test_superuser_behavior(self): """Test behavior with superuser.""" superuser = User.objects.create_superuser(username="superuser", email="super@example.com", password="pass") user_perms = list(get_user_perms(superuser, self.obj)) all_perms = get_perms(superuser, self.obj) # Superuser should have all permissions via get_perms # Fix: self.obj is a ContentType, so we need to get permissions for ContentType model from django.contrib.contenttypes.models import ContentType ct = ContentType.objects.get_for_model(ContentType) all_model_perms = list(Permission.objects.filter(content_type=ct).values_list("codename", flat=True)) self.assertEqual( set(all_perms), set(all_model_perms), "Superuser should have all model permissions via get_perms" ) # get_perms should be superset of get_user_perms self.assertTrue( set(all_perms).issuperset(set(user_perms)), f"get_perms {all_perms} should be superset of get_user_perms {user_perms}", ) def test_reported_issue_reproduction(self): """Reproduce the exact issue reported in the feedback.""" # Create scenario where user has permissions via group but not directly assign_perm("view_contenttype", self.group, self.obj) assign_perm("change_contenttype", self.group, self.obj) assign_perm("add_contenttype", self.group, self.obj) assign_perm("delete_contenttype", self.group, self.obj) # Simulate the user's script perms = get_perms(self.user, self.obj) user_perms = list(get_user_perms(self.user, self.obj)) # This reproduces the reported scenario self.assertGreater(len(perms), 0, "User should have permissions via group") self.assertEqual(len(user_perms), 0, "User should have no direct permissions") # The user reported: "user_perms != perms" # This is expected behavior, but let's verify the relationship if user_perms != perms: # This is the "issue" reported, but it's actually correct behavior # get_perms includes group permissions, get_user_perms does not pass # The important test: get_perms should always be superset of get_user_perms self.assertTrue( set(perms).issuperset(set(user_perms)), "get_perms should always be a superset of get_user_perms" ) # Verify that perms contains the group permissions group_perms = list(get_group_perms(self.user, self.obj)) self.assertTrue(set(group_perms).issubset(set(perms)), "get_perms should include group permissions")
GetPermsVsGetUserPermsTest
python
pypa__twine
twine/repository.py
{ "start": 1111, "end": 9020 }
class ____: def __init__( self, repository_url: str, username: Optional[str], password: Optional[str], disable_progress_bar: bool = False, ) -> None: self.url = repository_url self.session = make_requests_session() # requests.Session.auth should be Union[None, Tuple[str, str], ...] # But username or password could be None # See TODO for utils.RepositoryConfig self.session.auth = ( (username or "", password or "") if username or password else None ) logger.info(f"username: {username if username else '<empty>'}") logger.info(f"password: <{'hidden' if password else 'empty'}>") # Working around https://github.com/python/typing/issues/182 self._releases_json_data: Dict[str, Dict[str, Any]] = {} self.disable_progress_bar = disable_progress_bar def close(self) -> None: self.session.close() @staticmethod def _convert_metadata_to_list_of_tuples( data: package_file.PackageMetadata, ) -> List[Tuple[str, Any]]: # This does what ``warehouse.forklift.parse_form_metadata()`` does, in reverse. data_to_send: List[Tuple[str, Any]] = [] for key, value in data.items(): if key == "gpg_signature": assert isinstance(value, tuple) data_to_send.append((key, value)) elif key == "project_urls": assert isinstance(value, dict) for name, url in value.items(): data_to_send.append((key, f"{name}, {url}")) elif key == "keywords": assert isinstance(value, list) data_to_send.append((key, ", ".join(value))) elif isinstance(value, (list, tuple)): data_to_send.extend((key, item) for item in value) else: assert isinstance(value, str) data_to_send.append((key, value)) return data_to_send def set_certificate_authority(self, cacert: Optional[str]) -> None: if cacert: self.session.verify = cacert def set_client_certificate(self, clientcert: Optional[str]) -> None: if clientcert: self.session.cert = clientcert def register(self, package: package_file.PackageFile) -> requests.Response: print(f"Registering {package.basefilename}") metadata = package.metadata_dictionary() data_to_send = self._convert_metadata_to_list_of_tuples(metadata) data_to_send.append((":action", "submit")) data_to_send.append(("protocol_version", "1")) encoder = requests_toolbelt.MultipartEncoder(data_to_send) resp = self.session.post( self.url, data=encoder, allow_redirects=False, headers={"Content-Type": encoder.content_type}, ) # Bug 28. Try to silence a ResourceWarning by releasing the socket. resp.close() return resp def _upload(self, package: package_file.PackageFile) -> requests.Response: print(f"Uploading {package.basefilename}") metadata = package.metadata_dictionary() data_to_send = self._convert_metadata_to_list_of_tuples(metadata) data_to_send.append((":action", "file_upload")) data_to_send.append(("protocol_version", "1")) with open(package.filename, "rb") as fp: data_to_send.append( ( "content", (package.basefilename, fp, "application/octet-stream"), ) ) encoder = requests_toolbelt.MultipartEncoder(data_to_send) with rich.progress.Progress( "[progress.percentage]{task.percentage:>3.0f}%", rich.progress.BarColumn(), rich.progress.DownloadColumn(), "•", rich.progress.TimeRemainingColumn( compact=True, elapsed_when_finished=True, ), "•", rich.progress.TransferSpeedColumn(), disable=self.disable_progress_bar, ) as progress: task_id = progress.add_task("", total=encoder.len) monitor = requests_toolbelt.MultipartEncoderMonitor( encoder, lambda monitor: progress.update( task_id, completed=monitor.bytes_read, ), ) resp = self.session.post( self.url, data=monitor, allow_redirects=False, headers={"Content-Type": monitor.content_type}, ) return resp def upload( self, package: package_file.PackageFile, max_redirects: int = 5 ) -> requests.Response: number_of_redirects = 0 while number_of_redirects < max_redirects: resp = self._upload(package) if resp.status_code == requests.codes.OK: return resp if 500 <= resp.status_code < 600: number_of_redirects += 1 logger.warning( f'Received "{resp.status_code}: {resp.reason}"' "\nPackage upload appears to have failed." f" Retry {number_of_redirects} of {max_redirects}." ) else: return resp return resp def package_is_uploaded( self, package: package_file.PackageFile, bypass_cache: bool = False ) -> bool: """Determine if a package has been uploaded to PyPI already. .. warning:: This does not support indexes other than PyPI or TestPyPI :param package: The package file that will otherwise be uploaded. :type package: :class:`~twine.package.PackageFile` :param bypass_cache: Force a request to PyPI. :type bypass_cache: bool :returns: True if package has already been uploaded, False otherwise :rtype: bool """ # NOTE(sigmavirus24): Not all indices are PyPI and pypi.io doesn't # have a similar interface for finding the package versions. if not self.url.startswith((LEGACY_PYPI, WAREHOUSE, OLD_WAREHOUSE)): return False safe_name = package.safe_name releases = None if not bypass_cache: releases = self._releases_json_data.get(safe_name) if releases is None: url = f"{LEGACY_PYPI}pypi/{safe_name}/json" headers = {"Accept": "application/json"} response = self.session.get(url, headers=headers) if response.status_code == 200: releases = response.json()["releases"] else: releases = {} self._releases_json_data[safe_name] = releases packages = releases.get(package.version, []) for uploaded_package in packages: if uploaded_package["filename"] == package.basefilename: return True return False def release_urls(self, packages: List[package_file.PackageFile]) -> Set[str]: if self.url.startswith(WAREHOUSE): url = WAREHOUSE_WEB elif self.url.startswith(TEST_WAREHOUSE): url = TEST_WAREHOUSE else: return set() return { f"{url}project/{package.safe_name}/{package.version}/" for package in packages } def verify_package_integrity(self, package: package_file.PackageFile) -> None: # TODO(sigmavirus24): Add a way for users to download the package and # check its hash against what it has locally. pass
Repository
python
python-attrs__attrs
src/attr/_compat.py
{ "start": 915, "end": 2829 }
class ____: """ Extract type annotations from a callable, returning None whenever there is none. """ __slots__ = ["sig"] def __init__(self, callable): try: self.sig = inspect.signature(callable) except (ValueError, TypeError): # inspect failed self.sig = None def get_first_param_type(self): """ Return the type annotation of the first argument if it's not empty. """ if not self.sig: return None params = list(self.sig.parameters.values()) if params and params[0].annotation is not inspect.Parameter.empty: return params[0].annotation return None def get_return_type(self): """ Return the return type if it's not empty. """ if ( self.sig and self.sig.return_annotation is not inspect.Signature.empty ): return self.sig.return_annotation return None # Thread-local global to track attrs instances which are already being repr'd. # This is needed because there is no other (thread-safe) way to pass info # about the instances that are already being repr'd through the call stack # in order to ensure we don't perform infinite recursion. # # For instance, if an instance contains a dict which contains that instance, # we need to know that we're already repr'ing the outside instance from within # the dict's repr() call. # # This lives here rather than in _make.py so that the functions in _make.py # don't have a direct reference to the thread-local in their globals dict. # If they have such a reference, it breaks cloudpickle. repr_context = threading.local() def get_generic_base(cl): """If this is a generic class (A[str]), return the generic base for it.""" if cl.__class__ is _GenericAlias: return cl.__origin__ return None
_AnnotationExtractor
python
aio-libs__aiohttp
aiohttp/helpers.py
{ "start": 18455, "end": 19983 }
class ____: """Timeout handle""" __slots__ = ("_timeout", "_loop", "_ceil_threshold", "_callbacks") def __init__( self, loop: asyncio.AbstractEventLoop, timeout: float | None, ceil_threshold: float = 5, ) -> None: self._timeout = timeout self._loop = loop self._ceil_threshold = ceil_threshold self._callbacks: list[ tuple[Callable[..., None], tuple[Any, ...], dict[str, Any]] ] = [] def register( self, callback: Callable[..., None], *args: Any, **kwargs: Any ) -> None: self._callbacks.append((callback, args, kwargs)) def close(self) -> None: self._callbacks.clear() def start(self) -> asyncio.TimerHandle | None: timeout = self._timeout if timeout is not None and timeout > 0: when = self._loop.time() + timeout if timeout >= self._ceil_threshold: when = ceil(when) return self._loop.call_at(when, self.__call__) else: return None def timer(self) -> "BaseTimerContext": if self._timeout is not None and self._timeout > 0: timer = TimerContext(self._loop) self.register(timer.timeout) return timer else: return TimerNoop() def __call__(self) -> None: for cb, args, kwargs in self._callbacks: with suppress(Exception): cb(*args, **kwargs) self._callbacks.clear()
TimeoutHandle
python
redis__redis-py
redis/asyncio/connection.py
{ "start": 2417, "end": 27335 }
class ____: """Manages communication to and from a Redis server""" __slots__ = ( "db", "username", "client_name", "lib_name", "lib_version", "credential_provider", "password", "socket_timeout", "socket_connect_timeout", "redis_connect_func", "retry_on_timeout", "retry_on_error", "health_check_interval", "next_health_check", "last_active_at", "encoder", "ssl_context", "protocol", "_reader", "_writer", "_parser", "_connect_callbacks", "_buffer_cutoff", "_lock", "_socket_read_size", "__dict__", ) def __init__( self, *, db: Union[str, int] = 0, password: Optional[str] = None, socket_timeout: Optional[float] = None, socket_connect_timeout: Optional[float] = None, retry_on_timeout: bool = False, retry_on_error: Union[list, _Sentinel] = SENTINEL, encoding: str = "utf-8", encoding_errors: str = "strict", decode_responses: bool = False, parser_class: Type[BaseParser] = DefaultParser, socket_read_size: int = 65536, health_check_interval: float = 0, client_name: Optional[str] = None, lib_name: Optional[str] = "redis-py", lib_version: Optional[str] = get_lib_version(), username: Optional[str] = None, retry: Optional[Retry] = None, redis_connect_func: Optional[ConnectCallbackT] = None, encoder_class: Type[Encoder] = Encoder, credential_provider: Optional[CredentialProvider] = None, protocol: Optional[int] = 2, event_dispatcher: Optional[EventDispatcher] = None, ): if (username or password) and credential_provider is not None: raise DataError( "'username' and 'password' cannot be passed along with 'credential_" "provider'. Please provide only one of the following arguments: \n" "1. 'password' and (optional) 'username'\n" "2. 'credential_provider'" ) if event_dispatcher is None: self._event_dispatcher = EventDispatcher() else: self._event_dispatcher = event_dispatcher self.db = db self.client_name = client_name self.lib_name = lib_name self.lib_version = lib_version self.credential_provider = credential_provider self.password = password self.username = username self.socket_timeout = socket_timeout if socket_connect_timeout is None: socket_connect_timeout = socket_timeout self.socket_connect_timeout = socket_connect_timeout self.retry_on_timeout = retry_on_timeout if retry_on_error is SENTINEL: retry_on_error = [] if retry_on_timeout: retry_on_error.append(TimeoutError) retry_on_error.append(socket.timeout) retry_on_error.append(asyncio.TimeoutError) self.retry_on_error = retry_on_error if retry or retry_on_error: if not retry: self.retry = Retry(NoBackoff(), 1) else: # deep-copy the Retry object as it is mutable self.retry = copy.deepcopy(retry) # Update the retry's supported errors with the specified errors self.retry.update_supported_errors(retry_on_error) else: self.retry = Retry(NoBackoff(), 0) self.health_check_interval = health_check_interval self.next_health_check: float = -1 self.encoder = encoder_class(encoding, encoding_errors, decode_responses) self.redis_connect_func = redis_connect_func self._reader: Optional[asyncio.StreamReader] = None self._writer: Optional[asyncio.StreamWriter] = None self._socket_read_size = socket_read_size self.set_parser(parser_class) self._connect_callbacks: List[weakref.WeakMethod[ConnectCallbackT]] = [] self._buffer_cutoff = 6000 self._re_auth_token: Optional[TokenInterface] = None self._should_reconnect = False try: p = int(protocol) except TypeError: p = DEFAULT_RESP_VERSION except ValueError: raise ConnectionError("protocol must be an integer") finally: if p < 2 or p > 3: raise ConnectionError("protocol must be either 2 or 3") self.protocol = protocol def __del__(self, _warnings: Any = warnings): # For some reason, the individual streams don't get properly garbage # collected and therefore produce no resource warnings. We add one # here, in the same style as those from the stdlib. if getattr(self, "_writer", None): _warnings.warn( f"unclosed Connection {self!r}", ResourceWarning, source=self ) try: asyncio.get_running_loop() self._close() except RuntimeError: # No actions been taken if pool already closed. pass def _close(self): """ Internal method to silently close the connection without waiting """ if self._writer: self._writer.close() self._writer = self._reader = None def __repr__(self): repr_args = ",".join((f"{k}={v}" for k, v in self.repr_pieces())) return f"<{self.__class__.__module__}.{self.__class__.__name__}({repr_args})>" @abstractmethod def repr_pieces(self): pass @property def is_connected(self): return self._reader is not None and self._writer is not None def register_connect_callback(self, callback): """ Register a callback to be called when the connection is established either initially or reconnected. This allows listeners to issue commands that are ephemeral to the connection, for example pub/sub subscription or key tracking. The callback must be a _method_ and will be kept as a weak reference. """ wm = weakref.WeakMethod(callback) if wm not in self._connect_callbacks: self._connect_callbacks.append(wm) def deregister_connect_callback(self, callback): """ De-register a previously registered callback. It will no-longer receive notifications on connection events. Calling this is not required when the listener goes away, since the callbacks are kept as weak methods. """ try: self._connect_callbacks.remove(weakref.WeakMethod(callback)) except ValueError: pass def set_parser(self, parser_class: Type[BaseParser]) -> None: """ Creates a new instance of parser_class with socket size: _socket_read_size and assigns it to the parser for the connection :param parser_class: The required parser class """ self._parser = parser_class(socket_read_size=self._socket_read_size) async def connect(self): """Connects to the Redis server if not already connected""" await self.connect_check_health(check_health=True) async def connect_check_health( self, check_health: bool = True, retry_socket_connect: bool = True ): if self.is_connected: return try: if retry_socket_connect: await self.retry.call_with_retry( lambda: self._connect(), lambda error: self.disconnect() ) else: await self._connect() except asyncio.CancelledError: raise # in 3.7 and earlier, this is an Exception, not BaseException except (socket.timeout, asyncio.TimeoutError): raise TimeoutError("Timeout connecting to server") except OSError as e: raise ConnectionError(self._error_message(e)) except Exception as exc: raise ConnectionError(exc) from exc try: if not self.redis_connect_func: # Use the default on_connect function await self.on_connect_check_health(check_health=check_health) else: # Use the passed function redis_connect_func ( await self.redis_connect_func(self) if asyncio.iscoroutinefunction(self.redis_connect_func) else self.redis_connect_func(self) ) except RedisError: # clean up after any error in on_connect await self.disconnect() raise # run any user callbacks. right now the only internal callback # is for pubsub channel/pattern resubscription # first, remove any dead weakrefs self._connect_callbacks = [ref for ref in self._connect_callbacks if ref()] for ref in self._connect_callbacks: callback = ref() task = callback(self) if task and inspect.isawaitable(task): await task def mark_for_reconnect(self): self._should_reconnect = True def should_reconnect(self): return self._should_reconnect @abstractmethod async def _connect(self): pass @abstractmethod def _host_error(self) -> str: pass def _error_message(self, exception: BaseException) -> str: return format_error_message(self._host_error(), exception) def get_protocol(self): return self.protocol async def on_connect(self) -> None: """Initialize the connection, authenticate and select a database""" await self.on_connect_check_health(check_health=True) async def on_connect_check_health(self, check_health: bool = True) -> None: self._parser.on_connect(self) parser = self._parser auth_args = None # if credential provider or username and/or password are set, authenticate if self.credential_provider or (self.username or self.password): cred_provider = ( self.credential_provider or UsernamePasswordCredentialProvider(self.username, self.password) ) auth_args = await cred_provider.get_credentials_async() # if resp version is specified and we have auth args, # we need to send them via HELLO if auth_args and self.protocol not in [2, "2"]: if isinstance(self._parser, _AsyncRESP2Parser): self.set_parser(_AsyncRESP3Parser) # update cluster exception classes self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES self._parser.on_connect(self) if len(auth_args) == 1: auth_args = ["default", auth_args[0]] # avoid checking health here -- PING will fail if we try # to check the health prior to the AUTH await self.send_command( "HELLO", self.protocol, "AUTH", *auth_args, check_health=False ) response = await self.read_response() if response.get(b"proto") != int(self.protocol) and response.get( "proto" ) != int(self.protocol): raise ConnectionError("Invalid RESP version") # avoid checking health here -- PING will fail if we try # to check the health prior to the AUTH elif auth_args: await self.send_command("AUTH", *auth_args, check_health=False) try: auth_response = await self.read_response() except AuthenticationWrongNumberOfArgsError: # a username and password were specified but the Redis # server seems to be < 6.0.0 which expects a single password # arg. retry auth with just the password. # https://github.com/andymccurdy/redis-py/issues/1274 await self.send_command("AUTH", auth_args[-1], check_health=False) auth_response = await self.read_response() if str_if_bytes(auth_response) != "OK": raise AuthenticationError("Invalid Username or Password") # if resp version is specified, switch to it elif self.protocol not in [2, "2"]: if isinstance(self._parser, _AsyncRESP2Parser): self.set_parser(_AsyncRESP3Parser) # update cluster exception classes self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES self._parser.on_connect(self) await self.send_command("HELLO", self.protocol, check_health=check_health) response = await self.read_response() # if response.get(b"proto") != self.protocol and response.get( # "proto" # ) != self.protocol: # raise ConnectionError("Invalid RESP version") # if a client_name is given, set it if self.client_name: await self.send_command( "CLIENT", "SETNAME", self.client_name, check_health=check_health, ) if str_if_bytes(await self.read_response()) != "OK": raise ConnectionError("Error setting client name") # set the library name and version, pipeline for lower startup latency if self.lib_name: await self.send_command( "CLIENT", "SETINFO", "LIB-NAME", self.lib_name, check_health=check_health, ) if self.lib_version: await self.send_command( "CLIENT", "SETINFO", "LIB-VER", self.lib_version, check_health=check_health, ) # if a database is specified, switch to it. Also pipeline this if self.db: await self.send_command("SELECT", self.db, check_health=check_health) # read responses from pipeline for _ in (sent for sent in (self.lib_name, self.lib_version) if sent): try: await self.read_response() except ResponseError: pass if self.db: if str_if_bytes(await self.read_response()) != "OK": raise ConnectionError("Invalid Database") async def disconnect(self, nowait: bool = False) -> None: """Disconnects from the Redis server""" try: async with async_timeout(self.socket_connect_timeout): self._parser.on_disconnect() if not self.is_connected: return try: self._writer.close() # type: ignore[union-attr] # wait for close to finish, except when handling errors and # forcefully disconnecting. if not nowait: await self._writer.wait_closed() # type: ignore[union-attr] except OSError: pass finally: self._reader = None self._writer = None except asyncio.TimeoutError: raise TimeoutError( f"Timed out closing connection after {self.socket_connect_timeout}" ) from None async def _send_ping(self): """Send PING, expect PONG in return""" await self.send_command("PING", check_health=False) if str_if_bytes(await self.read_response()) != "PONG": raise ConnectionError("Bad response from PING health check") async def _ping_failed(self, error): """Function to call when PING fails""" await self.disconnect() async def check_health(self): """Check the health of the connection with a PING/PONG""" if ( self.health_check_interval and asyncio.get_running_loop().time() > self.next_health_check ): await self.retry.call_with_retry(self._send_ping, self._ping_failed) async def _send_packed_command(self, command: Iterable[bytes]) -> None: self._writer.writelines(command) await self._writer.drain() async def send_packed_command( self, command: Union[bytes, str, Iterable[bytes]], check_health: bool = True ) -> None: if not self.is_connected: await self.connect_check_health(check_health=False) if check_health: await self.check_health() try: if isinstance(command, str): command = command.encode() if isinstance(command, bytes): command = [command] if self.socket_timeout: await asyncio.wait_for( self._send_packed_command(command), self.socket_timeout ) else: self._writer.writelines(command) await self._writer.drain() except asyncio.TimeoutError: await self.disconnect(nowait=True) raise TimeoutError("Timeout writing to socket") from None except OSError as e: await self.disconnect(nowait=True) if len(e.args) == 1: err_no, errmsg = "UNKNOWN", e.args[0] else: err_no = e.args[0] errmsg = e.args[1] raise ConnectionError( f"Error {err_no} while writing to socket. {errmsg}." ) from e except BaseException: # BaseExceptions can be raised when a socket send operation is not # finished, e.g. due to a timeout. Ideally, a caller could then re-try # to send un-sent data. However, the send_packed_command() API # does not support it so there is no point in keeping the connection open. await self.disconnect(nowait=True) raise async def send_command(self, *args: Any, **kwargs: Any) -> None: """Pack and send a command to the Redis server""" await self.send_packed_command( self.pack_command(*args), check_health=kwargs.get("check_health", True) ) async def can_read_destructive(self): """Poll the socket to see if there's data that can be read.""" try: return await self._parser.can_read_destructive() except OSError as e: await self.disconnect(nowait=True) host_error = self._host_error() raise ConnectionError(f"Error while reading from {host_error}: {e.args}") async def read_response( self, disable_decoding: bool = False, timeout: Optional[float] = None, *, disconnect_on_error: bool = True, push_request: Optional[bool] = False, ): """Read the response from a previously sent command""" read_timeout = timeout if timeout is not None else self.socket_timeout host_error = self._host_error() try: if read_timeout is not None and self.protocol in ["3", 3]: async with async_timeout(read_timeout): response = await self._parser.read_response( disable_decoding=disable_decoding, push_request=push_request ) elif read_timeout is not None: async with async_timeout(read_timeout): response = await self._parser.read_response( disable_decoding=disable_decoding ) elif self.protocol in ["3", 3]: response = await self._parser.read_response( disable_decoding=disable_decoding, push_request=push_request ) else: response = await self._parser.read_response( disable_decoding=disable_decoding ) except asyncio.TimeoutError: if timeout is not None: # user requested timeout, return None. Operation can be retried return None # it was a self.socket_timeout error. if disconnect_on_error: await self.disconnect(nowait=True) raise TimeoutError(f"Timeout reading from {host_error}") except OSError as e: if disconnect_on_error: await self.disconnect(nowait=True) raise ConnectionError(f"Error while reading from {host_error} : {e.args}") except BaseException: # Also by default close in case of BaseException. A lot of code # relies on this behaviour when doing Command/Response pairs. # See #1128. if disconnect_on_error: await self.disconnect(nowait=True) raise if self.health_check_interval: next_time = asyncio.get_running_loop().time() + self.health_check_interval self.next_health_check = next_time if isinstance(response, ResponseError): raise response from None return response def pack_command(self, *args: EncodableT) -> List[bytes]: """Pack a series of arguments into the Redis protocol""" output = [] # the client might have included 1 or more literal arguments in # the command name, e.g., 'CONFIG GET'. The Redis server expects these # arguments to be sent separately, so split the first argument # manually. These arguments should be bytestrings so that they are # not encoded. assert not isinstance(args[0], float) if isinstance(args[0], str): args = tuple(args[0].encode().split()) + args[1:] elif b" " in args[0]: args = tuple(args[0].split()) + args[1:] buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF)) buffer_cutoff = self._buffer_cutoff for arg in map(self.encoder.encode, args): # to avoid large string mallocs, chunk the command into the # output list if we're sending large values or memoryviews arg_length = len(arg) if ( len(buff) > buffer_cutoff or arg_length > buffer_cutoff or isinstance(arg, memoryview) ): buff = SYM_EMPTY.join( (buff, SYM_DOLLAR, str(arg_length).encode(), SYM_CRLF) ) output.append(buff) output.append(arg) buff = SYM_CRLF else: buff = SYM_EMPTY.join( ( buff, SYM_DOLLAR, str(arg_length).encode(), SYM_CRLF, arg, SYM_CRLF, ) ) output.append(buff) return output def pack_commands(self, commands: Iterable[Iterable[EncodableT]]) -> List[bytes]: """Pack multiple commands into the Redis protocol""" output: List[bytes] = [] pieces: List[bytes] = [] buffer_length = 0 buffer_cutoff = self._buffer_cutoff for cmd in commands: for chunk in self.pack_command(*cmd): chunklen = len(chunk) if ( buffer_length > buffer_cutoff or chunklen > buffer_cutoff or isinstance(chunk, memoryview) ): if pieces: output.append(SYM_EMPTY.join(pieces)) buffer_length = 0 pieces = [] if chunklen > buffer_cutoff or isinstance(chunk, memoryview): output.append(chunk) else: pieces.append(chunk) buffer_length += chunklen if pieces: output.append(SYM_EMPTY.join(pieces)) return output def _socket_is_empty(self): """Check if the socket is empty""" return len(self._reader._buffer) == 0 async def process_invalidation_messages(self): while not self._socket_is_empty(): await self.read_response(push_request=True) def set_re_auth_token(self, token: TokenInterface): self._re_auth_token = token async def re_auth(self): if self._re_auth_token is not None: await self.send_command( "AUTH", self._re_auth_token.try_get("oid"), self._re_auth_token.get_value(), ) await self.read_response() self._re_auth_token = None
AbstractConnection
python
keras-team__keras
keras/src/ops/image.py
{ "start": 25505, "end": 31612 }
class ____(Operation): def __init__( self, size, strides=None, dilation_rate=1, padding="valid", data_format=None, *, name=None, ): super().__init__(name=name) if isinstance(size, int): size = (size, size, size) elif len(size) != 3: raise TypeError( "Invalid `size` argument. Expected an " f"int or a tuple of length 3. Received: size={size}" ) self.size = size if strides is not None: if isinstance(strides, int): strides = (strides, strides, strides) elif len(strides) != 3: raise ValueError(f"Invalid `strides` argument. Got: {strides}") else: strides = size self.strides = strides self.dilation_rate = dilation_rate self.padding = padding self.data_format = backend.standardize_data_format(data_format) def call(self, volumes): return _extract_patches_3d( volumes, self.size, self.strides, self.dilation_rate, self.padding, self.data_format, ) def compute_output_spec(self, volumes): volumes_shape = list(volumes.shape) original_ndim = len(volumes_shape) strides = self.strides if self.data_format == "channels_last": channels_in = volumes_shape[-1] else: channels_in = volumes_shape[-4] if original_ndim == 4: volumes_shape = [1] + volumes_shape filters = self.size[0] * self.size[1] * self.size[2] * channels_in kernel_size = (self.size[0], self.size[1], self.size[2]) out_shape = compute_conv_output_shape( volumes_shape, filters, kernel_size, strides=strides, padding=self.padding, data_format=self.data_format, dilation_rate=self.dilation_rate, ) if original_ndim == 4: out_shape = out_shape[1:] return KerasTensor(shape=out_shape, dtype=volumes.dtype) def _extract_patches_3d( volumes, size, strides=None, dilation_rate=1, padding="valid", data_format=None, ): if isinstance(size, int): patch_d = patch_h = patch_w = size elif len(size) == 3: patch_d, patch_h, patch_w = size else: raise TypeError( "Invalid `size` argument. Expected an " f"int or a tuple of length 3. Received: size={size}" ) if strides is None: strides = size if isinstance(strides, int): strides = (strides, strides, strides) if len(strides) != 3: raise ValueError(f"Invalid `strides` argument. Got: {strides}") data_format = backend.standardize_data_format(data_format) if data_format == "channels_last": channels_in = volumes.shape[-1] elif data_format == "channels_first": channels_in = volumes.shape[-4] out_dim = patch_d * patch_w * patch_h * channels_in kernel = backend.numpy.eye(out_dim, dtype=volumes.dtype) kernel = backend.numpy.reshape( kernel, (patch_d, patch_h, patch_w, channels_in, out_dim) ) _unbatched = False if len(volumes.shape) == 4: _unbatched = True volumes = backend.numpy.expand_dims(volumes, axis=0) patches = backend.nn.conv( inputs=volumes, kernel=kernel, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate, ) if _unbatched: patches = backend.numpy.squeeze(patches, axis=0) return patches @keras_export("keras.ops.image.extract_patches_3d") def extract_patches_3d( volumes, size, strides=None, dilation_rate=1, padding="valid", data_format=None, ): """Extracts patches from the volume(s). Args: volumes: Input volume or batch of volumes. Must be 4D or 5D. size: Patch size int or tuple (patch_depth, patch_height, patch_width) strides: strides along depth, height, and width. If not specified, or if `None`, it defaults to the same value as `size`. dilation_rate: This is the input stride, specifying how far two consecutive patch samples are in the input. Note that using `dilation_rate > 1` is not supported in conjunction with `strides > 1` on the TensorFlow backend. padding: The type of padding algorithm to use: `"same"` or `"valid"`. data_format: A string specifying the data format of the input tensor. It can be either `"channels_last"` or `"channels_first"`. `"channels_last"` corresponds to inputs with shape `(batch, depth, height, width, channels)`, while `"channels_first"` corresponds to inputs with shape `(batch, channels, depth, height, width)`. If not specified, the value will default to `keras.config.image_data_format()`. Returns: Extracted patches 4D (if not batched) or 5D (if batched) Examples: >>> import numpy as np >>> import keras >>> # Batched case >>> volumes = np.random.random( ... (2, 10, 10, 10, 3) ... ).astype("float32") # batch of 2 volumes >>> patches = keras.ops.image.extract_patches_3d(volumes, (3, 3, 3)) >>> patches.shape (2, 3, 3, 3, 81) >>> # Unbatched case >>> volume = np.random.random((10, 10, 10, 3)).astype("float32") # 1 volume >>> patches = keras.ops.image.extract_patches_3d(volume, (3, 3, 3)) >>> patches.shape (3, 3, 3, 81) """ if any_symbolic_tensors((volumes,)): return ExtractPatches3D( size=size, strides=strides, dilation_rate=dilation_rate, padding=padding, data_format=data_format, ).symbolic_call(volumes) return _extract_patches_3d( volumes, size, strides, dilation_rate, padding, data_format=data_format )
ExtractPatches3D
python
scrapy__scrapy
tests/CrawlerProcess/asyncio_enabled_no_reactor.py
{ "start": 308, "end": 662 }
class ____(scrapy.Spider): name = "no_request" async def start(self): return yield process = CrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", "EXTENSIONS": {ReactorCheckExtension: 0}, } ) process.crawl(NoRequestsSpider) process.start()
NoRequestsSpider
python
sqlalchemy__sqlalchemy
test/orm/dml/test_orm_upd_del_inheritance.py
{ "start": 12523, "end": 14102 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" @testing.fixture def inherit_fixture(self, decl_base): def go(poly_type): class Person(decl_base): __tablename__ = "person" id = Column(Integer, primary_key=True) type = Column(String(50)) name = Column(String(50)) if poly_type.wpoly: __mapper_args__ = {"with_polymorphic": "*"} class Engineer(Person): __tablename__ = "engineer" id = Column(Integer, ForeignKey("person.id"), primary_key=True) engineer_name = Column(String(50)) if poly_type.inline: __mapper_args__ = {"polymorphic_load": "inline"} return Person, Engineer return go @testing.variation("poly_type", ["wpoly", "inline", "none"]) def test_update_base_only(self, poly_type, inherit_fixture): Person, Engineer = inherit_fixture(poly_type) self.assert_compile( update(Person).values(name="n1"), "UPDATE person SET name=:name" ) @testing.variation("poly_type", ["wpoly", "inline", "none"]) def test_delete_base_only(self, poly_type, inherit_fixture): Person, Engineer = inherit_fixture(poly_type) self.assert_compile(delete(Person), "DELETE FROM person") self.assert_compile( delete(Person).where(Person.id == 7), "DELETE FROM person WHERE person.id = :id_1", )
InheritWPolyTest
python
walkccc__LeetCode
solutions/3179. Find the N-th Value After K Seconds/3179.py
{ "start": 0, "end": 126 }
class ____: def valueAfterKSeconds(self, n: int, k: int) -> int: return math.comb(n + k - 1, n - 1) % 1_000_000_007
Solution
python
celery__celery
celery/backends/mongodb.py
{ "start": 830, "end": 11465 }
class ____(BaseBackend): """MongoDB result backend. Raises: celery.exceptions.ImproperlyConfigured: if module :pypi:`pymongo` is not available. """ mongo_host = None host = 'localhost' port = 27017 user = None password = None database_name = 'celery' taskmeta_collection = 'celery_taskmeta' groupmeta_collection = 'celery_groupmeta' max_pool_size = 10 options = None supports_autoexpire = False _connection = None def __init__(self, app=None, **kwargs): self.options = {} super().__init__(app, **kwargs) if not pymongo: raise ImproperlyConfigured( 'You need to install the pymongo library to use the ' 'MongoDB backend.') # Set option defaults for key, value in self._prepare_client_options().items(): self.options.setdefault(key, value) # update conf with mongo uri data, only if uri was given if self.url: self.url = self._ensure_mongodb_uri_compliance(self.url) uri_data = uri_parser.parse_uri(self.url) # build the hosts list to create a mongo connection hostslist = [ f'{x[0]}:{x[1]}' for x in uri_data['nodelist'] ] self.user = uri_data['username'] self.password = uri_data['password'] self.mongo_host = hostslist if uri_data['database']: # if no database is provided in the uri, use default self.database_name = uri_data['database'] self.options.update(uri_data['options']) # update conf with specific settings config = self.app.conf.get('mongodb_backend_settings') if config is not None: if not isinstance(config, dict): raise ImproperlyConfigured( 'MongoDB backend settings should be grouped in a dict') config = dict(config) # don't modify original if 'host' in config or 'port' in config: # these should take over uri conf self.mongo_host = None self.host = config.pop('host', self.host) self.port = config.pop('port', self.port) self.mongo_host = config.pop('mongo_host', self.mongo_host) self.user = config.pop('user', self.user) self.password = config.pop('password', self.password) self.database_name = config.pop('database', self.database_name) self.taskmeta_collection = config.pop( 'taskmeta_collection', self.taskmeta_collection, ) self.groupmeta_collection = config.pop( 'groupmeta_collection', self.groupmeta_collection, ) self.options.update(config.pop('options', {})) self.options.update(config) @staticmethod def _ensure_mongodb_uri_compliance(url): parsed_url = urlparse(url) if not parsed_url.scheme.startswith('mongodb'): url = f'mongodb+{url}' if url == 'mongodb://': url += 'localhost' return url def _prepare_client_options(self): if pymongo.version_tuple >= (3,): return {'maxPoolSize': self.max_pool_size} else: # pragma: no cover return {'max_pool_size': self.max_pool_size, 'auto_start_request': False} def _get_connection(self): """Connect to the MongoDB server.""" if self._connection is None: from pymongo import MongoClient host = self.mongo_host if not host: # The first pymongo.Connection() argument (host) can be # a list of ['host:port'] elements or a mongodb connection # URI. If this is the case, don't use self.port # but let pymongo get the port(s) from the URI instead. # This enables the use of replica sets and sharding. # See pymongo.Connection() for more info. host = self.host if isinstance(host, str) \ and not host.startswith('mongodb://'): host = f'mongodb://{host}:{self.port}' # don't change self.options conf = dict(self.options) conf['host'] = host if self.user: conf['username'] = self.user if self.password: conf['password'] = self.password self._connection = MongoClient(**conf) return self._connection def encode(self, data): if self.serializer == 'bson': # mongodb handles serialization return data payload = super().encode(data) # serializer which are in a unsupported format (pickle/binary) if self.serializer in BINARY_CODECS: payload = Binary(payload) return payload def decode(self, data): if self.serializer == 'bson': return data return super().decode(data) def _store_result(self, task_id, result, state, traceback=None, request=None, **kwargs): """Store return value and state of an executed task.""" meta = self._get_result_meta(result=self.encode(result), state=state, traceback=traceback, request=request, format_date=False) # Add the _id for mongodb meta['_id'] = task_id try: self.collection.replace_one({'_id': task_id}, meta, upsert=True) except InvalidDocument as exc: raise EncodeError(exc) return result def _get_task_meta_for(self, task_id): """Get task meta-data for a task by id.""" obj = self.collection.find_one({'_id': task_id}) if obj: if self.app.conf.find_value_for_key('extended', 'result'): return self.meta_from_decoded({ 'name': obj['name'], 'args': obj['args'], 'task_id': obj['_id'], 'queue': obj['queue'], 'kwargs': obj['kwargs'], 'status': obj['status'], 'worker': obj['worker'], 'retries': obj['retries'], 'children': obj['children'], 'date_done': obj['date_done'], 'traceback': obj['traceback'], 'result': self.decode(obj['result']), }) return self.meta_from_decoded({ 'task_id': obj['_id'], 'status': obj['status'], 'result': self.decode(obj['result']), 'date_done': obj['date_done'], 'traceback': obj['traceback'], 'children': obj['children'], }) return {'status': states.PENDING, 'result': None} def _save_group(self, group_id, result): """Save the group result.""" meta = { '_id': group_id, 'result': self.encode([i.id for i in result]), 'date_done': datetime.now(timezone.utc), } self.group_collection.replace_one({'_id': group_id}, meta, upsert=True) return result def _restore_group(self, group_id): """Get the result for a group by id.""" obj = self.group_collection.find_one({'_id': group_id}) if obj: return { 'task_id': obj['_id'], 'date_done': obj['date_done'], 'result': [ self.app.AsyncResult(task) for task in self.decode(obj['result']) ], } def _delete_group(self, group_id): """Delete a group by id.""" self.group_collection.delete_one({'_id': group_id}) def _forget(self, task_id): """Remove result from MongoDB. Raises: pymongo.exceptions.OperationsError: if the task_id could not be removed. """ # By using safe=True, this will wait until it receives a response from # the server. Likewise, it will raise an OperationsError if the # response was unable to be completed. self.collection.delete_one({'_id': task_id}) def cleanup(self): """Delete expired meta-data.""" if not self.expires: return self.collection.delete_many( {'date_done': {'$lt': self.app.now() - self.expires_delta}}, ) self.group_collection.delete_many( {'date_done': {'$lt': self.app.now() - self.expires_delta}}, ) def __reduce__(self, args=(), kwargs=None): kwargs = {} if not kwargs else kwargs return super().__reduce__( args, dict(kwargs, expires=self.expires, url=self.url)) def _get_database(self): conn = self._get_connection() return conn[self.database_name] @cached_property def database(self): """Get database from MongoDB connection. performs authentication if necessary. """ return self._get_database() @cached_property def collection(self): """Get the meta-data task collection.""" collection = self.database[self.taskmeta_collection] # Ensure an index on date_done is there, if not process the index # in the background. Once completed cleanup will be much faster collection.create_index('date_done', background=True) return collection @cached_property def group_collection(self): """Get the meta-data task collection.""" collection = self.database[self.groupmeta_collection] # Ensure an index on date_done is there, if not process the index # in the background. Once completed cleanup will be much faster collection.create_index('date_done', background=True) return collection @cached_property def expires_delta(self): return timedelta(seconds=self.expires) def as_uri(self, include_password=False): """Return the backend as an URI. Arguments: include_password (bool): Password censored if disabled. """ if not self.url: return 'mongodb://' if include_password: return self.url if ',' not in self.url: return maybe_sanitize_url(self.url) uri1, remainder = self.url.split(',', 1) return ','.join([maybe_sanitize_url(uri1), remainder])
MongoBackend
python
pytransitions__transitions
transitions/extensions/diagrams.py
{ "start": 12508, "end": 12698 }
class ____(GraphMachine, HierarchicalMarkupMachine): """ A hierarchical state machine with graph support. """ transition_cls = NestedGraphTransition
HierarchicalGraphMachine