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
getsentry__sentry
src/sentry/utils/snuba.py
{ "start": 30629, "end": 36421 }
class ____: """ Represents the information needed to make a query to Snuba. `start` and `end`: The beginning and end of the query time window (required) `groupby`: A list of column names to group by. `conditions`: A list of (column, operator, literal) conditions to be passed to the query. Conditions that we know will not have to be translated should be passed this way (eg tag[foo] = bar). `filter_keys`: A dictionary of {col: [key, ...]} that will be converted into "col IN (key, ...)" conditions. These are used to restrict the query to known sets of project/issue/environment/release etc. Appropriate translations (eg. from environment model ID to environment name) are performed on the query, and the inverse translation performed on the result. The project_id(s) to restrict the query to will also be automatically inferred from these keys. `aggregations` a list of (aggregation_function, column, alias) tuples to be passed to the query. The rest of the args are passed directly into the query JSON unmodified. See the snuba schema for details. """ def __init__( self, dataset=None, start: datetime | None = None, end: datetime | None = None, groupby=None, conditions=None, filter_keys=None, aggregations=None, rollup=None, referrer=None, is_grouprelease=False, **kwargs, ): # TODO: instead of having events be the default, make dataset required. self.dataset = dataset or Dataset.Events self.start = start or datetime( 2008, 5, 8 ) # Date of sentry's first commit. Will be clamped to project retention # Snuba has end exclusive but our UI wants it generally to be inclusive. # This shows up in unittests: https://github.com/getsentry/sentry/pull/15939 # We generally however require that the API user is aware of the exclusive # end. self.end = end or datetime.utcnow() + timedelta(seconds=1) self.groupby = groupby or [] self.conditions = conditions or [] self.aggregations = aggregations or [] self.filter_keys = filter_keys or {} self.rollup = rollup self.referrer = referrer self.is_grouprelease = is_grouprelease self.kwargs = kwargs # Groups can be merged together, but snuba is immutable(ish). In order to # account for merges, here we expand queries to include all group IDs that have # been merged together. if self.dataset in { Dataset.Events, Dataset.IssuePlatform, }: self._preprocess_group_id_redirects() def _preprocess_group_id_redirects(self): # Conditions are a series of "AND" statements. For "group_id", to dedupe, # we pre-collapse these. This helps us reduce the size of queries. in_groups = None out_groups: set[int | str] = set() if "group_id" in self.filter_keys: self.filter_keys = self.filter_keys.copy() in_groups = get_all_merged_group_ids(self.filter_keys["group_id"]) del self.filter_keys["group_id"] new_conditions = [] for triple in self.conditions: if triple[0] != "group_id": new_conditions.append(triple) continue op = triple[1] # IN statements need to intersect if op == "IN": new_in_groups = get_all_merged_group_ids(triple[2]) if in_groups is not None: new_in_groups = in_groups.intersection(new_in_groups) in_groups = new_in_groups elif op == "=": new_in_groups = get_all_merged_group_ids([triple[2]]) if in_groups is not None: new_in_groups = in_groups.intersection(new_in_groups) in_groups = new_in_groups # NOT IN statements can union and be differenced at the end elif op == "NOT IN": out_groups.update(triple[2]) elif op == "!=": out_groups.add(triple[2]) out_groups = get_all_merged_group_ids(list(out_groups)) triple = None # If there is an "IN" statement, we don't need a "NOT IN" statement. We can # just subtract the NOT IN groups from the IN groups. if in_groups is not None: in_groups.difference_update(out_groups) triple = ["group_id", "IN", in_groups] elif len(out_groups) > 0: triple = ["group_id", "NOT IN", out_groups] if triple is not None: new_conditions.append(triple) self.conditions = new_conditions def raw_query( dataset=None, start=None, end=None, groupby=None, conditions=None, filter_keys=None, aggregations=None, rollup=None, referrer=None, is_grouprelease=False, use_cache=False, **kwargs, ) -> Mapping[str, Any]: """ Sends a query to snuba. See `SnubaQueryParams` docstring for param descriptions. """ if referrer: kwargs["tenant_ids"] = kwargs.get("tenant_ids") or dict() kwargs["tenant_ids"]["referrer"] = referrer snuba_params = SnubaQueryParams( dataset=dataset, start=start, end=end, groupby=groupby, conditions=conditions, filter_keys=filter_keys, aggregations=aggregations, rollup=rollup, is_grouprelease=is_grouprelease, **kwargs, ) return bulk_raw_query([snuba_params], referrer=referrer, use_cache=use_cache)[0] Translator = Callable[[Any], Any] @dataclasses.dataclass(frozen=True)
SnubaQueryParams
python
great-expectations__great_expectations
great_expectations/core/freshness_diagnostics.py
{ "start": 1767, "end": 1854 }
class ____(FreshnessDiagnostics): pass @dataclass
BatchDefinitionFreshnessDiagnostics
python
getsentry__sentry
tests/sentry/issues/test_ingest.py
{ "start": 40512, "end": 42268 }
class ____(OccurrenceTestMixin, TestCase): def test(self) -> None: create_default_projects() event_data = load_data("generic-event-profiling") project_id = event_data["event"].pop("project_id") event_data["event"]["timestamp"] = timezone.now().isoformat() event = self.store_event(data=event_data["event"], project_id=project_id) occurrence = self.build_occurrence(event_id=event.event_id) group_info = save_issue_from_occurrence(occurrence, event, None) assert group_info is not None group_event = event.for_group(group_info.group) with ( mock.patch("sentry.issues.ingest.eventstream") as eventstream, mock.patch.object(event, "for_group", return_value=group_event), ): send_issue_occurrence_to_eventstream(event, occurrence, group_info) eventstream.backend.insert.assert_called_once_with( event=group_event, is_new=group_info.is_new, is_regression=group_info.is_regression, is_new_group_environment=group_info.is_new_group_environment, primary_hash=occurrence.fingerprint[0], received_timestamp=group_event.data.get("received") or group_event.datetime.timestamp(), skip_consume=False, group_states=[ { "id": group_info.group.id, "is_new": group_info.is_new, "is_regression": group_info.is_regression, "is_new_group_environment": group_info.is_new_group_environment, } ], )
SaveIssueOccurrenceToEventstreamTest
python
sympy__sympy
sympy/assumptions/handlers/common.py
{ "start": 560, "end": 1063 }
class ____: """Base class that all Ask Handlers must inherit.""" def __new__(cls, *args, **kwargs): sympy_deprecation_warning( """ The AskHandler system is deprecated. The AskHandler class should be replaced with the multipledispatch handler of Predicate """, deprecated_since_version="1.8", active_deprecations_target='deprecated-askhandler', ) return super().__new__(cls, *args, **kwargs)
AskHandler
python
Pylons__pyramid
src/pyramid/testing.py
{ "start": 4640, "end": 7938 }
class ____: """A dummy :app:`Pyramid` :term:`resource` object.""" def __init__( self, __name__=None, __parent__=None, __provides__=None, **kw ): """The resource's ``__name__`` attribute will be set to the value of the ``__name__`` argument, and the resource's ``__parent__`` attribute will be set to the value of the ``__parent__`` argument. If ``__provides__`` is specified, it should be an interface object or tuple of interface objects that will be attached to the resulting resource via :func:`zope.interface.alsoProvides`. Any extra keywords passed in the ``kw`` argument will be set as direct attributes of the resource object. .. note:: For backwards compatibility purposes, this class can also be imported as :class:`pyramid.testing.DummyModel`. """ self.__name__ = __name__ self.__parent__ = __parent__ if __provides__ is not None: alsoProvides(self, __provides__) self.kw = kw self.__dict__.update(**kw) self.subs = {} def __setitem__(self, name, val): """When the ``__setitem__`` method is called, the object passed in as ``val`` will be decorated with a ``__parent__`` attribute pointing at the dummy resource and a ``__name__`` attribute that is the value of ``name``. The value will then be returned when dummy resource's ``__getitem__`` is called with the name ``name```.""" val.__name__ = name val.__parent__ = self self.subs[name] = val def __getitem__(self, name): """Return a named subobject (see ``__setitem__``)""" ob = self.subs[name] return ob def __delitem__(self, name): del self.subs[name] def get(self, name, default=None): return self.subs.get(name, default) def values(self): """Return the values set by __setitem__""" return self.subs.values() def items(self): """Return the items set by __setitem__""" return self.subs.items() def keys(self): """Return the keys set by __setitem__""" return self.subs.keys() __iter__ = keys def __bool__(self): return True def __len__(self): return len(self.subs) def __contains__(self, name): return name in self.subs def clone(self, __name__=_marker, __parent__=_marker, **kw): """Create a clone of the resource object. If ``__name__`` or ``__parent__`` arguments are passed, use these values to override the existing ``__name__`` or ``__parent__`` of the resource. If any extra keyword args are passed in via the ``kw`` argument, use these keywords to add to or override existing resource keywords (attributes).""" oldkw = self.kw.copy() oldkw.update(kw) inst = self.__class__(self.__name__, self.__parent__, **oldkw) inst.subs = copy.deepcopy(self.subs) if __name__ is not _marker: inst.__name__ = __name__ if __parent__ is not _marker: inst.__parent__ = __parent__ return inst DummyModel = DummyResource # b/w compat (forever) @implementer(ISession)
DummyResource
python
kamyu104__LeetCode-Solutions
Python/find-array-given-subset-sums.py
{ "start": 1281, "end": 2575 }
class ____(object): def recoverArray(self, n, sums): """ :type n: int :type sums: List[int] :rtype: List[int] """ sums.sort() # Time: O(2^n * log(2^n)) = O(n * 2^n) shift, l = 0, len(sums) result = [] for _ in xrange(n): # log(2^n) times, each time costs O(2^(n-len(result))), Total Time: O(2^n) new_shift = sums[0]-sums[1] assert(new_shift <= 0) has_zero, j, k = False, 0, 0 for i in xrange(l): if k < j and sums[k] == sums[i]: # skip shifted one k += 1 else: if shift == sums[i]-new_shift: has_zero = True sums[j] = sums[i]-new_shift j += 1 if has_zero: # contain 0, choose this side result.append(new_shift) else: # contain no 0, choose another side and shift 0 offset result.append(-new_shift) shift -= new_shift l //= 2 return result # Time: O(2^n + n * r), len(sums) = 2^n # , r = max(sums)-min(sums) # Space: O(2^n + r) import collections # optimized from solution4 (not using dict), runtime: 968 ms
Solution
python
networkx__networkx
networkx/algorithms/isomorphism/tests/test_vf2userfunc.py
{ "start": 2240, "end": 3850 }
class ____: def setup_method(self): self.g1 = nx.Graph() self.g2 = nx.Graph() self.build() def build(self): self.nm = iso.categorical_node_match("color", "") self.em = iso.numerical_edge_match("weight", 1) self.g1.add_node("A", color="red") self.g2.add_node("C", color="blue") self.g1.add_edge("A", "B", weight=1) self.g2.add_edge("C", "D", weight=1) def test_noweight_nocolor(self): assert nx.is_isomorphic(self.g1, self.g2) def test_color1(self): assert not nx.is_isomorphic(self.g1, self.g2, node_match=self.nm) def test_color2(self): self.g1.nodes["A"]["color"] = "blue" assert nx.is_isomorphic(self.g1, self.g2, node_match=self.nm) def test_weight1(self): assert nx.is_isomorphic(self.g1, self.g2, edge_match=self.em) def test_weight2(self): self.g1.add_edge("A", "B", weight=2) assert not nx.is_isomorphic(self.g1, self.g2, edge_match=self.em) def test_colorsandweights1(self): iso = nx.is_isomorphic(self.g1, self.g2, node_match=self.nm, edge_match=self.em) assert not iso def test_colorsandweights2(self): self.g1.nodes["A"]["color"] = "blue" iso = nx.is_isomorphic(self.g1, self.g2, node_match=self.nm, edge_match=self.em) assert iso def test_colorsandweights3(self): # make the weights disagree self.g1.add_edge("A", "B", weight=2) assert not nx.is_isomorphic( self.g1, self.g2, node_match=self.nm, edge_match=self.em )
TestNodeMatch_Graph
python
plotly__plotly.py
tests/test_core/test_graph_objs/test_layout_subplots.py
{ "start": 102, "end": 9312 }
class ____(TestCase): def setUp(self): # Construct initial scatter object self.layout = go.Layout() pio.templates.default = None def tearDown(self): pio.templates.default = "plotly" def test_initial_access_subplots(self): # It should be possible to access base subplots initially self.assertEqual(self.layout.xaxis, go.layout.XAxis()) self.assertEqual(self.layout.yaxis, go.layout.YAxis()) self.assertEqual(self.layout["geo"], go.layout.Geo()) self.assertEqual(self.layout.scene, go.layout.Scene()) self.assertEqual(self.layout.mapbox, go.layout.Mapbox()) self.assertEqual(self.layout.polar, go.layout.Polar()) # Subplot ids of 1 should be mapped to the same object as the base # subplot. Notice we're using assertIs not assertEqual here self.assertIs(self.layout.xaxis, self.layout.xaxis1) self.assertIs(self.layout.yaxis, self.layout.yaxis1) self.assertIs(self.layout.geo, self.layout.geo1) self.assertIs(self.layout.scene, self.layout.scene1) self.assertIs(self.layout.mapbox, self.layout.mapbox1) self.assertIs(self.layout.polar, self.layout.polar1) def test_initial_access_subplot2_1(self): with pytest.raises(AttributeError): self.layout.xaxis2 def test_initial_access_subplot2_2(self): with pytest.raises(KeyError): self.layout["xaxis2"] def test_assign_subplots(self): self.assertIsNone(self.layout.xaxis.title.text) self.assertIsNone(self.layout.xaxis1.title.text) title_str = "xaxis title" self.layout.xaxis.title.text = title_str self.assertEqual(self.layout.xaxis.title.text, title_str) self.assertEqual(self.layout.xaxis1.title.text, title_str) def test_assign_subplot2(self): # Init xaxis2 self.layout.xaxis2 = go.layout.XAxis() # Properties are initially None self.assertIsNone(self.layout.xaxis2.range) # Set range xrange = [0, 1] self.layout.xaxis2.range = [0, 1] self.assertEqual(self.layout.xaxis2.range, tuple(xrange)) # Make sure range isn't shared with xaxis, or xaxis1 self.assertIsNone(self.layout.xaxis.range) self.assertIsNone(self.layout.xaxis1.range) def test_contains(self): # Initially xaxis and xaxis1 are `in` layout, but xaxis2 and 3 are not self.assertTrue("xaxis" in self.layout) self.assertTrue("xaxis1" in self.layout) self.assertFalse("xaxis2" in self.layout) self.assertFalse("xaxis3" in self.layout) # xaxis is in iter props, but xaxis1, 2, and 3 are not iter_props = list(self.layout) self.assertIn("xaxis", iter_props) self.assertNotIn("xaxis1", iter_props) self.assertNotIn("xaxis2", iter_props) self.assertNotIn("xaxis3", iter_props) # test dir props (these drive ipython tab completion) dir_props = self.layout.__dir__() self.assertIn("xaxis", dir_props) self.assertNotIn("xaxis1", dir_props) self.assertNotIn("xaxis2", dir_props) self.assertNotIn("xaxis3", dir_props) # Initialize xaxis2 self.layout.xaxis2 = {} self.assertTrue("xaxis" in self.layout) self.assertTrue("xaxis1" in self.layout) self.assertTrue("xaxis2" in self.layout) self.assertFalse("xaxis3" in self.layout) # xaxis and xaxis2 are in iter props iter_props = list(self.layout) self.assertIn("xaxis", iter_props) self.assertNotIn("xaxis1", iter_props) self.assertIn("xaxis2", iter_props) self.assertNotIn("xaxis3", iter_props) # test dir props dir_props = self.layout.__dir__() self.assertIn("xaxis", dir_props) self.assertNotIn("xaxis1", dir_props) self.assertIn("xaxis2", dir_props) self.assertNotIn("xaxis3", dir_props) # Initialize xaxis3 self.layout["xaxis3"] = {} self.assertTrue("xaxis" in self.layout) self.assertTrue("xaxis1" in self.layout) self.assertTrue("xaxis2" in self.layout) self.assertTrue("xaxis3" in self.layout) # xaxis, xaxis2, and xaxis3 are in iter props iter_props = list(self.layout) self.assertIn("xaxis", iter_props) self.assertNotIn("xaxis1", iter_props) self.assertIn("xaxis2", iter_props) self.assertIn("xaxis3", iter_props) # test dir props dir_props = self.layout.__dir__() self.assertIn("xaxis", dir_props) self.assertNotIn("xaxis1", dir_props) self.assertIn("xaxis2", dir_props) self.assertIn("xaxis3", dir_props) def test_subplot_objs_have_proper_type(self): self.layout.xaxis2 = {} self.assertIsInstance(self.layout.xaxis2, go.layout.XAxis) self.layout.yaxis3 = {} self.assertIsInstance(self.layout.yaxis3, go.layout.YAxis) self.layout.geo4 = {} self.assertIsInstance(self.layout.geo4, go.layout.Geo) self.layout.ternary5 = {} self.assertIsInstance(self.layout.ternary5, go.layout.Ternary) self.layout.scene6 = {} self.assertIsInstance(self.layout.scene6, go.layout.Scene) self.layout.mapbox7 = {} self.assertIsInstance(self.layout.mapbox7, go.layout.Mapbox) self.layout.polar8 = {} self.assertIsInstance(self.layout.polar8, go.layout.Polar) def test_subplot_1_in_constructor(self): layout = go.Layout(xaxis1=go.layout.XAxis(title={"text": "xaxis 1"})) self.assertEqual(layout.xaxis1.title.text, "xaxis 1") def test_subplot_props_in_constructor(self): layout = go.Layout( xaxis2=go.layout.XAxis(title={"text": "xaxis 2"}), yaxis3=go.layout.YAxis(title={"text": "yaxis 3"}), geo4=go.layout.Geo(bgcolor="blue"), ternary5=go.layout.Ternary(sum=120), scene6=go.layout.Scene(dragmode="zoom"), mapbox7=go.layout.Mapbox(zoom=2), polar8=go.layout.Polar(sector=[0, 90]), ) self.assertEqual(layout.xaxis2.title.text, "xaxis 2") self.assertEqual(layout.yaxis3.title.text, "yaxis 3") self.assertEqual(layout.geo4.bgcolor, "blue") self.assertEqual(layout.ternary5.sum, 120) self.assertEqual(layout.scene6.dragmode, "zoom") self.assertEqual(layout.mapbox7.zoom, 2) self.assertEqual(layout.polar8.sector, (0, 90)) def test_create_subplot_with_update(self): self.layout.update( xaxis1=go.layout.XAxis(title={"text": "xaxis 1"}), xaxis2=go.layout.XAxis(title={"text": "xaxis 2"}), yaxis3=go.layout.YAxis(title={"text": "yaxis 3"}), geo4=go.layout.Geo(bgcolor="blue"), ternary5=go.layout.Ternary(sum=120), scene6=go.layout.Scene(dragmode="zoom"), mapbox7=go.layout.Mapbox(zoom=2), polar8=go.layout.Polar(sector=[0, 90]), ) self.assertEqual(self.layout.xaxis1.title.text, "xaxis 1") self.assertEqual(self.layout.xaxis2.title.text, "xaxis 2") self.assertEqual(self.layout.yaxis3.title.text, "yaxis 3") self.assertEqual(self.layout.geo4.bgcolor, "blue") self.assertEqual(self.layout.ternary5.sum, 120) self.assertEqual(self.layout.scene6.dragmode, "zoom") self.assertEqual(self.layout.mapbox7.zoom, 2) self.assertEqual(self.layout.polar8.sector, (0, 90)) def test_create_subplot_with_update_dict(self): self.layout.update( { "xaxis1": {"title": {"text": "xaxis 1"}}, "xaxis2": {"title": {"text": "xaxis 2"}}, "yaxis3": {"title": {"text": "yaxis 3"}}, "geo4": {"bgcolor": "blue"}, "ternary5": {"sum": 120}, "scene6": {"dragmode": "zoom"}, "mapbox7": {"zoom": 2}, "polar8": {"sector": [0, 90]}, } ) self.assertEqual(self.layout.xaxis1.title.text, "xaxis 1") self.assertEqual(self.layout.xaxis2.title.text, "xaxis 2") self.assertEqual(self.layout.yaxis3.title.text, "yaxis 3") self.assertEqual(self.layout.geo4.bgcolor, "blue") self.assertEqual(self.layout.ternary5.sum, 120) self.assertEqual(self.layout.scene6.dragmode, "zoom") self.assertEqual(self.layout.mapbox7.zoom, 2) self.assertEqual(self.layout.polar8.sector, (0, 90)) def test_bug_1462(self): # https: // github.com / plotly / plotly.py / issues / 1462 fig = go.Figure( data=[ go.Scatter(x=[1, 2], y=[1, 2], xaxis="x"), go.Scatter(x=[2, 3], y=[2, 3], xaxis="x2"), ] ) layout_dict = { "grid": {"xaxes": ["x", "x2"], "yaxes": ["y"]}, "xaxis2": {"matches": "x", "title": {"text": "total_bill"}}, } fig.update(layout=layout_dict) updated_layout_dict = fig.layout.to_plotly_json() self.assertEqual(updated_layout_dict, layout_dict)
TestLayoutSubplots
python
numpy__numpy
benchmarks/benchmarks/bench_manipulate.py
{ "start": 1097, "end": 1993 }
class ____(Benchmark): params = [[(16, 32), (32, 64)], [2, 5], TYPES1] param_names = ['shape', 'narrays', 'ndtype'] timeout = 10 def setup(self, shape, narrays, ndtype): self.xarg = [np.random.ranf(shape[0] * shape[1]).reshape(shape) for x in range(narrays)] self.xarg = [x.astype(ndtype) for x in self.xarg] if ndtype.startswith('complex'): [x + np.random.ranf(1) * 1j for x in self.xarg] def time_concatenate_ax0(self, size, narrays, ndtype): np.concatenate(self.xarg, axis=0) def time_concatenate_ax1(self, size, narrays, ndtype): np.concatenate(self.xarg, axis=1) def time_stack_ax0(self, size, narrays, ndtype): np.stack(self.xarg, axis=0) def time_stack_ax1(self, size, narrays, ndtype): np.stack(self.xarg, axis=1)
ConcatenateStackArrays
python
jazzband__django-pipeline
pipeline/compilers/__init__.py
{ "start": 3176, "end": 6340 }
class ____(CompilerBase): def execute_command(self, command, cwd=None, stdout_captured=None): """Execute a command at cwd, saving its normal output at stdout_captured. Errors, defined as nonzero return code or a failure to start execution, will raise a CompilerError exception with a description of the cause. They do not write output. This is file-system safe (any valid file names are allowed, even with spaces or crazy characters) and OS agnostic (existing and future OSes that Python supports should already work). The only thing weird here is that any incoming command arg item may itself be a tuple. This allows compiler implementations to look clean while supporting historical string config settings and maintaining backwards compatibility. Thus, we flatten one layer deep. ((env, foocomp), infile, (-arg,)) -> (env, foocomp, infile, -arg) """ argument_list = [] for flattening_arg in command: if isinstance(flattening_arg, (str,)): argument_list.append(flattening_arg) else: argument_list.extend(flattening_arg) # The first element in argument_list is the program that will be # executed; if it is '', then a PermissionError will be raised. # Thus empty arguments are filtered out from argument_list argument_list = list(filter(None, argument_list)) stdout = None try: # We always catch stdout in a file, but we may not have a use for it. temp_file_container = ( cwd or os.path.dirname(stdout_captured or "") or os.getcwd() ) with NamedTemporaryFile( "wb", delete=False, dir=temp_file_container ) as stdout: compiling = subprocess.Popen( argument_list, cwd=cwd, stdout=stdout, stderr=subprocess.PIPE ) _, stderr = compiling.communicate() set_std_streams_blocking() if compiling.returncode != 0: stdout_captured = None # Don't save erroneous result. raise CompilerError( f"{argument_list!r} exit code {compiling.returncode}\n{stderr}", command=argument_list, error_output=force_str(stderr), ) # User wants to see everything that happened. if self.verbose: with open(stdout.name, "rb") as out: print(out.read()) print(stderr) except OSError as e: stdout_captured = None # Don't save erroneous result. raise CompilerError(e, command=argument_list, error_output=str(e)) finally: # Decide what to do with captured stdout. if stdout: if stdout_captured: shutil.move( stdout.name, os.path.join(cwd or os.curdir, stdout_captured) ) else: os.remove(stdout.name)
SubProcessCompiler
python
marshmallow-code__marshmallow
tests/test_deserialization.py
{ "start": 60074, "end": 60254 }
class ____(Schema): email = fields.Email() colors = fields.Str(validate=validate.OneOf(["red", "blue"])) age = fields.Integer(validate=[validate.Range(1, 99)])
Validators
python
django__django
django/contrib/postgres/search.py
{ "start": 12473, "end": 12541 }
class ____(TrigramBase): function = "SIMILARITY"
TrigramSimilarity
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 150283, "end": 151375 }
class ____(sgqlc.types.Input): """Information from a check run analysis to specific lines of code.""" __schema__ = github_schema __field_names__ = ("path", "location", "annotation_level", "message", "title", "raw_details") path = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="path") """The path of the file to add an annotation to.""" location = sgqlc.types.Field(sgqlc.types.non_null("CheckAnnotationRange"), graphql_name="location") """The location of the annotation""" annotation_level = sgqlc.types.Field(sgqlc.types.non_null(CheckAnnotationLevel), graphql_name="annotationLevel") """Represents an annotation's information level""" message = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="message") """A short description of the feedback for these lines of code.""" title = sgqlc.types.Field(String, graphql_name="title") """The title that represents the annotation.""" raw_details = sgqlc.types.Field(String, graphql_name="rawDetails") """Details about this annotation."""
CheckAnnotationData
python
huggingface__transformers
src/transformers/models/dab_detr/modeling_dab_detr.py
{ "start": 64462, "end": 66081 }
class ____(nn.Module): """This is a 2D attention module, which only returns the attention softmax (no multiplication by value)""" def __init__(self, query_dim, hidden_dim, num_heads, dropout=0.0, bias=True, std=None): super().__init__() self.num_heads = num_heads self.hidden_dim = hidden_dim self.dropout = nn.Dropout(dropout) self.q_linear = nn.Linear(query_dim, hidden_dim, bias=bias) self.k_linear = nn.Linear(query_dim, hidden_dim, bias=bias) self.normalize_fact = float(hidden_dim / self.num_heads) ** -0.5 def forward(self, q, k, mask: Optional[Tensor] = None): q = self.q_linear(q) k = nn.functional.conv2d(k, self.k_linear.weight.unsqueeze(-1).unsqueeze(-1), self.k_linear.bias) queries_per_head = q.view(q.shape[0], q.shape[1], self.num_heads, self.hidden_dim // self.num_heads) keys_per_head = k.view(k.shape[0], self.num_heads, self.hidden_dim // self.num_heads, k.shape[-2], k.shape[-1]) weights = torch.einsum("bqnc,bnchw->bqnhw", queries_per_head * self.normalize_fact, keys_per_head) if mask is not None: weights = weights.masked_fill(mask.unsqueeze(1).unsqueeze(1), torch.finfo(weights.dtype).min) weights = nn.functional.softmax(weights.flatten(2), dim=-1).view(weights.size()) weights = self.dropout(weights) return weights @auto_docstring( custom_intro=""" DAB_DETR Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks such as COCO detection. """ )
DabDetrMHAttentionMap
python
scipy__scipy
scipy/stats/tests/test_stats.py
{ "start": 194101, "end": 199391 }
class ____: """ Tests kstest and ks_samp 1-samples with K-S various sizes, alternatives, modes. """ def _testOne(self, x, alternative, expected_statistic, expected_prob, *, mode='auto', dtype, xp): rtol = 5e-14 if dtype == xp.float64 else 1e-5 res = stats.ks_1samp(x, special.ndtr, alternative=alternative, mode=mode) ref_statistic = xp.asarray(expected_statistic, dtype=dtype) ref_pvalue = xp.asarray(expected_prob, dtype=dtype) xp_assert_close(res.statistic, ref_statistic, rtol=rtol) xp_assert_close(res.pvalue, ref_pvalue, rtol=rtol) @pytest.mark.parametrize('dtype', [None, 'float32', 'float64']) def test_agree_with_r(self, dtype, xp): # comparing with some values from R if is_numpy(xp) and xp.__version__ < "2.0" and dtype == 'float32': pytest.skip("Pre-NEP 50 doesn't respect dtypes") dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype) x = xp.linspace(-1, 1, 9, dtype=dtype) self._testOne(x, 'two-sided', 0.15865525393145705, 0.95164069201518386, dtype=dtype, xp=xp) x = xp.linspace(-15, 15, 9, dtype=dtype) self._testOne(x, 'two-sided', 0.44435602715924361, 0.038850140086788665, dtype=dtype, xp=xp) x = [-1.23, 0.06, -0.60, 0.17, 0.66, -0.17, -0.08, 0.27, -0.98, -0.99] x = xp.asarray(x, dtype=dtype) self._testOne(x, 'two-sided', 0.293580126801961, 0.293408463684361, dtype=dtype, xp=xp) self._testOne(x, 'greater', 0.293580126801961, 0.146988835042376, mode='exact', dtype=dtype, xp=xp) self._testOne(x, 'less', 0.109348552425692, 0.732768892470675, mode='exact', dtype=dtype, xp=xp) @pytest.mark.parametrize('dtype', [None, 'float32', 'float64']) def test_known_examples(self, xp, dtype): # the following tests rely on deterministically replicated rvs if is_numpy(xp) and xp.__version__ < "2.0" and dtype == 'float32': pytest.skip("Pre-NEP 50 doesn't respect dtypes") dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype) x = stats.norm.rvs(loc=0.2, size=100, random_state=987654321) x = xp.asarray(x, dtype=dtype) self._testOne(x, 'two-sided', 0.12464329735846891, 0.089444888711820769, mode='asymp', xp=xp, dtype=dtype) self._testOne(x, 'less', 0.12464329735846891, 0.040989164077641749, xp=xp, dtype=dtype) self._testOne(x, 'greater', 0.0072115233216310994, 0.98531158590396228, xp=xp, dtype=dtype) # this is a test of the exact p-value calculation, available only with NumPy. def test_ks1samp_allpaths(self): # Check NaN input, output. assert_(np.isnan(kolmogn(np.nan, 1, True))) with assert_raises(ValueError, match='n is not integral: 1.5'): kolmogn(1.5, 1, True) assert_(np.isnan(kolmogn(-1, 1, True))) dataset = np.asarray([ # Check x out of range (101, 1, True, 1.0), (101, 1.1, True, 1.0), (101, 0, True, 0.0), (101, -0.1, True, 0.0), (32, 1.0 / 64, True, 0.0), # Ruben-Gambino (32, 1.0 / 64, False, 1.0), # Ruben-Gambino # Miller (32, 0.5, True, 0.9999999363163307), # Miller 2 * special.smirnov(32, 0.5) (32, 0.5, False, 6.368366937916623e-08), # Check some other paths (32, 1.0 / 8, True, 0.34624229979775223), (32, 1.0 / 4, True, 0.9699508336558085), (1600, 0.49, False, 0.0), # 2 * special.smirnov(1600, 1/16.0) (1600, 1 / 16.0, False, 7.0837876229702195e-06), # _kolmogn_DMTW (1600, 14 / 1600, False, 0.99962357317602), # _kolmogn_PelzGood (1600, 1 / 32, False, 0.08603386296651416), ]) FuncData(kolmogn, dataset, (0, 1, 2), 3).check(dtypes=[int, float, bool]) @pytest.mark.parametrize("ksfunc", [stats.kstest, stats.ks_1samp]) @pytest.mark.parametrize("alternative, x6val, ref_location, ref_sign", [('greater', 6., 6., +1), ('less', 7., 7., -1), ('two-sided', 6., 6., +1), ('two-sided', 7., 7., -1)]) def test_location_sign(self, ksfunc, alternative, x6val, ref_location, ref_sign, xp): # Test that location and sign corresponding with statistic are as # expected. (Test is designed to be easy to predict.) x = xp.arange(10.) + 0.5 x = xpx.at(x)[6].set(x6val) # cdf = stats.uniform(scale=10).cdf def cdf(x): return x / 10. res = ksfunc(xp.asarray(x), cdf, alternative=alternative) rtol = 1e-15 if x.dtype == xp.float64 else 1e-6 xp_assert_close(res.statistic, xp.asarray(0.1), rtol=rtol) xp_assert_equal(res.statistic_location, xp.asarray(ref_location)) xp_assert_equal(res.statistic_sign, xp.asarray(ref_sign, dtype=xp.int8)) # missing: no test that uses *args
TestKSOneSample
python
apache__airflow
airflow-core/src/airflow/models/dagcode.py
{ "start": 1739, "end": 7174 }
class ____(Base): """ A table for DAGs code. dag_code table contains code of DAG files synchronized by scheduler. For details on dag serialization see SerializedDagModel """ __tablename__ = "dag_code" id: Mapped[str] = mapped_column(UUIDType(binary=False), primary_key=True, default=uuid6.uuid7) dag_id: Mapped[str] = mapped_column(String(ID_LEN), nullable=False) fileloc: Mapped[str] = mapped_column(String(2000), nullable=False) # The max length of fileloc exceeds the limit of indexing. created_at: Mapped[datetime] = mapped_column(UtcDateTime, nullable=False, default=timezone.utcnow) last_updated: Mapped[datetime] = mapped_column( UtcDateTime, nullable=False, default=timezone.utcnow, onupdate=timezone.utcnow ) source_code: Mapped[str] = mapped_column(Text().with_variant(MEDIUMTEXT(), "mysql"), nullable=False) source_code_hash: Mapped[str] = mapped_column(String(32), nullable=False) dag_version_id: Mapped[str] = mapped_column( UUIDType(binary=False), ForeignKey("dag_version.id", ondelete="CASCADE"), nullable=False, unique=True ) dag_version = relationship("DagVersion", back_populates="dag_code", uselist=False) def __init__(self, dag_version, full_filepath: str, source_code: str | None = None): self.dag_version = dag_version self.fileloc = full_filepath self.source_code = source_code or DagCode.code(self.dag_version.dag_id) self.source_code_hash = self.dag_source_hash(self.source_code) self.dag_id = dag_version.dag_id @classmethod @provide_session def write_code(cls, dag_version: DagVersion, fileloc: str, session: Session = NEW_SESSION) -> DagCode: """ Write code into database. :param fileloc: file path of DAG to sync :param session: ORM Session """ log.debug("Writing DAG file %s into DagCode table", fileloc) dag_code = DagCode(dag_version, fileloc, cls.get_code_from_file(fileloc)) session.add(dag_code) log.debug("DAG file %s written into DagCode table", fileloc) return dag_code @classmethod @provide_session def has_dag(cls, dag_id: str, session: Session = NEW_SESSION) -> bool: """ Check a dag exists in dag code table. :param dag_id: the dag_id of the DAG :param session: ORM Session """ return ( session.scalars(select(literal(True)).where(cls.dag_id == dag_id).limit(1)).one_or_none() is not None ) @classmethod @provide_session def code(cls, dag_id, session: Session = NEW_SESSION) -> str: """ Return source code for this DagCode object. :return: source code as string """ return cls._get_code_from_db(dag_id, session) @staticmethod def get_code_from_file(fileloc): try: with open_maybe_zipped(fileloc, "r") as f: code = f.read() return code except FileNotFoundError: test_mode = conf.getboolean("core", "unit_test_mode") if test_mode: return "source_code" raise @classmethod @provide_session def _get_code_from_db(cls, dag_id, session: Session = NEW_SESSION) -> str: dag_code = session.scalar( select(cls).where(cls.dag_id == dag_id).order_by(cls.last_updated.desc()).limit(1) ) if not dag_code: raise DagCodeNotFound() code = dag_code.source_code return code @staticmethod def dag_source_hash(source: str) -> str: """ Hash the source code of the DAG. This is needed so we can update the source on code changes """ return md5(source.encode("utf-8")).hexdigest() @classmethod def _latest_dagcode_select(cls, dag_id: str) -> Select: """ Get the select object to get the latest dagcode. :param dag_id: The DAG ID. :return: The select object. """ return select(cls).where(cls.dag_id == dag_id).order_by(cls.last_updated.desc()).limit(1) @classmethod @provide_session def get_latest_dagcode(cls, dag_id: str, session: Session = NEW_SESSION) -> DagCode | None: """ Get the latest dagcode. :param dag_id: The DAG ID. :param session: The database session. :return: The latest dagcode or None if not found. """ return session.scalar(cls._latest_dagcode_select(dag_id)) @classmethod @provide_session def update_source_code(cls, dag_id: str, fileloc: str, session: Session = NEW_SESSION) -> None: """ Check if the source code of the DAG has changed and update it if needed. :param dag_id: Dag ID :param fileloc: The path of code file to read the code from :param session: The database session. :return: None """ latest_dagcode = cls.get_latest_dagcode(dag_id, session) if not latest_dagcode: return new_source_code = cls.get_code_from_file(fileloc) new_source_code_hash = cls.dag_source_hash(new_source_code) if new_source_code_hash != latest_dagcode.source_code_hash: latest_dagcode.source_code = new_source_code latest_dagcode.source_code_hash = new_source_code_hash session.merge(latest_dagcode)
DagCode
python
great-expectations__great_expectations
great_expectations/datasource/fluent/data_asset/path/spark/spark_generic.py
{ "start": 310, "end": 1669 }
class ____(PathDataAsset): # vvv Docs <> Source Code mismatch # ignoreCorruptFiles and ignoreMissingFiles appear in the docs https://spark.apache.org/docs/latest/sql-data-sources-generic-options.html # but not in any reader method signatures (e.g. https://github.com/apache/spark/blob/v3.4.0/python/pyspark/sql/readwriter.py#L604) # ignore_corrupt_files: bool = Field(alias="ignoreCorruptFiles") # ignore_missing_files: bool = Field(alias="ignoreMissingFiles") # ^^^ Docs <> Source Code mismatch path_glob_filter: Optional[Union[bool, str]] = Field(None, alias="pathGlobFilter") recursive_file_lookup: Optional[Union[bool, str]] = Field(None, alias="recursiveFileLookup") modified_before: Optional[Union[bool, str]] = Field(None, alias="modifiedBefore") modified_after: Optional[Union[bool, str]] = Field(None, alias="modifiedAfter") @override def _get_reader_options_include(self) -> set[str]: return { "path_glob_filter", "recursive_file_lookup", "modified_before", "modified_after", # vvv Missing from method signatures but appear in documentation: # "ignoreCorruptFiles", # "ignore_missing_files", # ^^^ Missing from method signatures but appear in documentation: }
_SparkGenericFilePathAssetMixin
python
lxml__lxml
src/lxml/tests/test_incremental_xmlfile.py
{ "start": 13770, "end": 14087 }
class ____(_XmlFileTestCaseBase): def setUp(self): self._file = BytesIO() def test_filelike_close(self): with etree.xmlfile(self._file, close=True) as xf: with xf.element('test'): pass self.assertRaises(ValueError, self._file.getvalue)
BytesIOXmlFileTestCase
python
django__django
django/core/cache/backends/memcached.py
{ "start": 236, "end": 5311 }
class ____(BaseCache): def __init__(self, server, params, library, value_not_found_exception): super().__init__(params) if isinstance(server, str): self._servers = re.split("[;,]", server) else: self._servers = server # Exception type raised by the underlying client library for a # nonexistent key. self.LibraryValueNotFoundException = value_not_found_exception self._lib = library self._class = library.Client self._options = params.get("OPTIONS") or {} @property def client_servers(self): return self._servers @cached_property def _cache(self): """ Implement transparent thread-safe access to a memcached client. """ return self._class(self.client_servers, **self._options) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout if timeout is None: # Using 0 in memcache sets a non-expiring timeout. return 0 elif int(timeout) == 0: # Other cache backends treat 0 as set-and-expire. To achieve this # in memcache backends, a negative timeout must be passed. timeout = -1 if timeout > 2592000: # 60*60*24*30, 30 days # See: # https://github.com/memcached/memcached/wiki/Programming#expiration # "Expiration times can be set from 0, meaning "never expire", to # 30 days. Any time higher than 30 days is interpreted as a Unix # timestamp date. If you want to expire an object on January 1st of # next year, this is how you do that." # # This means that we have to switch to absolute timestamps. timeout += int(time.time()) return int(timeout) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.get(key, default) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) if not self._cache.set(key, value, self.get_backend_timeout(timeout)): # Make sure the key doesn't keep its old value in case of failure # to set (memcached's 1MB limit). self._cache.delete(key) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return bool(self._cache.touch(key, self.get_backend_timeout(timeout))) def delete(self, key, version=None): key = self.make_and_validate_key(key, version=version) return bool(self._cache.delete(key)) def get_many(self, keys, version=None): key_map = { self.make_and_validate_key(key, version=version): key for key in keys } ret = self._cache.get_multi(key_map.keys()) return {key_map[k]: v for k, v in ret.items()} def close(self, **kwargs): # Many clients don't clean up connections properly. self._cache.disconnect_all() def incr(self, key, delta=1, version=None): key = self.make_and_validate_key(key, version=version) try: # Memcached doesn't support negative delta. if delta < 0: val = self._cache.decr(key, -delta) else: val = self._cache.incr(key, delta) # Normalize an exception raised by the underlying client library to # ValueError in the event of a nonexistent key when calling # incr()/decr(). except self.LibraryValueNotFoundException: val = None if val is None: raise ValueError("Key '%s' not found" % key) return val def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): safe_data = {} original_keys = {} for key, value in data.items(): safe_key = self.make_and_validate_key(key, version=version) safe_data[safe_key] = value original_keys[safe_key] = key failed_keys = self._cache.set_multi( safe_data, self.get_backend_timeout(timeout) ) return [original_keys[k] for k in failed_keys] def delete_many(self, keys, version=None): keys = [self.make_and_validate_key(key, version=version) for key in keys] self._cache.delete_multi(keys) def clear(self): self._cache.flush_all() def validate_key(self, key): for warning in memcache_key_warnings(key): raise InvalidCacheKey(warning)
BaseMemcachedCache
python
pytorch__pytorch
test/functorch/test_control_flow.py
{ "start": 208803, "end": 223167 }
class ____(torch.nn.Module): def forward(self, L_ctx_saved_tensors_0_: "f32[4]", L_ctx_pred: "b8[]", L_args_1_: "f32[4]"): l_ctx_saved_tensors_0_ = L_ctx_saved_tensors_0_ l_ctx_pred = L_ctx_pred l_args_1_ = L_args_1_ cond_true_0 = self.cond_true_0 cond_false_0 = self.cond_false_0 cond = torch.ops.higher_order.cond(l_ctx_pred, cond_true_0, cond_false_0, (l_args_1_, l_ctx_saved_tensors_0_)); l_ctx_pred = cond_true_0 = cond_false_0 = l_args_1_ = l_ctx_saved_tensors_0_ = None getitem: "f32[4]" = cond[0]; cond = None return (getitem,) class cond_true_0(torch.nn.Module): def forward(self, l_args_1_: "f32[4]", l_ctx_saved_tensors_0_: "f32[4]"): l_args_1__1 = l_args_1_ l_ctx_saved_tensors_0__1 = l_ctx_saved_tensors_0_ sin: "f32[4]" = torch.ops.aten.sin.default(l_ctx_saved_tensors_0__1); sin = None cos: "f32[4]" = torch.ops.aten.cos.default(l_ctx_saved_tensors_0__1); l_ctx_saved_tensors_0__1 = None mul: "f32[4]" = torch.ops.aten.mul.Tensor(l_args_1__1, cos); l_args_1__1 = cos = None return (mul,) class cond_false_0(torch.nn.Module): def forward(self, l_args_1_: "f32[4]", l_ctx_saved_tensors_0_: "f32[4]"): l_args_1__1 = l_args_1_ l_ctx_saved_tensors_0__1 = l_ctx_saved_tensors_0_ cos: "f32[4]" = torch.ops.aten.cos.default(l_ctx_saved_tensors_0__1); cos = None sin: "f32[4]" = torch.ops.aten.sin.default(l_ctx_saved_tensors_0__1); l_ctx_saved_tensors_0__1 = None neg: "f32[4]" = torch.ops.aten.neg.default(sin); sin = None mul: "f32[4]" = torch.ops.aten.mul.Tensor(l_args_1__1, neg); l_args_1__1 = neg = None return (mul,) """, # noqa: B950 ) def test_while_loop_op_mismatch_in_meta(self): class Mod(torch.nn.Module): def forward(self, c, a, b): def cond_fn(c, a, b): return c > 0 def body_fn(c, a, b): return c - 1, a.nonzero(), b.nonzero() return torch.ops.higher_order.while_loop( cond_fn, body_fn, (c, a, b), tuple(), ) with self.assertRaisesRegex( torch._dynamo.exc.UncapturedHigherOrderOpError, "Expected carried_inputs and body_output to have same metadata but found", ): make_fx(Mod(), tracing_mode="fake")( torch.tensor( 0, ), torch.randn(2, 3), torch.randn(2, 3), ) def test_while_loop_nested_traced(self): fn, inp = WHILE_LOOP_TESTS["nested"] graphs = self._check_tracing(fn, inp) self.assertExpectedInline( graphs["symbolic"].code.strip("\n"), """\ def forward(self, out_iter_1, it_1, y_1): while_loop_cond_graph_0 = self.while_loop_cond_graph_0 while_loop_body_graph_0 = self.while_loop_body_graph_0 while_loop = torch.ops.higher_order.while_loop(while_loop_cond_graph_0, while_loop_body_graph_0, (out_iter_1, it_1, y_1), ()); while_loop_cond_graph_0 = while_loop_body_graph_0 = out_iter_1 = it_1 = y_1 = None getitem = while_loop[0] getitem_1 = while_loop[1] getitem_2 = while_loop[2]; while_loop = None return (getitem, getitem_1, getitem_2) """, # noqa: B950 ) self.assertExpectedInline( graphs["symbolic"].while_loop_cond_graph_0.code.strip("\n"), """\ def forward(self, arg0_1, arg1_1, arg2_1): sum_1 = torch.ops.aten.sum.default(arg0_1); arg0_1 = None lt = torch.ops.aten.lt.Scalar(sum_1, 2); sum_1 = None return lt """, ) self.assertExpectedInline( graphs["symbolic"].while_loop_body_graph_0.code.strip("\n"), """\ def forward(self, arg0_1, arg1_1, arg2_1): while_loop_cond_graph_0 = self.while_loop_cond_graph_0 while_loop_body_graph_0 = self.while_loop_body_graph_0 while_loop = torch.ops.higher_order.while_loop(while_loop_cond_graph_0, while_loop_body_graph_0, (arg0_1, arg1_1, arg2_1), ()); while_loop_cond_graph_0 = while_loop_body_graph_0 = arg0_1 = arg1_1 = arg2_1 = None getitem = while_loop[0] getitem_1 = while_loop[1] getitem_2 = while_loop[2]; while_loop = None add = torch.ops.aten.add.Tensor(getitem, 1); getitem = None return (add, getitem_1, getitem_2) """, # noqa: B950 ) def test_while_loop_pytree_carry(self): fn, inp = WHILE_LOOP_TESTS["simple_with_pytree_carry"] backend = EagerAndRecordGraphs() expected_res = fn(*inp) compiled_res = torch.compile(fn, backend=backend)(*inp) self.assertEqual(expected_res, compiled_res) # When test with torch dynamo, the graph is not captured because # it's traced together with the code before torch.compile if not TEST_WITH_TORCHDYNAMO: self.assertEqual(len(backend.graphs), 1) self.assertExpectedInline( backend.graphs[0].code.strip(), """\ def forward(self, L_it_ : torch.Tensor, L_pytree_input_0_0_ : torch.Tensor, L_pytree_input_1_x_ : torch.Tensor, L_pytree_input_1_y_ : torch.Tensor): l_it_ = L_it_ l_pytree_input_0_0_ = L_pytree_input_0_0_ l_pytree_input_1_x_ = L_pytree_input_1_x_ l_pytree_input_1_y_ = L_pytree_input_1_y_ cond_fn_0 = self.cond_fn_0 body_fn_0 = self.body_fn_0 while_loop = torch.ops.higher_order.while_loop(cond_fn_0, body_fn_0, (l_it_, l_pytree_input_0_0_, l_pytree_input_1_x_, l_pytree_input_1_y_), ()); cond_fn_0 = body_fn_0 = l_it_ = l_pytree_input_0_0_ = l_pytree_input_1_x_ = l_pytree_input_1_y_ = None getitem = while_loop[0] getitem_1 = while_loop[1] value = while_loop[2] value_1 = while_loop[3]; while_loop = None return (getitem, getitem_1, value, value_1)""", # noqa: B950 ) def _wrap_with_functionalize(self, fn, func_type): mode = None if func_type == "cpp": fn = CppFunctionalizeAPI().functionalize(fn) elif func_type == "python": fn = PythonFunctionalizeAPI().functionalize(fn) mode = FunctionalTensorMode() elif func_type == "functorch": fn = torch.func.functionalize(fn) else: assert func_type == "no" return fn, mode @parametrize("func_type", ["no", "cpp", "python", "functorch"]) def test_while_loop_simple_functionalize_check_graph(self, func_type): fn, inp = WHILE_LOOP_TESTS["simple_with_mutation"] fn, mode = self._wrap_with_functionalize(fn, func_type) mode = mode if mode is not None else contextlib.nullcontext() with mode: graphs = self._check_tracing(fn, inp) if func_type == "no": self.assertExpectedInline( graphs["symbolic"].code.strip("\n"), """\ def forward(self, x_1): while_loop_cond_graph_0 = self.while_loop_cond_graph_0 while_loop_body_graph_0 = self.while_loop_body_graph_0 while_loop = torch.ops.higher_order.while_loop(while_loop_cond_graph_0, while_loop_body_graph_0, (x_1,), ()); while_loop_cond_graph_0 = while_loop_body_graph_0 = x_1 = None getitem = while_loop[0]; while_loop = None return (getitem,) """, # noqa: B950 ) self.assertExpectedInline( graphs["symbolic"].while_loop_cond_graph_0.code.strip("\n"), """\ def forward(self, arg0_1): clone = torch.ops.aten.clone.default(arg0_1); arg0_1 = None add_ = torch.ops.aten.add_.Tensor(clone, 1); clone = None add__1 = torch.ops.aten.add_.Tensor(add_, -1); add_ = None sum_1 = torch.ops.aten.sum.default(add__1); add__1 = None lt = torch.ops.aten.lt.Scalar(sum_1, 10); sum_1 = None return lt """, ) self.assertExpectedInline( graphs["symbolic"].while_loop_body_graph_0.code.strip("\n"), """\ def forward(self, arg0_1): clone = torch.ops.aten.clone.default(arg0_1); arg0_1 = None add_ = torch.ops.aten.add_.Tensor(clone, 1); clone = None add__1 = torch.ops.aten.add_.Tensor(add_, -1); add_ = None add = torch.ops.aten.add.Tensor(add__1, 1); add__1 = None return (add,) """, ) elif func_type == "python": self.assertExpectedInline( graphs["symbolic"].code.strip("\n"), """\ def forward(self, arg0_1): while_loop_cond_graph_0 = self.while_loop_cond_graph_0 while_loop_body_graph_0 = self.while_loop_body_graph_0 while_loop = torch.ops.higher_order.while_loop(while_loop_cond_graph_0, while_loop_body_graph_0, (arg0_1,), ()); while_loop_cond_graph_0 = while_loop_body_graph_0 = arg0_1 = None getitem = while_loop[0]; while_loop = None return (getitem,) """, # noqa: B950 ) self.assertExpectedInline( graphs["symbolic"].while_loop_cond_graph_0.code.strip("\n"), """\ def forward(self, arg0_1): clone = torch.ops.aten.clone.default(arg0_1); arg0_1 = None add = torch.ops.aten.add.Tensor(clone, 1); clone = None add_1 = torch.ops.aten.add.Tensor(add, -1); add = None sum_1 = torch.ops.aten.sum.default(add_1); add_1 = None lt = torch.ops.aten.lt.Scalar(sum_1, 10); sum_1 = None return lt """, ) self.assertExpectedInline( graphs["symbolic"].while_loop_body_graph_0.code.strip("\n"), """\ def forward(self, arg0_1): clone = torch.ops.aten.clone.default(arg0_1); arg0_1 = None add = torch.ops.aten.add.Tensor(clone, 1); clone = None add_1 = torch.ops.aten.add.Tensor(add, -1); add = None add_2 = torch.ops.aten.add.Tensor(add_1, 1); add_1 = None return (add_2,) """, ) else: self.assertExpectedInline( graphs["symbolic"].code.strip("\n"), """\ def forward(self, x_1): while_loop_cond_graph_0 = self.while_loop_cond_graph_0 while_loop_body_graph_0 = self.while_loop_body_graph_0 while_loop = torch.ops.higher_order.while_loop(while_loop_cond_graph_0, while_loop_body_graph_0, (x_1,), ()); while_loop_cond_graph_0 = while_loop_body_graph_0 = x_1 = None getitem = while_loop[0]; while_loop = None return (getitem,) """, # noqa: B950 ) self.assertExpectedInline( graphs["symbolic"].while_loop_cond_graph_0.code.strip("\n"), """\ def forward(self, arg0_1): clone = torch.ops.aten.clone.default(arg0_1); arg0_1 = None add = torch.ops.aten.add.Tensor(clone, 1); clone = None add_1 = torch.ops.aten.add.Tensor(add, -1); add = None sum_1 = torch.ops.aten.sum.default(add_1); add_1 = None lt = torch.ops.aten.lt.Scalar(sum_1, 10); sum_1 = None return lt """, ) self.assertExpectedInline( graphs["symbolic"].while_loop_body_graph_0.code.strip("\n"), """\ def forward(self, arg0_1): clone = torch.ops.aten.clone.default(arg0_1); arg0_1 = None add = torch.ops.aten.add.Tensor(clone, 1); clone = None add_1 = torch.ops.aten.add.Tensor(add, -1); add = None add_2 = torch.ops.aten.add.Tensor(add_1, 1); add_1 = None return (add_2,) """, ) @parametrize("func_type", ["no", "cpp", "python", "functorch"]) # - "simple_with_linear" and "nested_with_linear" doesn't work because parameters and buffers # are not inputs so they're not wrapped by functionalization and tracing. # # - make_fx tracing mode "real" fails for "int_carry", "pytree_int_carry" and "const_and_symint_output" # because tensors are real but we unspecialize the ints with unbacked symints causing # data dependent errors. # Since this is not the common use path, we skip them for now. @parametrize( "while_loop_test", set(WHILE_LOOP_TESTS.keys()) - { "simple_with_linear", "nested_with_linear", "int_carry", "pytree_int_carry", "const_and_symint_output", }, ) def test_while_loop_functionalize(self, func_type, while_loop_test): fn, inp = WHILE_LOOP_TESTS[while_loop_test] fn, mode = self._wrap_with_functionalize(fn, func_type) mode = mode if mode is not None else contextlib.nullcontext() with mode: self._check_tracing(fn, inp) # - make_fx tracing mode "real" fails for "int_carry", "pytree_int_carry" and "const_and_symint_output" # because tensors are real but we unspecialize the ints with unbacked symints causing # data dependent errors. # Since this is not the common use path, we skip them for now. @parametrize( "while_loop_test", set(WHILE_LOOP_TESTS.keys()) - {"int_carry", "pytree_int_carry", "const_and_symint_output"}, ) def test_while_loop_tracing(self, while_loop_test): fn, inp = WHILE_LOOP_TESTS[while_loop_test] allow_non_fake_inputs = while_loop_test in ( "simple_with_linear", "nested_with_linear", ) self._check_tracing(fn, inp, allow_non_fake_inputs) @parametrize("backend", ["eager", "aot_eager"]) @parametrize("while_loop_test", list(WHILE_LOOP_TESTS.keys())) def test_while_loop_compile(self, backend, while_loop_test): fn, inp = WHILE_LOOP_TESTS[while_loop_test] self._check_compile(fn, inp, backend=backend) @skipIfTorchDynamo("Graph is not captured by backend if test with dynamo") @skipIfCrossRef # Arg order changes with cross ref def test_while_loop_simple_with_linear_compile_check_graph(self): fn, inp = WHILE_LOOP_TESTS["simple_with_linear"] backend = EagerAndRecordGraphs() torch.compile(fn, backend=backend)(*inp) self.assertEqual(len(backend.graphs), 1) gm = backend.graphs[0] if torch._dynamo.config.inline_inbuilt_nn_modules: self.assertExpectedInline( normalize_gm(gm.print_readable(print_output=False)), """\
GraphModule
python
dagster-io__dagster
python_modules/dagster-pipes/dagster_pipes/__init__.py
{ "start": 46584, "end": 47572 }
class ____(PipesBlobStoreMessageWriter): """Message writer that writes messages by periodically writing message chunks to an AzureBlobStorage container. Args: client (Any): An azure.storage.blob.BlobServiceClient object. interval (float): interval in seconds between upload chunk uploads. """ def __init__(self, client: Any, *, interval: float = 10): super().__init__(interval=interval) self._client = client def make_channel( self, params: PipesParams, ) -> "PipesAzureBlobStorageMessageWriterChannel": bucket = _assert_env_param_type(params, "bucket", str, self.__class__) key_prefix = _assert_opt_env_param_type(params, "key_prefix", str, self.__class__) return PipesAzureBlobStorageMessageWriterChannel( client=self._client, bucket=bucket, key_prefix=key_prefix, interval=self.interval, )
PipesAzureBlobStorageMessageWriter
python
sqlalchemy__sqlalchemy
test/dialect/mssql/test_query.py
{ "start": 14395, "end": 20867 }
class ____(AssertsCompiledSQL, fixtures.TablesTest): __only_on__ = "mssql" __skip_if__ = (full_text_search_missing,) __backend__ = True run_setup_tables = "once" run_inserts = run_deletes = "once" @classmethod def define_tables(cls, metadata): Table( "cattable", metadata, Column("id", Integer), Column("description", String(50)), PrimaryKeyConstraint("id", name="PK_cattable"), ) Table( "matchtable", metadata, Column("id", Integer), Column("title", String(200)), Column("category_id", Integer, ForeignKey("cattable.id")), PrimaryKeyConstraint("id", name="PK_matchtable"), ) event.listen( metadata, "before_create", DDL("CREATE FULLTEXT CATALOG Catalog AS DEFAULT"), ) event.listen( metadata, "after_create", DDL( """CREATE FULLTEXT INDEX ON cattable (description) KEY INDEX PK_cattable""" ), ) event.listen( metadata, "after_create", DDL( """CREATE FULLTEXT INDEX ON matchtable (title) KEY INDEX PK_matchtable""" ), ) event.listen( metadata, "after_drop", DDL("DROP FULLTEXT CATALOG Catalog"), ) @classmethod def setup_bind(cls): return testing.db.execution_options(isolation_level="AUTOCOMMIT") @classmethod def setup_test_class(cls): with testing.db.connect().execution_options( isolation_level="AUTOCOMMIT" ) as conn: try: conn.exec_driver_sql("DROP FULLTEXT CATALOG Catalog") except: pass @classmethod def insert_data(cls, connection): cattable, matchtable = cls.tables("cattable", "matchtable") connection.execute( cattable.insert(), [ {"id": 1, "description": "Python"}, {"id": 2, "description": "Ruby"}, ], ) connection.execute( matchtable.insert(), [ { "id": 1, "title": "Web Development with Rails", "category_id": 2, }, {"id": 2, "title": "Dive Into Python", "category_id": 1}, { "id": 3, "title": "Programming Matz's Ruby", "category_id": 2, }, {"id": 4, "title": "Guide to Django", "category_id": 1}, {"id": 5, "title": "Python in a Nutshell", "category_id": 1}, ], ) # apparently this is needed! index must run asynchronously connection.execute(DDL("WAITFOR DELAY '00:00:05'")) def test_expression(self): matchtable = self.tables.matchtable self.assert_compile( matchtable.c.title.match("somstr"), "CONTAINS (matchtable.title, ?)", dialect=mssql_pyodbc.dialect(paramstyle="qmark"), ) def test_simple_match(self, connection): matchtable = self.tables.matchtable results = connection.execute( matchtable.select() .where(matchtable.c.title.match("python")) .order_by(matchtable.c.id) ).fetchall() eq_([2, 5], [r.id for r in results]) def test_simple_match_with_apostrophe(self, connection): matchtable = self.tables.matchtable results = connection.execute( matchtable.select().where(matchtable.c.title.match("Matz's")) ).fetchall() eq_([3], [r.id for r in results]) def test_simple_prefix_match(self, connection): matchtable = self.tables.matchtable results = connection.execute( matchtable.select().where(matchtable.c.title.match('"nut*"')) ).fetchall() eq_([5], [r.id for r in results]) def test_simple_inflectional_match(self, connection): matchtable = self.tables.matchtable results = connection.execute( matchtable.select().where( matchtable.c.title.match('FORMSOF(INFLECTIONAL, "dives")') ) ).fetchall() eq_([2], [r.id for r in results]) def test_or_match(self, connection): matchtable = self.tables.matchtable results1 = connection.execute( matchtable.select() .where( or_( matchtable.c.title.match("nutshell"), matchtable.c.title.match("ruby"), ) ) .order_by(matchtable.c.id) ).fetchall() eq_([3, 5], [r.id for r in results1]) results2 = connection.execute( matchtable.select() .where(matchtable.c.title.match("nutshell OR ruby")) .order_by(matchtable.c.id) ).fetchall() eq_([3, 5], [r.id for r in results2]) def test_and_match(self, connection): matchtable = self.tables.matchtable results1 = connection.execute( matchtable.select().where( and_( matchtable.c.title.match("python"), matchtable.c.title.match("nutshell"), ) ) ).fetchall() eq_([5], [r.id for r in results1]) results2 = connection.execute( matchtable.select().where( matchtable.c.title.match("python AND nutshell") ) ).fetchall() eq_([5], [r.id for r in results2]) def test_match_across_joins(self, connection): matchtable = self.tables.matchtable cattable = self.tables.cattable results = connection.execute( matchtable.select() .where( and_( cattable.c.id == matchtable.c.category_id, or_( cattable.c.description.match("Ruby"), matchtable.c.title.match("nutshell"), ), ) ) .order_by(matchtable.c.id) ).fetchall() eq_([1, 3, 5], [r.id for r in results])
MatchTest
python
ray-project__ray
release/train_tests/benchmark/s3_parquet_reader.py
{ "start": 1707, "end": 5401 }
class ____(S3Reader): """Extended S3Reader class for Parquet-specific functionality. Provides specialized methods for: 1. Collecting Parquet file metadata (row counts) from S3 2. Distributing files among workers based on row counts 3. Managing parallel S3 operations with Ray tasks """ def _collect_file_info( self, bucket: str, prefix: str ) -> Tuple[List[str], List[int]]: """Collect file URLs and their row counts in parallel using Ray tasks. Lists all Parquet files in the specified S3 prefix and launches parallel tasks to count rows in each file using S3 Select for efficient metadata collection. Args: bucket: S3 bucket name to list files from prefix: S3 prefix to filter files Returns: Tuple containing: - List of file URLs (e.g., "s3://bucket/path/to/file") - List of row counts for each file """ file_urls, _ = self._list_s3_files(bucket, prefix) # Launch parallel metadata collection tasks tasks = [] for file_url in file_urls: # Extract key from file_url key = file_url.replace(f"s3://{bucket}/", "") task = _fetch_parquet_metadata.remote(bucket, key, file_url) tasks.append(task) # Wait for all tasks to complete worker_rank = ray.train.get_context().get_world_rank() logger.info( f"Worker {worker_rank}: Waiting for metadata from {len(tasks)} files..." ) results = ray.get(tasks) # Process results file_urls, file_rows = zip(*results) if results else ([], []) logger.info( f"Worker {worker_rank}: Collected metadata for {len(file_urls)} files" ) return list(file_urls), list(file_rows) def _get_file_urls(self, url: str) -> List[str]: """Get file URLs from S3 and distribute them among Ray workers. Collects file metadata from S3 and distributes files among workers based on row counts to ensure balanced workload distribution. Args: url: S3 URL to list files from (e.g., "s3://bucket/path/to/directory") Returns: List of S3 URLs assigned to the current Ray worker Raises: S3CredentialsError: If AWS credentials are not found or invalid S3FileError: If there's an error listing files from S3 """ try: # Get Ray worker configuration worker_rank = ray.train.get_context().get_world_rank() num_workers = ray.train.get_context().get_world_size() # Parse S3 URL components bucket, prefix = self._parse_s3_url(url) # Collect file metadata for balanced distribution logger.info( f"Worker {worker_rank}: Collecting file metadata for balanced distribution" ) file_urls, file_rows = self._collect_file_info(bucket, prefix) logger.info(f"Found {len(file_urls)} files in {url}") # Distribute files based on row counts return self._distribute_files( file_urls=file_urls, file_weights=file_rows, worker_rank=worker_rank, num_workers=num_workers, weight_unit="rows", ) except NoCredentialsError: raise self.S3CredentialsError( "AWS credentials not found. Ensure you have configured them." ) except Exception as e: raise self.S3FileError(f"Error listing files from {url}: {str(e)}")
S3ParquetReader
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 37489, "end": 38385 }
class ____(BaseModel): type: Literal["WaitTimeFromHeader"] header: str = Field( ..., description="The name of the response header defining how long to wait before retrying.", examples=["Retry-After"], title="Response Header Name", ) regex: Optional[str] = Field( None, description="Optional regex to apply on the header to extract its value. The regex should define a capture group defining the wait time.", examples=["([-+]?\\d+)"], title="Extraction Regex", ) max_waiting_time_in_seconds: Optional[float] = Field( None, description="Given the value extracted from the header is greater than this value, stop the stream.", examples=[3600], title="Max Waiting Time in Seconds", ) parameters: Optional[Dict[str, Any]] = Field(None, alias="$parameters")
WaitTimeFromHeader
python
ionelmc__pytest-benchmark
src/pytest_benchmark/logger.py
{ "start": 150, "end": 206 }
class ____(PytestWarning): pass
PytestBenchmarkWarning
python
python-openxml__python-docx
tests/image/test_jpeg.py
{ "start": 8550, "end": 10014 }
class ____: def it_can_construct_from_a_stream_and_offset(self, _App0Marker__init_): bytes_ = b"\x00\x10JFIF\x00\x01\x01\x01\x00\x2a\x00\x18" marker_code, offset, length = JPEG_MARKER_CODE.APP0, 0, 16 density_units, x_density, y_density = 1, 42, 24 stream = StreamReader(io.BytesIO(bytes_), BIG_ENDIAN) app0_marker = _App0Marker.from_stream(stream, marker_code, offset) _App0Marker__init_.assert_called_once_with( ANY, marker_code, offset, length, density_units, x_density, y_density ) assert isinstance(app0_marker, _App0Marker) def it_knows_the_image_dpi(self, dpi_fixture): density_units, x_density, y_density, horz_dpi, vert_dpi = dpi_fixture app0 = _App0Marker(None, None, None, density_units, x_density, y_density) assert app0.horz_dpi == horz_dpi assert app0.vert_dpi == vert_dpi # fixtures ------------------------------------------------------- @pytest.fixture def _App0Marker__init_(self, request): return initializer_mock(request, _App0Marker) @pytest.fixture( params=[ (0, 100, 200, 72, 72), (1, 100, 200, 100, 200), (2, 100, 200, 254, 508), ] ) def dpi_fixture(self, request): density_units, x_density, y_density, horz_dpi, vert_dpi = request.param return density_units, x_density, y_density, horz_dpi, vert_dpi
Describe_App0Marker
python
pytorch__pytorch
torch/_inductor/virtualized.py
{ "start": 4592, "end": 6350 }
class ____(Generic[T]): """ Implements a global variable that redirects via thread local variable (NB: construct this class to create the global variable; this is not a singleton class!) This allows us to swap in different op implementations in codegen. NB: Despite the fact that we typically call these "handlers" (e.g., NullHandler is the default value of the variable), we sometimes use these variables to store other things, like booleans. """ def __init__(self, vname: str, default: Union[Callable[[], T], type[NullHandler]]): self._vname = vname self._key: str = f"__torchinductor_{vname}" self._default = default def _set_handler(self, value: T) -> AbstractContextManager[None]: prior = self._get_handler(False) setattr(threadlocal, self._key, value) @contextmanager def ctx(): try: yield finally: self._set_handler(prior) return ctx() def _get_handler(self, check_poisoned: bool = True) -> T: try: value = getattr(threadlocal, self._key) if check_poisoned and value is _PoisonedVirtual: raise RuntimeError( f"Attempt to use poisoned virtualized value '{self._vname}'." ) return value except AttributeError: # TODO: To be honest, I feel we probably should just error in this # case, instead of making a null handler that will probably error # when you getattr on it return self._default() # type: ignore[return-value] def __getattr__(self, name: str) -> Any: return getattr(self._get_handler(), name)
Virtualized
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 60978, "end": 61270 }
class ____(DynamicCache): def __init__(self) -> None: logger.warning_once( "`OffloadedCache` is deprecated and will be removed in version v4.59 " "Use `DynamicCache(offloading=True)` instead" ) super().__init__(offloading=True)
OffloadedCache
python
pytest-dev__pytest
doc/en/example/fixtures/test_fixtures_order_autouse_multiple_scopes.py
{ "start": 453, "end": 560 }
class ____: def test_order(self, order, c2): assert order == ["c1", "c2"]
TestClassWithoutC1Request
python
getsentry__sentry
tests/sentry/issues/test_issue_search.py
{ "start": 6637, "end": 8830 }
class ____(TestCase): def test_valid_assign_me_converter(self) -> None: raw_value = "me" filters = [SearchFilter(SearchKey("assigned_to"), "=", SearchValue(raw_value))] expected = value_converters["assigned_to"]([raw_value], [self.project], self.user, None) filters = convert_query_values(filters, [self.project], self.user, None) assert filters[0].value.raw_value == expected def test_valid_assign_me_no_converter(self) -> None: search_val = SearchValue("me") filters = [SearchFilter(SearchKey("something"), "=", search_val)] filters = convert_query_values(filters, [self.project], self.user, None) assert filters[0].value.raw_value == search_val.raw_value def test_valid_assign_my_teams_converter(self) -> None: raw_value = "my_teams" filters = [SearchFilter(SearchKey("assigned_to"), "=", SearchValue(raw_value))] expected = value_converters["assigned_to"]([raw_value], [self.project], self.user, None) filters = convert_query_values(filters, [self.project], self.user, None) assert filters[0].value.raw_value == expected def test_valid_assign_my_teams_no_converter(self) -> None: search_val = SearchValue("my_teams") filters = [SearchFilter(SearchKey("something"), "=", search_val)] filters = convert_query_values(filters, [self.project], self.user, None) assert filters[0].value.raw_value == search_val.raw_value def test_valid_converter(self) -> None: raw_value = "me" filters = [SearchFilter(SearchKey("assigned_to"), "=", SearchValue(raw_value))] expected = value_converters["assigned_to"]([raw_value], [self.project], self.user, None) filters = convert_query_values(filters, [self.project], self.user, None) assert filters[0].value.raw_value == expected def test_no_converter(self) -> None: search_val = SearchValue("me") filters = [SearchFilter(SearchKey("something"), "=", search_val)] filters = convert_query_values(filters, [self.project], self.user, None) assert filters[0].value.raw_value == search_val.raw_value
ConvertQueryValuesTest
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 946938, "end": 947358 }
class ____(sgqlc.types.Type): """An edge in a connection.""" __schema__ = github_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") """A cursor for use in pagination.""" node = sgqlc.types.Field("RepositoryVulnerabilityAlert", graphql_name="node") """The item at the end of the edge."""
RepositoryVulnerabilityAlertEdge
python
Lightning-AI__lightning
src/lightning/fabric/utilities/distributed.py
{ "start": 12284, "end": 14273 }
class ____(Dataset): """Dataset to create indexes from `Sampler` or `Iterable`""" def __init__(self, sampler: Union[Sampler, Iterable]) -> None: if not isinstance(sampler, Sized): raise TypeError( "You seem to have configured a sampler in your DataLoader which" " does not provide `__len__` method. The sampler was about to be" " replaced by `DistributedSamplerWrapper` since `use_distributed_sampler`" " is True and you are using distributed training. Either provide `__len__`" " method in your sampler, remove it from DataLoader or set `use_distributed_sampler=False`" " if you want to handle distributed sampling yourself." ) if len(sampler) == float("inf"): raise TypeError( "You seem to have configured a sampler in your DataLoader which" " does not provide finite `__len__` method. The sampler was about to be" " replaced by `DistributedSamplerWrapper` since `use_distributed_sampler`" " is True and you are using distributed training. Either provide `__len__`" " method in your sampler which returns a finite number, remove it from DataLoader" " or set `use_distributed_sampler=False` if you want to handle distributed sampling yourself." ) self._sampler = sampler # defer materializing an iterator until it is necessary self._sampler_list: Optional[list[Any]] = None @override def __getitem__(self, index: int) -> Any: if self._sampler_list is None: self._sampler_list = list(self._sampler) return self._sampler_list[index] def __len__(self) -> int: return len(self._sampler) def reset(self) -> None: """Reset the sampler list in order to get new sampling.""" self._sampler_list = list(self._sampler)
_DatasetSamplerWrapper
python
huggingface__transformers
src/transformers/models/siglip2/modeling_siglip2.py
{ "start": 18315, "end": 19307 }
class ____(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`Siglip2EncoderLayer`]. Args: config: Siglip2Config """ def __init__(self, config: Siglip2Config): super().__init__() self.config = config self.layers = nn.ModuleList([Siglip2EncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False # Ignore copy @auto_docstring def forward( self, inputs_embeds, attention_mask: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutput: hidden_states = inputs_embeds for encoder_layer in self.layers: hidden_states = encoder_layer( hidden_states, attention_mask, **kwargs, ) return BaseModelOutput(last_hidden_state=hidden_states)
Siglip2Encoder
python
django__django
django/db/migrations/serializer.py
{ "start": 10378, "end": 10475 }
class ____(BaseSequenceSerializer): def _format(self): return "[%s]"
SequenceSerializer
python
getsentry__sentry
tests/sentry/web/frontend/test_setup_wizard.py
{ "start": 378, "end": 12834 }
class ____(PermissionTestCase): def test_redirect(self) -> None: user = self.create_user("foo@example.com", is_active=False) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(url) self.login_as(user) assert resp.status_code == 302 def test_simple(self) -> None: self.create_organization(owner=self.user) self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(url) assert resp.status_code == 200 self.assertTemplateUsed(resp, "sentry/setup-wizard.html") def test_redirect_to_org(self) -> None: self.create_organization(owner=self.user) self.login_as(self.user) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "xyz"}) resp = self.client.get(url) assert resp.status_code == 302 def test_renders_selection(self) -> None: self.org = self.create_organization(owner=self.user) self.team = self.create_team(organization=self.org, name="Mariachi Band") self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal") self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(url) assert resp.status_code == 200 self.assertTemplateUsed(resp, "sentry/setup-wizard.html") assert resp.context["enableProjectSelection"] is True cached = default_cache.get(key) assert cached == "test" def test_skips_selection_when_given_org_and_project_slug_and(self) -> None: self.org = self.create_organization(owner=self.user) self.team = self.create_team(organization=self.org, name="Mariachi Band") self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal") self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(f"{url}?org_slug={self.org.slug}&project_slug={self.project.slug}") assert resp.status_code == 200 self.assertTemplateUsed(resp, "sentry/setup-wizard.html") assert resp.context["enableProjectSelection"] is False cached = default_cache.get(key) assert len(cached.get("projects")) == 1 cached_project = cached.get("projects")[0] assert cached_project.get("id") == self.project.id def test_renders_selection_when_given_only_org_slug(self) -> None: self.org = self.create_organization(owner=self.user) self.team = self.create_team(organization=self.org, name="Mariachi Band") self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal") self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(f"{url}?org_slug={self.org.slug}") assert resp.status_code == 200 self.assertTemplateUsed(resp, "sentry/setup-wizard.html") assert resp.context["enableProjectSelection"] is True assert default_cache.get(key) == "test" def test_renders_selection_when_given_org_and_project_slug_and_project_not_in_org(self) -> None: self.org = self.create_organization(owner=self.user) self.project = self.create_project() self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(f"{url}?org_slug={self.org.slug}&project_slug={self.project.slug}") assert resp.status_code == 200 self.assertTemplateUsed(resp, "sentry/setup-wizard.html") assert resp.context["enableProjectSelection"] is True assert default_cache.get(key) == "test" def test_renders_selection_when_org_slug_cannot_be_found(self) -> None: self.org = self.create_organization(owner=self.user) self.project = self.create_project(organization=self.org) self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(f"{url}?org_slug=bad-slug&project_slug={self.project.slug}") assert resp.status_code == 200 self.assertTemplateUsed(resp, "sentry/setup-wizard.html") assert resp.context["enableProjectSelection"] is True assert default_cache.get(key) == "test" @override_settings(SENTRY_SIGNUP_URL="https://sentry.io/signup/") def test_redirect_to_signup(self) -> None: self.create_organization(owner=self.user) url = ( reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "xyz"}) + "?signup=1&test=other" ) resp = self.client.get(url) assert resp.status_code == 302 assert ( resp.headers["Location"] == "https://sentry.io/signup/?next=http%3A%2F%2Ftestserver%2Faccount%2Fsettings%2Fwizard%2Fxyz%2F&test=other" ) @override_settings(SENTRY_SIGNUP_URL="https://sentry.io/signup/") def test_redirect_to_login_if_no_query_param(self) -> None: self.create_organization(owner=self.user) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "xyz"}) resp = self.client.get(url) assert resp.status_code == 302 assert resp.headers["Location"] == "/auth/login/" def test_post_success(self) -> None: self.org = self.create_organization(owner=self.user) self.team = self.create_team(organization=self.org, name="Mariachi Band") self.project = self.create_project(organization=self.org, teams=[self.team], name="Bengal") # create another project to make sure only the submitted project is in the cache self.create_project(organization=self.org, teams=[self.team], name="Bengal2") self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.post( path=url, data={"organizationId": self.org.id, "projectId": self.project.id}, content_type="application/json", ) assert resp.status_code == 200 cached = default_cache.get(key) assert cached.get("apiKeys").get("scopes")[0] == "org:ci" # The submitted project should be the only one in the cache assert len(cached.get("projects")) == 1 cached_project = cached.get("projects")[0] assert cached_project.get("id") == self.project.id assert cached_project.get("status") == "active" assert cached_project.get("keys")[0].get("isActive") assert cached_project.get("organization").get("status").get("id") == "active" def test_post_bad_request(self) -> None: self.login_as(self.user) # missing organizationId url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.post( path=url, data={"projectId": 123}, content_type="application/json", ) assert resp.status_code == 400 # missing projectId url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.post( path=url, data={"organizationId": 123}, content_type="application/json", ) assert resp.status_code == 400 def test_post_project_not_found(self) -> None: self.org = self.create_organization(owner=self.user) self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.post( path=url, data={"organizationId": self.org.id, "projectId": 1234}, content_type="application/json", ) assert resp.status_code == 404 def test_organization_not_found(self) -> None: self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.post( path=url, data={"organizationId": 1234, "projectId": 1234}, content_type="application/json", ) assert resp.status_code == 404 def test_organization_without_membership(self) -> None: self.org = self.create_organization() self.project = self.create_project(organization=self.org) self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.post( path=url, data={"organizationId": self.org.id, "projectId": self.project.id}, content_type="application/json", ) assert resp.status_code == 404 def test_post_project_not_in_org(self) -> None: self.org = self.create_organization(owner=self.user) self.project = self.create_project() self.login_as(self.user) key = f"{SETUP_WIZARD_CACHE_KEY}abc" default_cache.set(key, "test", 600) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.post( path=url, data={"organizationId": self.org.id, "projectId": self.project.id}, content_type="application/json", ) assert resp.status_code == 404 @override_settings(SENTRY_SIGNUP_URL="https://sentry.io/signup/") def test_post_redirect_to_signup(self) -> None: self.create_organization(owner=self.user) url = ( reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "xyz"}) + "?signup=1&test=other" ) resp = self.client.post(url) assert resp.status_code == 302 assert ( resp.headers["Location"] == "https://sentry.io/signup/?next=http%3A%2F%2Ftestserver%2Faccount%2Fsettings%2Fwizard%2Fxyz%2F&test=other" ) @override_settings(SENTRY_SIGNUP_URL="https://sentry.io/signup/") def test_post_redirect_to_login_if_no_query_param(self) -> None: self.create_organization(owner=self.user) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "xyz"}) resp = self.client.post(url) assert resp.status_code == 302 assert resp.headers["Location"] == "/auth/login/" def test_options_request_cors_headers(self) -> None: self.org = self.create_organization(owner=self.user) self.project = self.create_project() url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) _ = self.client.options(url) self.login_as(self.user) resp = self.client.options(url) assert resp.status_code == 200 assert resp.headers["Content-Length"] == "0" assert "Access-Control-Allow-Origin" in resp.headers assert "Access-Control-Allow-Methods" in resp.headers @override_options( {"demo-mode.enabled": True, "demo-mode.users": [100], "demo-mode.orgs": [100]} ) def test_demo_user(self) -> None: demo_user = self.create_user("demo@example.com", id=100) self.create_organization(owner=self.user, id=100) self.login_as(demo_user) url = reverse("sentry-project-wizard-fetch", kwargs={"wizard_hash": "abc"}) resp = self.client.get(url) assert resp.status_code == 403
SetupWizard
python
walkccc__LeetCode
solutions/1980. Find Unique Binary String/1980.py
{ "start": 0, "end": 273 }
class ____: def findDifferentBinaryString(self, nums: list[str]) -> str: bitSize = len(nums[0]) maxNum = 1 << bitSize numsSet = {int(num, 2) for num in nums} for num in range(maxNum): if num not in numsSet: return f'{num:0>{bitSize}b}'
Solution
python
ipython__ipython
IPython/core/guarded_eval.py
{ "start": 47131, "end": 57474 }
class ____(dict): """A dict subclass that always returns the factory instance and claims to have any item.""" def __init__(self, factory, *args, **kwargs): super().__init__(*args, **kwargs) self._factory = factory def __getitem__(self, key): return self._factory() def __contains__(self, key): return True def _resolve_annotation( annotation: object | str, context: EvaluationContext, sig: Signature | None = None, func: Callable | None = None, node: ast.Call | None = None, ): """Resolve annotation created by user with `typing` module and custom objects.""" if annotation is None: return None annotation = _eval_annotation(annotation, context) origin = get_origin(annotation) if annotation is Self and func and hasattr(func, "__self__"): return func.__self__ elif origin is Literal: type_args = get_args(annotation) if len(type_args) == 1: return type_args[0] elif annotation is LiteralString: return "" elif annotation is AnyStr: index = None if func and hasattr(func, "__node__"): def_node = func.__node__ for i, arg in enumerate(def_node.args.args): if not arg.annotation: continue annotation = _eval_annotation(arg.annotation.id, context) if annotation is AnyStr: index = i break is_bound_method = ( isinstance(func, MethodType) and getattr(func, "__self__") is not None ) if index and is_bound_method: index -= 1 elif sig: for i, (key, value) in enumerate(sig.parameters.items()): if value.annotation is AnyStr: index = i break if index is None: return None if index < 0 or index >= len(node.args): return None return eval_node(node.args[index], context) elif origin is TypeGuard: return False elif origin is set or origin is list: # only one type argument allowed attributes = [ attr for attr in dir( _resolve_annotation(get_args(annotation)[0], context, sig, func, node) ) ] duck = _Duck(attributes=dict.fromkeys(attributes)) return _Duck( attributes=dict.fromkeys(dir(origin())), # items are not strrictly needed for set items=_GetItemDuck(lambda: duck), ) elif origin is tuple: # multiple type arguments return tuple( _resolve_annotation(arg, context, sig, func, node) for arg in get_args(annotation) ) elif origin is Union: # multiple type arguments attributes = [ attr for type_arg in get_args(annotation) for attr in dir(_resolve_annotation(type_arg, context, sig, func, node)) ] return _Duck(attributes=dict.fromkeys(attributes)) elif is_typeddict(annotation): return _Duck( attributes=dict.fromkeys(dir(dict())), items={ k: _resolve_annotation(v, context, sig, func, node) for k, v in annotation.__annotations__.items() }, ) elif hasattr(annotation, "_is_protocol"): return _Duck(attributes=dict.fromkeys(dir(annotation))) elif origin is Annotated: type_arg = get_args(annotation)[0] return _resolve_annotation(type_arg, context, sig, func, node) elif isinstance(annotation, NewType): return _eval_or_create_duck(annotation.__supertype__, context) elif isinstance(annotation, TypeAliasType): return _eval_or_create_duck(annotation.__value__, context) else: return _eval_or_create_duck(annotation, context) def _eval_node_name(node_id: str, context: EvaluationContext): policy = get_policy(context) if node_id in context.transient_locals: return context.transient_locals[node_id] if policy.allow_locals_access and node_id in context.locals: return context.locals[node_id] if policy.allow_globals_access and node_id in context.globals: return context.globals[node_id] if policy.allow_builtins_access and hasattr(builtins, node_id): # note: do not use __builtins__, it is implementation detail of cPython return getattr(builtins, node_id) if policy.allow_auto_import and context.auto_import: return context.auto_import(node_id) if not policy.allow_globals_access and not policy.allow_locals_access: raise GuardRejection( f"Namespace access not allowed in {context.evaluation} mode" ) else: raise NameError(f"{node_id} not found in locals, globals, nor builtins") def _eval_or_create_duck(duck_type, context: EvaluationContext): policy = get_policy(context) # if allow-listed builtin is on type annotation, instantiate it if policy.can_call(duck_type): return duck_type() # if custom class is in type annotation, mock it return _create_duck_for_heap_type(duck_type) def _create_duck_for_heap_type(duck_type): """Create an imitation of an object of a given type (a duck). Returns the duck or NOT_EVALUATED sentinel if duck could not be created. """ duck = ImpersonatingDuck() try: # this only works for heap types, not builtins duck.__class__ = duck_type return duck except TypeError: pass return NOT_EVALUATED SUPPORTED_EXTERNAL_GETITEM = { ("pandas", "core", "indexing", "_iLocIndexer"), ("pandas", "core", "indexing", "_LocIndexer"), ("pandas", "DataFrame"), ("pandas", "Series"), ("numpy", "ndarray"), ("numpy", "void"), } BUILTIN_GETITEM: set[InstancesHaveGetItem] = { dict, str, # type: ignore[arg-type] bytes, # type: ignore[arg-type] list, tuple, type, # for type annotations like list[str] _Duck, collections.defaultdict, collections.deque, collections.OrderedDict, collections.ChainMap, collections.UserDict, collections.UserList, collections.UserString, # type: ignore[arg-type] _DummyNamedTuple, _IdentitySubscript, } def _list_methods(cls, source=None): """For use on immutable objects or with methods returning a copy""" return [getattr(cls, k) for k in (source if source else dir(cls))] dict_non_mutating_methods = ("copy", "keys", "values", "items") list_non_mutating_methods = ("copy", "index", "count") set_non_mutating_methods = set(dir(set)) & set(dir(frozenset)) dict_keys: type[collections.abc.KeysView] = type({}.keys()) dict_values: type = type({}.values()) dict_items: type = type({}.items()) NUMERICS = {int, float, complex} ALLOWED_CALLS = { bytes, *_list_methods(bytes), bytes.__iter__, dict, *_list_methods(dict, dict_non_mutating_methods), dict.__iter__, dict_keys.__iter__, dict_values.__iter__, dict_items.__iter__, dict_keys.isdisjoint, list, *_list_methods(list, list_non_mutating_methods), list.__iter__, set, *_list_methods(set, set_non_mutating_methods), set.__iter__, frozenset, *_list_methods(frozenset), frozenset.__iter__, range, range.__iter__, str, *_list_methods(str), str.__iter__, tuple, *_list_methods(tuple), tuple.__iter__, bool, *_list_methods(bool), *NUMERICS, *[method for numeric_cls in NUMERICS for method in _list_methods(numeric_cls)], collections.deque, *_list_methods(collections.deque, list_non_mutating_methods), collections.deque.__iter__, collections.defaultdict, *_list_methods(collections.defaultdict, dict_non_mutating_methods), collections.defaultdict.__iter__, collections.OrderedDict, *_list_methods(collections.OrderedDict, dict_non_mutating_methods), collections.OrderedDict.__iter__, collections.UserDict, *_list_methods(collections.UserDict, dict_non_mutating_methods), collections.UserDict.__iter__, collections.UserList, *_list_methods(collections.UserList, list_non_mutating_methods), collections.UserList.__iter__, collections.UserString, *_list_methods(collections.UserString, dir(str)), collections.UserString.__iter__, collections.Counter, *_list_methods(collections.Counter, dict_non_mutating_methods), collections.Counter.__iter__, collections.Counter.elements, collections.Counter.most_common, object.__dir__, type.__dir__, _Duck.__dir__, } BUILTIN_GETATTR: set[MayHaveGetattr] = { *BUILTIN_GETITEM, set, frozenset, object, type, # `type` handles a lot of generic cases, e.g. numbers as in `int.real`. *NUMERICS, dict_keys, MethodDescriptorType, ModuleType, } BUILTIN_OPERATIONS = {*BUILTIN_GETATTR} EVALUATION_POLICIES = { "minimal": EvaluationPolicy( allow_builtins_access=True, allow_locals_access=False, allow_globals_access=False, allow_item_access=False, allow_attr_access=False, allowed_calls=set(), allow_any_calls=False, allow_all_operations=False, ), "limited": SelectivePolicy( allowed_getitem=BUILTIN_GETITEM, allowed_getitem_external=SUPPORTED_EXTERNAL_GETITEM, allowed_getattr=BUILTIN_GETATTR, allowed_getattr_external={ # pandas Series/Frame implements custom `__getattr__` ("pandas", "DataFrame"), ("pandas", "Series"), }, allowed_operations=BUILTIN_OPERATIONS, allow_builtins_access=True, allow_locals_access=True, allow_globals_access=True, allow_getitem_on_types=True, allowed_calls=ALLOWED_CALLS, ), "unsafe": EvaluationPolicy( allow_builtins_access=True, allow_locals_access=True, allow_globals_access=True, allow_attr_access=True, allow_item_access=True, allow_any_calls=True, allow_all_operations=True, ), } __all__ = [ "guarded_eval", "eval_node", "GuardRejection", "EvaluationContext", "_unbind_method", ]
_GetItemDuck
python
pytorch__pytorch
torch/testing/_internal/common_modules.py
{ "start": 6713, "end": 6936 }
class ____: """ Contains args and kwargs to pass as input to a function. """ __slots__ = ['args', 'kwargs'] def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs
FunctionInput
python
modin-project__modin
modin/core/execution/dispatching/factories/dispatcher.py
{ "start": 2855, "end": 14312 }
class ____(object): """ Class that routes IO-work to the factories. This class is responsible for keeping selected factory up-to-date and dispatching calls of IO-functions to its actual execution-specific implementations. """ __factory: factories.BaseFactory = None @classmethod def get_factory(cls) -> factories.BaseFactory: """Get current factory.""" if cls.__factory is None: from modin.pandas import _initialize_engine Engine.subscribe( lambda engine_parameter: _initialize_engine(engine_parameter.get()) ) Backend.subscribe(cls._update_factory) return_value = cls.__factory return return_value @classmethod def _get_prepared_factory_for_backend(cls, backend) -> factories.BaseFactory: """ Get factory for the specified backend. Parameters ---------- backend : str Backend name. Returns ------- factories.BaseFactory Factory for the specified backend. """ execution = Backend.get_execution_for_backend(backend) from modin.pandas import _initialize_engine _initialize_engine(execution.engine) factory_name = f"{execution.storage_format}On{execution.engine}Factory" experimental_factory_name = "Experimental" + factory_name try: factory = getattr(factories, factory_name, None) or getattr( factories, experimental_factory_name ) except AttributeError: if not IsExperimental.get(): # allow missing factories in experimental mode only msg = ( "Cannot find neither factory {} nor experimental factory {}. " + "Potential reason might be incorrect environment variable value for " + f"{StorageFormat.varname} or {Engine.varname}" ) raise FactoryNotFoundError( msg.format(factory_name, experimental_factory_name) ) factory = StubFactory.set_failing_name(factory_name) else: try: factory.prepare() except ModuleNotFoundError as err: raise ModuleNotFoundError( f"Make sure all required packages are installed: {str(err)}" ) from err return factory @classmethod def _update_factory(cls, *args): """ Update and prepare factory with a new one specified via Modin config. Parameters ---------- *args : iterable This parameters serves the compatibility purpose. Does not affect the result. """ cls.__factory = cls._get_prepared_factory_for_backend(Backend.get()) @classmethod def from_pandas( cls, df, backend: Union[str, NoDefault] = no_default ) -> BaseQueryCompiler: """ Create a Modin query compiler from a pandas DataFrame. Parameters ---------- df : pandas.DataFrame The pandas DataFrame to convert. backend : str or NoDefault, default: NoDefault The backend to use for the resulting query compiler. If NoDefault, use the current global default ``Backend`` from the Modin config. Returns ------- BaseQueryCompiler A Modin query compiler that wraps the input pandas DataFrame. """ return ( cls.get_factory() if backend is no_default else cls._get_prepared_factory_for_backend(backend) )._from_pandas(df) @classmethod @_inherit_docstrings(factories.BaseFactory._from_arrow) def from_arrow(cls, at): return cls.get_factory()._from_arrow(at) @classmethod @_inherit_docstrings(factories.BaseFactory._from_non_pandas) def from_non_pandas(cls, *args, **kwargs): return cls.get_factory()._from_non_pandas(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._from_interchange_dataframe) def from_interchange_dataframe(cls, *args, **kwargs): return cls.get_factory()._from_interchange_dataframe(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._from_ray) def from_ray(cls, ray_obj): return cls.get_factory()._from_ray(ray_obj) @classmethod @_inherit_docstrings(factories.BaseFactory._from_dask) def from_dask(cls, dask_obj): return cls.get_factory()._from_dask(dask_obj) @classmethod @_inherit_docstrings(factories.BaseFactory._from_map) def from_map(cls, func, iterable, *args, **kwargs): return cls.get_factory()._from_map(func, iterable, *args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_parquet) def read_parquet(cls, **kwargs): return cls.get_factory()._read_parquet(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_csv) def read_csv(cls, **kwargs): return cls.get_factory()._read_csv(**kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._read_csv_glob) def read_csv_glob(cls, **kwargs): return cls.get_factory()._read_csv_glob(**kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._read_pickle_glob) def read_pickle_glob(cls, **kwargs): return cls.get_factory()._read_pickle_glob(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_json) def read_json(cls, **kwargs): return cls.get_factory()._read_json(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_gbq) def read_gbq(cls, **kwargs): return cls.get_factory()._read_gbq(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_html) def read_html(cls, **kwargs): return cls.get_factory()._read_html(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_clipboard) def read_clipboard(cls, **kwargs): return cls.get_factory()._read_clipboard(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_excel) def read_excel(cls, **kwargs): return cls.get_factory()._read_excel(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_hdf) def read_hdf(cls, **kwargs): return cls.get_factory()._read_hdf(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_feather) def read_feather(cls, **kwargs): return cls.get_factory()._read_feather(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_stata) def read_stata(cls, **kwargs): return cls.get_factory()._read_stata(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_sas) def read_sas(cls, **kwargs): # pragma: no cover return cls.get_factory()._read_sas(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_pickle) def read_pickle(cls, **kwargs): return cls.get_factory()._read_pickle(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_sql) def read_sql(cls, **kwargs): return cls.get_factory()._read_sql(**kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._read_sql_distributed) def read_sql_distributed(cls, **kwargs): return cls.get_factory()._read_sql_distributed(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_fwf) def read_fwf(cls, **kwargs): return cls.get_factory()._read_fwf(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_sql_table) def read_sql_table(cls, **kwargs): return cls.get_factory()._read_sql_table(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_sql_query) def read_sql_query(cls, **kwargs): return cls.get_factory()._read_sql_query(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._read_spss) def read_spss(cls, **kwargs): return cls.get_factory()._read_spss(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_sql) def to_sql(cls, *args, **kwargs): return cls.get_factory()._to_sql(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_pickle) def to_pickle(cls, *args, **kwargs): return cls.get_factory()._to_pickle(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._to_pickle_glob) def to_pickle_glob(cls, *args, **kwargs): return cls.get_factory()._to_pickle_glob(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._read_parquet_glob) def read_parquet_glob(cls, *args, **kwargs): return cls.get_factory()._read_parquet_glob(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._to_parquet_glob) def to_parquet_glob(cls, *args, **kwargs): return cls.get_factory()._to_parquet_glob(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._read_json_glob) def read_json_glob(cls, *args, **kwargs): return cls.get_factory()._read_json_glob(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._to_json_glob) def to_json_glob(cls, *args, **kwargs): return cls.get_factory()._to_json_glob(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._read_xml_glob) def read_xml_glob(cls, *args, **kwargs): return cls.get_factory()._read_xml_glob(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._to_xml_glob) def to_xml_glob(cls, *args, **kwargs): return cls.get_factory()._to_xml_glob(*args, **kwargs) @classmethod @_inherit_docstrings(factories.PandasOnRayFactory._read_custom_text) def read_custom_text(cls, **kwargs): return cls.get_factory()._read_custom_text(**kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_csv) def to_csv(cls, *args, **kwargs): return cls.get_factory()._to_csv(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_json) def to_json(cls, *args, **kwargs): return cls.get_factory()._to_json(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_json) def to_json_series(cls, *args, **kwargs): return cls.get_factory()._to_json_series(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_xml) def to_xml(cls, *args, **kwargs): return cls.get_factory()._to_xml(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_parquet) def to_parquet(cls, *args, **kwargs): return cls.get_factory()._to_parquet(*args, **kwargs) @classmethod @_inherit_docstrings(factories.BaseFactory._to_ray) def to_ray(cls, modin_obj): return cls.get_factory()._to_ray(modin_obj) @classmethod @_inherit_docstrings(factories.BaseFactory._to_dask) def to_dask(cls, modin_obj): return cls.get_factory()._to_dask(modin_obj)
FactoryDispatcher
python
pandas-dev__pandas
asv_bench/benchmarks/hash_functions.py
{ "start": 930, "end": 1359 }
class ____: params = ["Int64", "Float64"] param_names = ["dtype"] def setup(self, dtype): self.ser = pd.Series(([1, pd.NA, 2] + list(range(100_000))) * 3, dtype=dtype) self.ser_unique = pd.Series(list(range(300_000)) + [pd.NA], dtype=dtype) def time_unique_with_duplicates(self, exponent): pd.unique(self.ser) def time_unique(self, exponent): pd.unique(self.ser_unique)
Unique
python
getsentry__sentry
src/sentry/auth/providers/saml2/activedirectory/apps.py
{ "start": 89, "end": 350 }
class ____(AppConfig): name = "sentry.auth.providers.saml2.activedirectory" def ready(self) -> None: from sentry.auth import register from .provider import ActiveDirectorySAML2Provider register(ActiveDirectorySAML2Provider)
Config
python
huggingface__transformers
tests/models/edgetam/test_modeling_edgetam.py
{ "start": 17710, "end": 29162 }
class ____(unittest.TestCase): def setUp(self): super().setUp() self.model = EdgeTamModel.from_pretrained("yonigozlan/EdgeTAM-hf").to(torch.float32) self.processor = Sam2Processor.from_pretrained("yonigozlan/EdgeTAM-hf") self.model.to(torch_device) self.model.eval() def tearDown(self): super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() backend_empty_cache(torch_device) def test_inference_mask_generation_one_point_multimask(self): raw_image = prepare_image() input_points = [[[[500, 375]]]] input_labels = [[[1]]] inputs = self.processor( images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt" ).to(torch_device) with torch.no_grad(): outputs = self.model(**inputs) self.assertEqual(outputs.iou_scores.shape, (1, 1, 3)) self.assertEqual(outputs.pred_masks.shape, (1, 1, 3, 256, 256)) sorted_indices = torch.argsort(outputs.iou_scores.squeeze(), descending=True) scores = outputs.iou_scores.squeeze()[sorted_indices] masks_logits = outputs.pred_masks.squeeze()[sorted_indices][0, :3, :3] torch.testing.assert_close( scores, torch.tensor([0.7621, 0.4859, 0.0461]).to(torch_device), atol=1e-4, rtol=1e-4 ) torch.testing.assert_close( masks_logits, torch.tensor( [[-19.5483, -22.3549, -26.0962], [-18.1821, -23.4761, -24.2262], [-20.3549, -24.5518, -22.7232]] ).to(torch_device), atol=1e-4, rtol=1e-4, ) def test_inference_mask_generation_one_point_no_multimask(self): raw_image = prepare_image() input_points = [[[[500, 375]]]] input_labels = [[[1]]] inputs = self.processor( images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt" ).to(torch_device) with torch.no_grad(): outputs = self.model(**inputs, multimask_output=False) self.assertEqual(outputs.iou_scores.shape, (1, 1, 1)) self.assertEqual(outputs.pred_masks.shape, (1, 1, 1, 256, 256)) scores = outputs.iou_scores.squeeze((0, 1)) masks_logits = outputs.pred_masks.squeeze((0, 1))[0, :3, :3] torch.testing.assert_close(scores, torch.tensor([0.7621]).to(torch_device), atol=1e-4, rtol=1e-4) torch.testing.assert_close( masks_logits, torch.tensor( [[-19.5483, -22.3549, -26.0962], [-18.1821, -23.4761, -24.2262], [-20.3549, -24.5518, -22.7232]] ).to(torch_device), atol=1e-4, rtol=1e-4, ) def test_inference_mask_generation_batched_images_multi_points(self): raw_image1 = prepare_image() raw_image2 = prepare_dog_img() input_points = [[[[500, 375]]], [[[770, 200], [730, 120]]]] input_labels = [[[1]], [[1, 0]]] inputs = self.processor( images=[raw_image1, raw_image2], input_points=input_points, input_labels=input_labels, return_tensors="pt" ).to(torch_device) with torch.no_grad(): outputs = self.model(**inputs) self.assertEqual(outputs.iou_scores.shape, (2, 1, 3)) self.assertEqual(outputs.pred_masks.shape, (2, 1, 3, 256, 256)) sorted_indices = torch.argsort(outputs.iou_scores[0].squeeze(), descending=True) scores1 = outputs.iou_scores[0].squeeze()[sorted_indices] masks_logits1 = outputs.pred_masks[0].squeeze()[sorted_indices][0, :3, :3] sorted_indices = torch.argsort(outputs.iou_scores[1].squeeze(), descending=True) scores2 = outputs.iou_scores[1].squeeze()[sorted_indices] masks_logits2 = outputs.pred_masks[1].squeeze()[sorted_indices][0, :3, :3] torch.testing.assert_close( scores1, torch.tensor([0.7490, 0.4685, 0.0463]).to(torch_device), atol=1e-4, rtol=1e-4 ) torch.testing.assert_close( masks_logits1, torch.tensor( [[-19.1423, -21.6488, -25.6816], [-17.8018, -22.6512, -23.5699], [-19.9140, -23.6919, -22.3147]] ).to(torch_device), atol=1e-4, rtol=1e-4, ) torch.testing.assert_close( scores2, torch.tensor([0.7225, 0.6515, 0.6350]).to(torch_device), atol=1e-4, rtol=1e-4 ) torch.testing.assert_close( masks_logits2, torch.tensor([[-8.8259, -7.7961, -9.3665], [-8.2648, -8.7771, -9.1390], [-9.5951, -8.3995, -9.0599]]).to( torch_device ), atol=1e-4, rtol=1e-4, ) def test_inference_mask_generation_batched_images_batched_points_multi_points(self): raw_image1 = prepare_image() raw_image2 = prepare_groceries_image() input_points = [[[[500, 375]], [[650, 750]]], [[[400, 300]], [[630, 300], [550, 300]]]] input_labels = [[[1], [1]], [[1], [1, 1]]] inputs = self.processor( images=[raw_image1, raw_image2], input_points=input_points, input_labels=input_labels, return_tensors="pt" ).to(torch_device) with torch.no_grad(): outputs = self.model(**inputs, multimask_output=False) self.assertEqual(outputs.iou_scores.shape, (2, 2, 1)) self.assertEqual(outputs.pred_masks.shape, (2, 2, 1, 256, 256)) torch.testing.assert_close( outputs.iou_scores, torch.tensor([[[0.7490], [0.9397]], [[0.7952], [0.8723]]]).to(torch_device), atol=1e-4, rtol=1e-4, ) torch.testing.assert_close( outputs.pred_masks[:, :, :, :2, :2], torch.tensor( [ [[[[-19.1423, -21.6488], [-17.8018, -22.6512]]], [[[-7.1591, -9.8201], [-7.4133, -9.2781]]]], [[[[-16.7645, -15.2790], [-16.1805, -16.2937]]], [[[-8.5934, -8.4215], [-8.1873, -8.3722]]]], ] ).to(torch_device), atol=1e-4, rtol=1e-4, ) def test_inference_batched_images_batched_boxes(self): raw_image1 = prepare_image() raw_image2 = prepare_groceries_image() input_boxes = [ [[75, 275, 1725, 850], [425, 600, 700, 875], [1375, 550, 1650, 800], [1240, 675, 1400, 750]], [[450, 170, 520, 350], [350, 190, 450, 350], [500, 170, 580, 350], [580, 170, 640, 350]], ] inputs = self.processor(images=[raw_image1, raw_image2], input_boxes=input_boxes, return_tensors="pt").to( torch_device ) with torch.no_grad(): outputs = self.model(**inputs, multimask_output=False) self.assertEqual(outputs.iou_scores.shape, (2, 4, 1)) self.assertEqual(outputs.pred_masks.shape, (2, 4, 1, 256, 256)) torch.testing.assert_close( outputs.iou_scores, torch.tensor([[[0.9773], [0.9415], [0.9683], [0.8792]], [[0.9721], [0.9852], [0.9812], [0.9760]]]).to( torch_device ), atol=1e-4, rtol=1e-4, ) torch.testing.assert_close( outputs.pred_masks[:, :, :, :2, :2], torch.tensor( [ [ [[[-12.6412, -12.0553], [-11.8415, -13.1696]]], [[[-16.0378, -19.9641], [-15.4939, -19.0260]]], [[[-18.8254, -23.6185], [-17.7889, -23.2116]]], [[[-25.7024, -29.8722], [-22.9264, -30.0557]]], ], [ [[[-19.0264, -17.0396], [-16.9458, -16.3287]]], [[[-20.9671, -19.2132], [-18.5827, -18.0511]]], [[[-22.4642, -19.7389], [-19.4541, -19.4717]]], [[[-21.9226, -18.6297], [-18.9272, -18.8151]]], ], ] ).to(torch_device), atol=1e-4, rtol=1e-4, ) def test_inference_mask_generation_from_existing_points_and_mask(self): raw_image = prepare_image() input_points = [[[[500, 375]]]] input_labels = [[[1]]] original_inputs = self.processor( images=raw_image, input_points=input_points, input_labels=input_labels, return_tensors="pt" ).to(torch_device) with torch.no_grad(): outputs = self.model(**original_inputs) # best mask to use as input for new points mask_input = outputs.pred_masks[:, :, torch.argmax(outputs.iou_scores)] new_input_points = [[[[500, 375], [1125, 625]]]] new_input_labels = [[[1, 1]]] inputs = self.processor( input_points=new_input_points, input_labels=new_input_labels, original_sizes=original_inputs["original_sizes"], return_tensors="pt", ).to(torch_device) with torch.no_grad(): outputs = self.model( **inputs, input_masks=mask_input, image_embeddings=outputs.image_embeddings, multimask_output=False, ) self.assertEqual(outputs.iou_scores.shape, (1, 1, 1)) self.assertEqual(outputs.pred_masks.shape, (1, 1, 1, 256, 256)) scores = outputs.iou_scores.squeeze((0, 1)) masks_logits = outputs.pred_masks.squeeze((0, 1))[0, :3, :3] torch.testing.assert_close(scores, torch.tensor([0.9431]).to(torch_device), atol=1e-4, rtol=1e-4) torch.testing.assert_close( masks_logits, torch.tensor([[-4.1968, -4.9034, -6.0680], [-4.4053, -5.1200, -5.8580], [-4.3920, -5.5096, -5.8166]]).to( torch_device ), atol=1e-4, rtol=1e-4, ) # with negative point new_input_points = [[[[500, 375], [1125, 625]]]] new_input_labels = [[[1, 0]]] inputs = self.processor( input_points=new_input_points, input_labels=new_input_labels, original_sizes=original_inputs["original_sizes"], return_tensors="pt", ).to(torch_device) with torch.no_grad(): outputs = self.model( **inputs, input_masks=mask_input, image_embeddings=outputs.image_embeddings, multimask_output=False, ) self.assertEqual(outputs.iou_scores.shape, (1, 1, 1)) self.assertEqual(outputs.pred_masks.shape, (1, 1, 1, 256, 256)) scores = outputs.iou_scores.squeeze((0, 1)) masks_logits = outputs.pred_masks.squeeze((0, 1))[0, :3, :3] torch.testing.assert_close(scores, torch.tensor([0.9695]).to(torch_device), atol=1e-4, rtol=1e-4) torch.testing.assert_close( masks_logits, torch.tensor( [[-14.3212, -15.4295, -17.4482], [-13.2246, -15.9468, -17.1341], [-15.1678, -16.4498, -14.7385]] ).to(torch_device), atol=1e-4, rtol=1e-4, ) def test_dummy_pipeline_generation(self): generator = pipeline("mask-generation", model="yonigozlan/EdgeTAM-hf", device=torch_device) raw_image = prepare_image() _ = generator(raw_image, points_per_batch=64)
EdgeTamModelIntegrationTest
python
getsentry__sentry
src/sentry/api/endpoints/organization_traces.py
{ "start": 36537, "end": 40751 }
class ____: project: int | None = None name: str | None = None duration: float | None = None def format_trace_result( trace: GetTracesResponse.Trace, projects_map: dict[int, str], ) -> TraceResult: result: TraceResult = { "trace": "", "numErrors": 0, "numOccurrences": 0, "matchingSpans": 0, "numSpans": 0, "project": None, "name": None, "rootDuration": None, "duration": 0, "start": 0, "end": 0, "breakdowns": [], } earliest_span = TraceInfo() frontend_span = TraceInfo() root_span = TraceInfo() for attribute in trace.attributes: if attribute.key == TraceAttribute.Key.KEY_TRACE_ID: result["trace"] = get_attr_val_str(attribute) elif attribute.key == TraceAttribute.Key.KEY_START_TIMESTAMP: result["start"] = int(get_attr_val_double(attribute) * 1000) elif attribute.key == TraceAttribute.Key.KEY_END_TIMESTAMP: result["end"] = int(get_attr_val_double(attribute) * 1000) elif attribute.key == TraceAttribute.Key.KEY_TOTAL_ITEM_COUNT: result["numSpans"] = get_attr_val_int(attribute) elif attribute.key == TraceAttribute.Key.KEY_FILTERED_ITEM_COUNT: result["matchingSpans"] = get_attr_val_int(attribute) # earliest span elif attribute.key == TraceAttribute.Key.KEY_EARLIEST_SPAN_PROJECT_ID: earliest_span.project = get_attr_val_int(attribute) elif attribute.key == TraceAttribute.Key.KEY_EARLIEST_SPAN_NAME: earliest_span.name = get_attr_val_str(attribute) elif attribute.key == TraceAttribute.Key.KEY_EARLIEST_SPAN_DURATION_MS: earliest_span.duration = float(get_attr_val_int(attribute)) # frontend span elif attribute.key == TraceAttribute.Key.KEY_EARLIEST_FRONTEND_SPAN_PROJECT_ID: frontend_span.project = get_attr_val_int(attribute) elif attribute.key == TraceAttribute.Key.KEY_EARLIEST_FRONTEND_SPAN: frontend_span.name = get_attr_val_str(attribute) elif attribute.key == TraceAttribute.Key.KEY_EARLIEST_FRONTEND_SPAN_DURATION_MS: frontend_span.duration = float(get_attr_val_int(attribute)) # root span elif attribute.key == TraceAttribute.Key.KEY_ROOT_SPAN_PROJECT_ID: root_span.project = get_attr_val_int(attribute) elif attribute.key == TraceAttribute.Key.KEY_ROOT_SPAN_NAME: root_span.name = get_attr_val_str(attribute) elif attribute.key == TraceAttribute.Key.KEY_ROOT_SPAN_DURATION_MS: root_span.duration = float(get_attr_val_int(attribute)) else: raise ValueError(f"Unexpected attribute found: {attribute.key}") if not result["start"]: raise ValueError(f"Expected {TraceAttribute.Key.KEY_START_TIMESTAMP} to be present") if not result["end"]: raise ValueError(f"Expected {TraceAttribute.Key.KEY_END_TIMESTAMP} to be present") result["duration"] = result["end"] - result["start"] # if we see any of these spans, use them to fill in the result # on a best-effort basis for span in [root_span, frontend_span, earliest_span]: if span.project in projects_map and span.name: result["project"] = projects_map[span.project] result["name"] = span.name result["rootDuration"] = span.duration break return result def validate_attribute_type(attribute: TraceAttribute, type: AttributeKey.Type.ValueType): if attribute.type != type: raise ValueError(f"Expected {attribute.key} to be of type {type} but got {attribute.type}") def get_attr_val_str(attribute: TraceAttribute) -> str: validate_attribute_type(attribute, AttributeKey.Type.TYPE_STRING) return attribute.value.val_str def get_attr_val_double(attribute: TraceAttribute) -> float: validate_attribute_type(attribute, AttributeKey.Type.TYPE_DOUBLE) return attribute.value.val_double def get_attr_val_int(attribute: TraceAttribute) -> int: validate_attribute_type(attribute, AttributeKey.Type.TYPE_INT) return attribute.value.val_int
TraceInfo
python
walkccc__LeetCode
solutions/555. Split Concatenated Strings/555.py
{ "start": 0, "end": 380 }
class ____: def splitLoopedString(self, strs: list[str]) -> str: ans = '' sortedStrs = [max(s, s[::-1]) for s in strs] for i, sortedStr in enumerate(sortedStrs): for s in (sortedStr, sortedStr[::-1]): for j in range(len(s) + 1): ans = max( ans, s[j:] + ''.join(sortedStrs[i + 1:] + sortedStrs[:i]) + s[:j]) return ans
Solution
python
miyuchina__mistletoe
mistletoe/span_token.py
{ "start": 7079, "end": 7527 }
class ____(SpanToken): """ Line break token: hard or soft. This is an inline token without children. Attributes: soft (bool): true if this is a soft line break. """ repr_attributes = ("soft",) pattern = re.compile(r'( *|\\)\n') parse_inner = False parse_group = 0 def __init__(self, match): self.content = match.group(1) self.soft = not self.content.startswith((' ', '\\'))
LineBreak
python
great-expectations__great_expectations
great_expectations/render/renderer/site_builder.py
{ "start": 1304, "end": 13703 }
class ____: """SiteBuilder builds data documentation for the project defined by a DataContext. A data documentation site consists of HTML pages for expectation suites, profiling and validation results, and an index.html page that links to all the pages. The exact behavior of SiteBuilder is controlled by configuration in the DataContext's great_expectations.yml file. Users can specify: * which datasources to document (by default, all) * whether to include expectations, validations and profiling results sections (by default, all) * where the expectations and validations should be read from (filesystem or S3) * where the HTML files should be written (filesystem or S3) * which renderer and view class should be used to render each section Here is an example of a minimal configuration for a site:: local_site: class_name: SiteBuilder store_backend: class_name: TupleS3StoreBackend bucket: data_docs.my_company.com prefix: /data_docs/ A more verbose configuration can also control individual sections and override renderers, views, and stores:: local_site: class_name: SiteBuilder store_backend: class_name: TupleS3StoreBackend bucket: data_docs.my_company.com prefix: /data_docs/ site_index_builder: class_name: DefaultSiteIndexBuilder # Verbose version: # site_index_builder: # module_name: great_expectations.render.builder # class_name: DefaultSiteIndexBuilder # renderer: # module_name: great_expectations.render.renderer # class_name: SiteIndexPageRenderer # view: # module_name: great_expectations.render.view # class_name: DefaultJinjaIndexPageView site_section_builders: # Minimal specification expectations: class_name: DefaultSiteSectionBuilder source_store_name: expectation_store renderer: module_name: great_expectations.render.renderer class_name: ExpectationSuitePageRenderer # More verbose specification with optional arguments validations: module_name: great_expectations.data_context.render class_name: DefaultSiteSectionBuilder source_store_name: local_validation_store renderer: module_name: great_expectations.render.renderer class_name: SiteIndexPageRenderer view: module_name: great_expectations.render.view class_name: DefaultJinjaIndexPageView """ def __init__( # noqa: C901, PLR0912, PLR0913 # FIXME CoP self, data_context: AbstractDataContext, store_backend, site_name=None, site_index_builder=None, show_how_to_buttons=True, site_section_builders=None, runtime_environment=None, cloud_mode=False, # <GX_RENAME> Deprecated 0.15.37 ge_cloud_mode=False, **kwargs, ) -> None: self.site_name = site_name self.data_context = data_context self.store_backend = store_backend self.show_how_to_buttons = show_how_to_buttons if ge_cloud_mode: cloud_mode = ge_cloud_mode self.cloud_mode = cloud_mode self.ge_cloud_mode = cloud_mode self.data_context_id = data_context.variables.data_context_id # set custom_styles_directory if present custom_styles_directory = None plugins_directory = data_context.plugins_directory if plugins_directory and os.path.isdir( # noqa: PTH112 # FIXME CoP os.path.join( # noqa: PTH118 # FIXME CoP plugins_directory, "custom_data_docs", "styles" ) ): custom_styles_directory = os.path.join( # noqa: PTH118 # FIXME CoP plugins_directory, "custom_data_docs", "styles" ) # set custom_views_directory if present custom_views_directory = None if plugins_directory and os.path.isdir( # noqa: PTH112 # FIXME CoP os.path.join(plugins_directory, "custom_data_docs", "views") # noqa: PTH118 # FIXME CoP ): custom_views_directory = os.path.join( # noqa: PTH118 # FIXME CoP plugins_directory, "custom_data_docs", "views" ) if site_index_builder is None: site_index_builder = {"class_name": "DefaultSiteIndexBuilder"} # The site builder is essentially a frontend store. We'll open up # three types of backends using the base # type of the configuration defined in the store_backend section if cloud_mode: self.target_store = JsonSiteStore( store_backend=store_backend, runtime_environment=runtime_environment ) else: self.target_store = HtmlSiteStore( store_backend=store_backend, runtime_environment=runtime_environment ) default_site_section_builders_config = { "expectations": { "class_name": "DefaultSiteSectionBuilder", "source_store_name": data_context.expectations_store_name, "renderer": {"class_name": "ExpectationSuitePageRenderer"}, }, "validations": { "class_name": "DefaultSiteSectionBuilder", "source_store_name": data_context.validation_results_store_name, "renderer": {"class_name": "ValidationResultsPageRenderer"}, "validation_results_limit": site_index_builder.get("validation_results_limit"), }, "profiling": { "class_name": "DefaultSiteSectionBuilder", "source_store_name": data_context.validation_results_store_name, "renderer": {"class_name": "ProfilingResultsPageRenderer"}, }, } if site_section_builders is None: site_section_builders = default_site_section_builders_config else: site_section_builders = nested_update( default_site_section_builders_config, site_section_builders ) # set default run_name_filter if site_section_builders.get("validations", "None") not in FALSEY_YAML_STRINGS: if site_section_builders["validations"].get("run_name_filter") is None: site_section_builders["validations"]["run_name_filter"] = { "not_includes": "profiling" } if site_section_builders.get("profiling", "None") not in FALSEY_YAML_STRINGS: if site_section_builders["profiling"].get("run_name_filter") is None: site_section_builders["profiling"]["run_name_filter"] = {"includes": "profiling"} self.site_section_builders = {} for site_section_name, site_section_config in site_section_builders.items(): if not site_section_config or site_section_config in FALSEY_YAML_STRINGS: continue module_name = ( site_section_config.get("module_name") or "great_expectations.render.renderer.site_builder" ) self.site_section_builders[site_section_name] = instantiate_class_from_config( config=site_section_config, runtime_environment={ "data_context": data_context, "target_store": self.target_store, "custom_styles_directory": custom_styles_directory, "custom_views_directory": custom_views_directory, "data_context_id": self.data_context_id, "show_how_to_buttons": self.show_how_to_buttons, "cloud_mode": self.cloud_mode, }, config_defaults={ "name": site_section_name, "module_name": module_name, }, ) if not self.site_section_builders[site_section_name]: raise exceptions.ClassInstantiationError( module_name=module_name, package_name=None, class_name=site_section_config["class_name"], ) module_name = ( site_index_builder.get("module_name") or "great_expectations.render.renderer.site_builder" ) class_name = site_index_builder.get("class_name") or "DefaultSiteIndexBuilder" self.site_index_builder = instantiate_class_from_config( config=site_index_builder, runtime_environment={ "data_context": data_context, "custom_styles_directory": custom_styles_directory, "custom_views_directory": custom_views_directory, "show_how_to_buttons": self.show_how_to_buttons, "target_store": self.target_store, "site_name": self.site_name, "data_context_id": self.data_context_id, "source_stores": { section_name: section_config.get("source_store_name") for (section_name, section_config) in site_section_builders.items() if section_config not in FALSEY_YAML_STRINGS }, "site_section_builders_config": site_section_builders, "cloud_mode": self.cloud_mode, }, config_defaults={ "name": "site_index_builder", "module_name": module_name, "class_name": class_name, }, ) if not self.site_index_builder: raise exceptions.ClassInstantiationError( module_name=module_name, package_name=None, class_name=site_index_builder["class_name"], ) def clean_site(self) -> None: self.target_store.clean_site() def build(self, resource_identifiers=None, build_index: bool = True): """ :param resource_identifiers: a list of resource identifiers (ExpectationSuiteIdentifier, ValidationResultIdentifier). If specified, rebuild HTML(or other views the data docs site renders) only for the resources in this list. This supports incremental build of data docs sites (e.g., when a new validation result is created) and avoids full rebuild. :param build_index: a flag if False, skips building the index page :return: """ # copy static assets for site_section_builder in self.site_section_builders.values(): site_section_builder.build(resource_identifiers=resource_identifiers) # GX Cloud supports JSON Site Data Docs # Skip static assets, indexing if self.cloud_mode: return self.target_store.copy_static_assets() _, index_links_dict = self.site_index_builder.build(build_index=build_index) return ( self.get_resource_url(only_if_exists=False), index_links_dict, ) def get_resource_url(self, resource_identifier=None, only_if_exists=True) -> Optional[str]: """ Return the URL of the HTML document that renders a resource (e.g., an expectation suite or a validation result). :param resource_identifier: ExpectationSuiteIdentifier, ValidationResultIdentifier or any other type's identifier. The argument is optional - when not supplied, the method returns the URL of the index page. :return: URL (string) """ return self.target_store.get_url_for_resource( resource_identifier=resource_identifier, only_if_exists=only_if_exists )
SiteBuilder
python
readthedocs__readthedocs.org
readthedocs/projects/views/mixins.py
{ "start": 406, "end": 1648 }
class ____: """ Mixin class for constructing model views for project dashboard. This mixin class is used for model views on models that have a relation to the :py:class:`Project` model. :cvar project_lookup_url_kwarg: URL kwarg to use in project lookup :cvar project_lookup_field: Query field for project relation :cvar project_context_object_name: Context object name for project """ project_lookup_url_kwarg = "project_slug" project_lookup_field = "project" project_context_object_name = "project" def get_project_queryset(self): return Project.objects.for_admin_user(user=self.request.user) def get_project(self): if self.project_lookup_url_kwarg not in self.kwargs: return None return get_object_or_404( self.get_project_queryset(), slug=self.kwargs[self.project_lookup_url_kwarg], ) def get_queryset(self): return self.model.objects.filter(**{self.project_lookup_field: self.get_project()}) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context[self.project_context_object_name] = self.get_project() return context
ProjectRelationMixin
python
FactoryBoy__factory_boy
factory/base.py
{ "start": 23298, "end": 23936 }
class ____(Factory): """Factory for list-like classes.""" class Meta: abstract = True @classmethod def _build(cls, model_class, *args, **kwargs): if args: raise ValueError( "ListFactory %r does not support Meta.inline_args." % cls) # kwargs are constructed from a list, their insertion order matches the list # order, no additional sorting is required. values = kwargs.values() return model_class(values) @classmethod def _create(cls, model_class, *args, **kwargs): return cls._build(model_class, *args, **kwargs)
BaseListFactory
python
python__mypy
mypy/visitor.py
{ "start": 8009, "end": 8972 }
class ____(Generic[T]): @abstractmethod def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T: pass @abstractmethod def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T: pass @abstractmethod def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T: pass @abstractmethod def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T: pass @abstractmethod def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T: pass @abstractmethod def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T: pass @abstractmethod def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T: pass @abstractmethod def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T: pass @trait @mypyc_attr(allow_interpreted_subclasses=True)
PatternVisitor
python
realpython__materials
python-protocol/adder_v1.py
{ "start": 148, "end": 366 }
class ____: def add(self, x, y): return x + y def add(adder: Adder) -> None: print(adder.add(2, 3)) add(IntAdder()) add(FloatAdder()) for adder in [IntAdder(), FloatAdder()]: add(adder)
FloatAdder
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 17960, "end": 18038 }
class ____(RootModel[int]): root: Annotated[int, Field(ge=0, title="Id")]
Id
python
lxml__lxml
doc/s5/ep2008/atom.py
{ "start": 13211, "end": 13435 }
class ____(_EntryElement): """ Represents authors and contributors """ email = _text_element_property('email') uri = _text_element_property('uri') name = _text_element_property('name')
PersonElement
python
viewflow__viewflow
viewflow/forms/renderers.py
{ "start": 24594, "end": 25283 }
class ____(Column): def __init__(self, title, *elements, **kwargs): self.title = title super().__init__(*elements, **kwargs) def append(self, layout: FormLayout, form: forms.Form, root: ElementTree.Element): wrapper = ElementTree.SubElement( root, "div", { "class": "vf-form__formset", }, ) title = ElementTree.SubElement( wrapper, "h3", { "class": "mdc-typography--subheading2 vf-form__formset-header", }, ) title.text = force_str(self.title) super().append(layout, form, wrapper)
FieldSet
python
google__jax
jax/_src/state/types.py
{ "start": 8746, "end": 12014 }
class ____: ref: Any transforms: tuple[Transform, ...] @property def is_dynamic_size(self): return any(not isinstance(i, int) for i in self.shape) @property def shape(self) -> tuple[int | Array, ...]: unprocessed, shape = 0, None # We first go backwards to find the first transform that knows its output # shape. It's possible none of them do! for unprocessed, t in enumerate(reversed(self.transforms), 1): if (shape := t.transform_shape(None)) is not None: unprocessed -= 1 break if shape is None: shape = self.ref.shape if not unprocessed: return shape # If there are any unprocessed transforms left, we apply them to the shape # we've found previously. for t in self.transforms[-unprocessed:]: shape = t.transform_shape(shape) assert shape is not None return shape @property def dtype(self): # The structure of this method is analogous to `shape`. See comments there. unprocessed, dtype = 0, None for unprocessed, t in enumerate(reversed(self.transforms), 1): if (dtype := t.transform_dtype(None)) is not None: unprocessed -= 1 break if dtype is None: dtype = self.ref.dtype if not unprocessed: return dtype for t in self.transforms[-unprocessed:]: dtype = t.transform_dtype(dtype) assert dtype is not None return dtype ndim = property(lambda self: len(self.shape)) size = property(lambda self: math.prod(self.shape)) T = property(lambda self: self.transpose(*reversed(range(self.ndim)))) @property def at(self) -> RefIndexer: return RefIndexer(self) def bitcast(self, dtype): return TransformedRef( self.ref, (*self.transforms, RefBitcaster.from_ref_new_dtype(self, dtype)), ) def reshape(self, *shape): return TransformedRef( self.ref, (*self.transforms, RefReshaper.from_ref_new_shape(self, *shape)), ) def transpose(self, *permutation): transposer = RefTransposer.from_ref_new_permutation(self, *permutation) return TransformedRef(self.ref, (*self.transforms, transposer)) def set(self, value, idx=()): from jax._src.state.primitives import ref_set # pytype: disable=import-error return ref_set(self, idx, value) def swap(self, value, idx=()): from jax._src.state.primitives import ref_swap # pytype: disable=import-error return ref_swap(self, idx, value) def get(self, idx=()): from jax._src.state.primitives import ref_get # pytype: disable=import-error return ref_get(self, idx) def __getattr__(self, name): return getattr(self.ref, name) def __getitem__(self, slc): from jax._src.state.primitives import ref_get # pytype: disable=import-error return ref_get(self, slc) def __setitem__(self, slc, value): from jax._src.state.primitives import ref_set # pytype: disable=import-error return ref_set(self, slc, value) def get_transforms_shape( ts: Sequence[Transform], shape: tuple[int | Array, ...] ) -> tuple[int | Array, ...]: for t in ts: shape = t.transform_shape(shape) # type: ignore assert shape is not None return shape # We need an aval for `Ref`s so we can represent `get` and `swap` in Jaxprs.
TransformedRef
python
zarr-developers__zarr-python
src/zarr/core/metadata/v3.py
{ "start": 6717, "end": 17249 }
class ____(Metadata): shape: tuple[int, ...] data_type: ZDType[TBaseDType, TBaseScalar] chunk_grid: ChunkGrid chunk_key_encoding: ChunkKeyEncoding fill_value: Any codecs: tuple[Codec, ...] attributes: dict[str, Any] = field(default_factory=dict) dimension_names: tuple[str | None, ...] | None = None zarr_format: Literal[3] = field(default=3, init=False) node_type: Literal["array"] = field(default="array", init=False) storage_transformers: tuple[dict[str, JSON], ...] extra_fields: dict[str, AllowedExtraField] def __init__( self, *, shape: Iterable[int], data_type: ZDType[TBaseDType, TBaseScalar], chunk_grid: dict[str, JSON] | ChunkGrid | NamedConfig[str, Any], chunk_key_encoding: ChunkKeyEncodingLike, fill_value: object, codecs: Iterable[Codec | dict[str, JSON] | NamedConfig[str, Any] | str], attributes: dict[str, JSON] | None, dimension_names: DimensionNames, storage_transformers: Iterable[dict[str, JSON]] | None = None, extra_fields: Mapping[str, AllowedExtraField] | None = None, ) -> None: """ Because the class is a frozen dataclass, we set attributes using object.__setattr__ """ shape_parsed = parse_shapelike(shape) chunk_grid_parsed = ChunkGrid.from_dict(chunk_grid) chunk_key_encoding_parsed = parse_chunk_key_encoding(chunk_key_encoding) dimension_names_parsed = parse_dimension_names(dimension_names) # Note: relying on a type method is numpy-specific fill_value_parsed = data_type.cast_scalar(fill_value) attributes_parsed = parse_attributes(attributes) codecs_parsed_partial = parse_codecs(codecs) storage_transformers_parsed = parse_storage_transformers(storage_transformers) extra_fields_parsed = parse_extra_fields(extra_fields) array_spec = ArraySpec( shape=shape_parsed, dtype=data_type, fill_value=fill_value_parsed, config=ArrayConfig.from_dict({}), # TODO: config is not needed here. prototype=default_buffer_prototype(), # TODO: prototype is not needed here. ) codecs_parsed = tuple(c.evolve_from_array_spec(array_spec) for c in codecs_parsed_partial) validate_codecs(codecs_parsed_partial, data_type) object.__setattr__(self, "shape", shape_parsed) object.__setattr__(self, "data_type", data_type) object.__setattr__(self, "chunk_grid", chunk_grid_parsed) object.__setattr__(self, "chunk_key_encoding", chunk_key_encoding_parsed) object.__setattr__(self, "codecs", codecs_parsed) object.__setattr__(self, "dimension_names", dimension_names_parsed) object.__setattr__(self, "fill_value", fill_value_parsed) object.__setattr__(self, "attributes", attributes_parsed) object.__setattr__(self, "storage_transformers", storage_transformers_parsed) object.__setattr__(self, "extra_fields", extra_fields_parsed) self._validate_metadata() def _validate_metadata(self) -> None: if isinstance(self.chunk_grid, RegularChunkGrid) and len(self.shape) != len( self.chunk_grid.chunk_shape ): raise ValueError( "`chunk_shape` and `shape` need to have the same number of dimensions." ) if self.dimension_names is not None and len(self.shape) != len(self.dimension_names): raise ValueError( "`dimension_names` and `shape` need to have the same number of dimensions." ) if self.fill_value is None: raise ValueError("`fill_value` is required.") for codec in self.codecs: codec.validate(shape=self.shape, dtype=self.data_type, chunk_grid=self.chunk_grid) @property def ndim(self) -> int: return len(self.shape) @property def dtype(self) -> ZDType[TBaseDType, TBaseScalar]: return self.data_type @property def chunks(self) -> tuple[int, ...]: if isinstance(self.chunk_grid, RegularChunkGrid): from zarr.codecs.sharding import ShardingCodec if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): sharding_codec = self.codecs[0] assert isinstance(sharding_codec, ShardingCodec) # for mypy return sharding_codec.chunk_shape else: return self.chunk_grid.chunk_shape msg = ( f"The `chunks` attribute is only defined for arrays using `RegularChunkGrid`." f"This array has a {self.chunk_grid} instead." ) raise NotImplementedError(msg) @property def shards(self) -> tuple[int, ...] | None: if isinstance(self.chunk_grid, RegularChunkGrid): from zarr.codecs.sharding import ShardingCodec if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): return self.chunk_grid.chunk_shape else: return None msg = ( f"The `shards` attribute is only defined for arrays using `RegularChunkGrid`." f"This array has a {self.chunk_grid} instead." ) raise NotImplementedError(msg) @property def inner_codecs(self) -> tuple[Codec, ...]: if isinstance(self.chunk_grid, RegularChunkGrid): from zarr.codecs.sharding import ShardingCodec if len(self.codecs) == 1 and isinstance(self.codecs[0], ShardingCodec): return self.codecs[0].codecs return self.codecs def get_chunk_spec( self, _chunk_coords: tuple[int, ...], array_config: ArrayConfig, prototype: BufferPrototype ) -> ArraySpec: assert isinstance(self.chunk_grid, RegularChunkGrid), ( "Currently, only regular chunk grid is supported" ) return ArraySpec( shape=self.chunk_grid.chunk_shape, dtype=self.dtype, fill_value=self.fill_value, config=array_config, prototype=prototype, ) def encode_chunk_key(self, chunk_coords: tuple[int, ...]) -> str: return self.chunk_key_encoding.encode_chunk_key(chunk_coords) def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]: json_indent = config.get("json_indent") d = self.to_dict() return { ZARR_JSON: prototype.buffer.from_bytes( json.dumps(d, allow_nan=True, indent=json_indent).encode() ) } @classmethod def from_dict(cls, data: dict[str, JSON]) -> Self: # make a copy because we are modifying the dict _data = data.copy() # check that the zarr_format attribute is correct _ = parse_zarr_format(_data.pop("zarr_format")) # check that the node_type attribute is correct _ = parse_node_type_array(_data.pop("node_type")) data_type_json = _data.pop("data_type") if not check_dtype_spec_v3(data_type_json): raise ValueError(f"Invalid data_type: {data_type_json!r}") data_type = get_data_type_from_json(data_type_json, zarr_format=3) # check that the fill value is consistent with the data type try: fill = _data.pop("fill_value") fill_value_parsed = data_type.from_json_scalar(fill, zarr_format=3) except ValueError as e: raise TypeError(f"Invalid fill_value: {fill!r}") from e # check if there are extra keys extra_keys = set(_data.keys()) - ARRAY_METADATA_KEYS allowed_extra_fields: dict[str, AllowedExtraField] = {} invalid_extra_fields = {} for key in extra_keys: val = _data[key] if check_allowed_extra_field(val): allowed_extra_fields[key] = val else: invalid_extra_fields[key] = val if len(invalid_extra_fields) > 0: msg = ( "Got a Zarr V3 metadata document with the following disallowed extra fields:" f"{sorted(invalid_extra_fields.keys())}." 'Extra fields are not allowed unless they are a dict with a "must_understand" key' "which is assigned the value `False`." ) raise MetadataValidationError(msg) # TODO: replace this with a real type check! _data_typed = cast(ArrayMetadataJSON_V3, _data) return cls( shape=_data_typed["shape"], chunk_grid=_data_typed["chunk_grid"], chunk_key_encoding=_data_typed["chunk_key_encoding"], codecs=_data_typed["codecs"], attributes=_data_typed.get("attributes", {}), # type: ignore[arg-type] dimension_names=_data_typed.get("dimension_names", None), fill_value=fill_value_parsed, data_type=data_type, extra_fields=allowed_extra_fields, storage_transformers=_data_typed.get("storage_transformers", ()), # type: ignore[arg-type] ) def to_dict(self) -> dict[str, JSON]: out_dict = super().to_dict() extra_fields = out_dict.pop("extra_fields") out_dict = out_dict | extra_fields # type: ignore[operator] out_dict["fill_value"] = self.data_type.to_json_scalar( self.fill_value, zarr_format=self.zarr_format ) if not isinstance(out_dict, dict): raise TypeError(f"Expected dict. Got {type(out_dict)}.") # if `dimension_names` is `None`, we do not include it in # the metadata document if out_dict["dimension_names"] is None: out_dict.pop("dimension_names") # TODO: replace the `to_dict` / `from_dict` on the `Metadata`` class with # to_json, from_json, and have ZDType inherit from `Metadata` # until then, we have this hack here, which relies on the fact that to_dict will pass through # any non-`Metadata` fields as-is. dtype_meta = out_dict["data_type"] if isinstance(dtype_meta, ZDType): out_dict["data_type"] = dtype_meta.to_json(zarr_format=3) # type: ignore[unreachable] return out_dict def update_shape(self, shape: tuple[int, ...]) -> Self: return replace(self, shape=shape) def update_attributes(self, attributes: dict[str, JSON]) -> Self: return replace(self, attributes=attributes)
ArrayV3Metadata
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/from_tensors_test.py
{ "start": 16549, "end": 17564 }
class ____( test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine( repetitions=[1, 3], seed=[None, 19], reshuffle_each_iteration=[True, False]))) def testTensorsDataset( self, repetitions: int, seed: Optional[int], reshuffle_each_iteration: bool): components = (np.array(1), np.array([1, 2, 3]), np.array(37.0)) dataset = dataset_ops.Dataset.from_tensors(components) if repetitions > 1: dataset = dataset.repeat(repetitions) dataset = global_shuffle_op._global_shuffle( dataset, seed=seed, reshuffle_each_iteration=reshuffle_each_iteration) expected = [components] * repetitions self.assertDatasetProduces( dataset, expected_output=expected, requires_initialization=True) self.assertLen(expected, self.evaluate(dataset.cardinality()))
FromTensorsGlobalShuffleTest
python
allegroai__clearml
clearml/backend_interface/task/repo/detectors.py
{ "start": 8249, "end": 12036 }
class ____(Detector): def __init__(self) -> None: super(GitDetector, self).__init__("git") def _get_commands(self) -> "GitDetector.Commands": return self.Commands( url=["git", "ls-remote", "--get-url"], branch=["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"], commit=["git", "rev-parse", "HEAD"], root=["git", "rev-parse", "--show-toplevel"], status=["git", "status", "-s"], diff=["git", "diff", "--submodule=diff", "HEAD"], modified=["git", "ls-files", "-m"], branch_fallback=["git", "rev-parse", "--abbrev-ref", "HEAD"], diff_fallback=["git", "diff", "HEAD"], diff_remote=[ "git", "diff", "--submodule=diff", ], commit_remote=[ "git", "rev-parse", ], diff_fallback_remote=[ "git", "diff", ], ) def get_info( self, path: str, include_diff: bool = False, diff_from_remote: bool = False, ) -> Result: """ Get repository information. :param path: Path to repository :param include_diff: Whether to include the diff command's output (if available) :param diff_from_remote: Whether to store the remote diff/commit based on the remote commit (not local commit) :return: RepoInfo instance """ info = super(GitDetector, self).get_info( path=path, include_diff=include_diff, diff_from_remote=diff_from_remote ) # check if for some reason we ended with the wrong branch name as HEAD (will happen when HEAD is detached) if info and info.branch == "HEAD": # noinspection PyBroadException try: # try to reparse the detached HEAD commands = self._get_commands() name = "branch" command = commands.branch_fallback[:] command[-1] = "origin" info.branch = ( self._get_command_output( path, name, command, commands=commands, strip=bool(name != "diff"), ) or info.branch ) info = self._post_process_info(info) except Exception: # not sure what happened, just skip it. pass # we could not locate the git because of some configuration issue, we need to try a more complex command if info and info.url == "origin": # noinspection PyBroadException try: url = get_command_output(["git", "remote", "-v"], path, strip=True) url = url.split("\n")[0].split("\t", 1)[1] if url.endswith("(fetch)"): url = url[: -len("(fetch)")] elif url.endswith("(pull)"): url = url[: -len("(pull)")] info.url = url.strip() except Exception: # not sure what happened, just skip it. pass return info def _post_process_info(self, info: Result) -> Result: # Deprecated code: this was intended to make sure git repository names always # ended with ".git", but this is not always the case (e.g. Azure Repos) # if info.url and not info.url.endswith(".git"): # info.url += ".git" if (info.branch or "").startswith("origin/"): info.branch = info.branch[len("origin/") :] return info
GitDetector
python
PyCQA__pylint
tests/functional/p/protected_access.py
{ "start": 1042, "end": 1076 }
class ____: _sauce = 42
BaseTomato
python
pennersr__django-allauth
tests/apps/socialaccount/providers/discord/tests.py
{ "start": 452, "end": 2015 }
class ____(OAuth2TestsMixin, TestCase): provider_id = DiscordProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """{ "id": "80351110224678912", "username": "nelly", "discriminator": "0", "global_name": "Nelly", "avatar": "8342729096ea3675442027381ff50dfe", "verified": true, "email": "nelly@example.com" }""", ) def get_expected_to_str(self): return "Nelly" def test_display_name(self, multiple_login=False): email = "user@example.com" user = get_user_model()(is_active=True) user_email(user, email) user_username(user, "user") user.set_password("test") user.save() EmailAddress.objects.create(user=user, email=email, primary=True, verified=True) self.client.login(username=user.username, password="test") self.login(self.get_mocked_response(), process="connect") if multiple_login: self.login( self.get_mocked_response(), with_refresh_token=False, process="connect", ) # get account sa = SocialAccount.objects.filter(user=user, provider=self.provider.id).get() # The following lines don't actually test that much, but at least # we make sure that the code is hit. provider_account = sa.get_provider_account() self.assertEqual(provider_account.to_str(), "Nelly")
DiscordTests
python
xlwings__xlwings
xlwings/pro/_xlremote.py
{ "start": 8996, "end": 11022 }
class ____(base_classes.Sheets): def __init__(self, api, book): self._api = api self.book = book @property def active(self): ix = self.book.api["book"]["active_sheet_index"] return Sheet(api=self.api[ix], sheets=self, index=ix + 1) @property def api(self): return self._api def __call__(self, name_or_index): if isinstance(name_or_index, int): return Sheet( api=self.api[name_or_index - 1], sheets=self, index=name_or_index ) else: for ix, sheet in enumerate(self.api): if sheet["name"] == name_or_index: return Sheet(api=sheet, sheets=self, index=ix + 1) raise ValueError(f"Sheet '{name_or_index}' doesn't exist!") def add(self, before=None, after=None, name=None): # TODO: this is hardcoded to English if name is None: sheet_number = 1 while True: if f"Sheet{sheet_number}" in [sheet.name for sheet in self]: sheet_number += 1 else: break name = f"Sheet{sheet_number}" api = { "name": name, "values": [[]], "pictures": [], "tables": [], } if before: if before.index == 1: ix = 1 else: ix = before.index - 1 elif after: ix = after.index + 1 else: # Default position is different from Desktop apps! ix = len(self) + 1 self.api.insert(ix - 1, api) self.book.append_json_action(func="addSheet", args=[ix - 1, name]) self.book.api["book"]["active_sheet_index"] = ix - 1 return Sheet(api=api, sheets=self, index=ix) def __len__(self): return len(self.api) def __iter__(self): for ix, sheet in enumerate(self.api): yield Sheet(api=sheet, sheets=self, index=ix + 1)
Sheets
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/retrieval_qa/base.py
{ "start": 7145, "end": 9858 }
class ____(BaseRetrievalQA): """Chain for question-answering against an index. This class is deprecated. See below for an example implementation using `create_retrieval_chain`: ```python from langchain_classic.chains import create_retrieval_chain from langchain_classic.chains.combine_documents import ( create_stuff_documents_chain, ) from langchain_core.prompts import ChatPromptTemplate from langchain_openai import ChatOpenAI retriever = ... # Your retriever model = ChatOpenAI() system_prompt = ( "Use the given context to answer the question. " "If you don't know the answer, say you don't know. " "Use three sentence maximum and keep the answer concise. " "Context: {context}" ) prompt = ChatPromptTemplate.from_messages( [ ("system", system_prompt), ("human", "{input}"), ] ) question_answer_chain = create_stuff_documents_chain(model, prompt) chain = create_retrieval_chain(retriever, question_answer_chain) chain.invoke({"input": query}) ``` Example: ```python from langchain_openai import OpenAI from langchain_classic.chains import RetrievalQA from langchain_community.vectorstores import FAISS from langchain_core.vectorstores import VectorStoreRetriever retriever = VectorStoreRetriever(vectorstore=FAISS(...)) retrievalQA = RetrievalQA.from_llm(llm=OpenAI(), retriever=retriever) ``` """ retriever: BaseRetriever = Field(exclude=True) def _get_docs( self, question: str, *, run_manager: CallbackManagerForChainRun, ) -> list[Document]: """Get docs.""" return self.retriever.invoke( question, config={"callbacks": run_manager.get_child()}, ) async def _aget_docs( self, question: str, *, run_manager: AsyncCallbackManagerForChainRun, ) -> list[Document]: """Get docs.""" return await self.retriever.ainvoke( question, config={"callbacks": run_manager.get_child()}, ) @property def _chain_type(self) -> str: """Return the chain type.""" return "retrieval_qa" @deprecated( since="0.2.13", removal="1.0", message=( "This class is deprecated. Use the `create_retrieval_chain` constructor " "instead. See migration guide here: " "https://python.langchain.com/docs/versions/migrating_chains/retrieval_qa/" ), )
RetrievalQA
python
ApeWorX__ape
src/ape_test/config.py
{ "start": 4462, "end": 6552 }
class ____(PluginConfig): balance: int = DEFAULT_TEST_ACCOUNT_BALANCE """ The starting-balance of every test account in Wei (NOT Ether). """ coverage: CoverageConfig = CoverageConfig() """ Configuration related to coverage reporting. """ enable_fixture_rebasing: bool = True """ Set to ``False`` to ignore fixture rebasing when non-function scoped fixtures become invalidated. """ disconnect_providers_after: bool = True """ Set to ``False`` to keep providers connected at the end of the test run. """ gas: GasConfig = GasConfig() """ Configuration related to gas reporting. """ hd_path: str = DEFAULT_TEST_HD_PATH """ The hd_path to use when generating the test accounts. """ mnemonic: str = DEFAULT_TEST_MNEMONIC """ The mnemonic to use when generating the test accounts. """ number_of_accounts: NonNegativeInt = DEFAULT_NUMBER_OF_TEST_ACCOUNTS """ The number of test accounts to generate in the provider. """ provider: EthTesterProviderConfig = EthTesterProviderConfig() """ Settings for the provider. """ show_internal: bool = False """ Set to ``True`` to always show Ape's internal stack-trace in errors, useful for debugging the framework itself. """ isolation: Union[bool, IsolationConfig] = True """ Configure which scope-specific isolation to enable. Set to ``False`` to disable all and ``True`` (default) to disable all. """ model_config = SettingsConfigDict(extra="allow", env_prefix="APE_TEST_") @field_validator("balance", mode="before") @classmethod def validate_balance(cls, value): return ( value if isinstance(value, int) else ManagerAccessMixin.conversion_manager.convert(value, int) ) def get_isolation(self, scope: "Scope") -> bool: return ( self.isolation if isinstance(self.isolation, bool) else self.isolation.get_isolation(scope) )
ApeTestConfig
python
google__jax
tests/pallas/tpu_splash_attention_kernel_test.py
{ "start": 3774, "end": 4466 }
class ____(Mask): q_seq_len: int kv_seq_len: int sparsity: float seed: int def get_mask(self) -> mask_lib.Mask: mask = mask_lib.make_random_mask( (self.q_seq_len, self.kv_seq_len), self.sparsity, self.seed ) # Make sure that no row is full of zeros as this is leads to undefined # softmax. mask[:, 0] = True return mask_lib.NumpyMask(mask) @hps.composite def random_mask_strategy(draw: Draw, q_seq_len: int, kv_seq_len: int) -> Mask: seed = draw(hps.integers(min_value=0, max_value=2**32 - 1)) sparsity = draw(hps.floats(min_value=0.0, max_value=0.5)) return RandomMask(q_seq_len, kv_seq_len, sparsity, seed) @dataclasses.dataclass
RandomMask
python
ansible__ansible
test/units/module_utils/basic/test_tmpdir.py
{ "start": 377, "end": 3843 }
class ____: DATA = ( ( { "_ansible_tmpdir": "/path/to/dir", "_ansible_remote_tmp": "/path/tmpdir", "_ansible_keep_remote_files": False, }, True, "/path/to/dir" ), ( { "_ansible_tmpdir": None, "_ansible_remote_tmp": "/path/tmpdir", "_ansible_keep_remote_files": False }, False, "/path/tmpdir/ansible-moduletmp-42-" ), ( { "_ansible_tmpdir": None, "_ansible_remote_tmp": "/path/tmpdir", "_ansible_keep_remote_files": False }, True, "/path/tmpdir/ansible-moduletmp-42-" ), ( { "_ansible_tmpdir": None, "_ansible_remote_tmp": "$HOME/.test", "_ansible_keep_remote_files": False }, False, os.path.join(os.environ['HOME'], ".test/ansible-moduletmp-42-") ), ) @pytest.mark.parametrize('args, expected, stat_exists', ((s, e, t) for s, t, e in DATA)) def test_tmpdir_property(self, monkeypatch, args, expected, stat_exists): makedirs = {'called': False} def mock_mkdtemp(prefix, dir): return os.path.join(dir, prefix) def mock_makedirs(path, mode): makedirs['called'] = True makedirs['path'] = path makedirs['mode'] = mode return monkeypatch.setattr(tempfile, 'mkdtemp', mock_mkdtemp) monkeypatch.setattr(os.path, 'exists', lambda x: stat_exists) monkeypatch.setattr(os, 'makedirs', mock_makedirs) with patch_module_args(args), \ patch('time.time', return_value=42): am = basic.AnsibleModule(argument_spec={}) actual_tmpdir = am.tmpdir assert actual_tmpdir == expected # verify subsequent calls always produces the same tmpdir assert am.tmpdir == actual_tmpdir if not stat_exists: assert makedirs['called'] expected = os.path.expanduser(os.path.expandvars(am._remote_tmp)) assert makedirs['path'] == expected assert makedirs['mode'] == 0o700 @pytest.mark.parametrize('stdin', ({"_ansible_tmpdir": None, "_ansible_remote_tmp": "$HOME/.test", "_ansible_keep_remote_files": True},), indirect=['stdin']) def test_tmpdir_makedirs_failure(self, am, monkeypatch): mock_mkdtemp = MagicMock(return_value="/tmp/path") mock_makedirs = MagicMock(side_effect=OSError("Some OS Error here")) monkeypatch.setattr(tempfile, 'mkdtemp', mock_mkdtemp) monkeypatch.setattr(os.path, 'exists', lambda x: False) monkeypatch.setattr(os, 'makedirs', mock_makedirs) actual = am.tmpdir assert actual == "/tmp/path" assert mock_makedirs.call_args[0] == (os.path.expanduser(os.path.expandvars("$HOME/.test")),) assert mock_makedirs.call_args[1] == {"mode": 0o700} # because makedirs failed the dir should be None so it uses the System tmp assert mock_mkdtemp.call_args[1]['dir'] is None assert mock_mkdtemp.call_args[1]['prefix'].startswith("ansible-moduletmp-")
TestAnsibleModuleTmpDir
python
Lightning-AI__lightning
tests/tests_pytorch/tuner/test_scale_batch_size.py
{ "start": 24465, "end": 25700 }
class ____(BoringModel): """A BoringModel that fails when batch size reaches a certain threshold.""" def __init__(self, batch_size=2, fail_at=16): super().__init__() self.batch_size = batch_size self.fail_at = fail_at def training_step(self, batch, batch_idx): # Simulate OOM error when batch size is too large if self.batch_size >= self.fail_at: raise RuntimeError("CUDA error: out of memory") return super().training_step(batch, batch_idx) @pytest.mark.parametrize( ("max_trials", "mode", "init_val", "expected"), [ (3, "power", 2, 8), (3, "binsearch", 2, 7), # applied margin of 5% on 8 -> int(8 * 0.95) = 7 (1, "power", 4, 4), (0, "power", 2, 2), ], ) def test_scale_batch_size_max_trials_modes(tmp_path, max_trials, mode, init_val, expected): model = AlwaysSucceedingBoringModel(batch_size=init_val) trainer = Trainer(default_root_dir=tmp_path, max_epochs=1) tuner = Tuner(trainer) result = tuner.scale_batch_size( model, mode=mode, steps_per_trial=1, max_trials=max_trials, init_val=init_val, ) assert result == expected
FailsAtBatchSizeBoringModel
python
spyder-ide__spyder
spyder/plugins/explorer/widgets/remote_explorer.py
{ "start": 2864, "end": 38887 }
class ____(QWidget, SpyderWidgetMixin): sig_dir_opened = Signal(str, str) sig_start_spinner_requested = Signal() sig_stop_spinner_requested = Signal() def __init__(self, parent=None, class_parent=None, files=None): super().__init__(parent=parent, class_parent=parent) # General attributes self.remote_files_manager = None self.server_id: str | None = None self.root_prefix: dict[str, str] = {} self.background_files_load = set() self.extra_files = [] self.more_files_available = False self.filter_on = False self.name_filters = [] self.history = [] self.histindex = None # Model, actions and widget setup self.context_menu = self.create_menu(RemoteViewMenus.Context) new_submenu = self.create_menu( RemoteViewMenus.New, _('New'), ) self.new_package_action = self.create_action( RemoteExplorerActions.NewPackage, text=_("Python package..."), icon=self.create_icon('package_new'), triggered=self.new_package, ) self.new_module_action = self.create_action( RemoteExplorerActions.NewModule, text=_("Python file..."), icon=self.create_icon('python'), triggered=self.new_module, ) self.new_directory_action = self.create_action( RemoteExplorerActions.NewDirectory, text=_("Folder..."), icon=self.create_icon('folder_new'), triggered=self.new_directory, ) self.new_file_action = self.create_action( RemoteExplorerActions.NewFile, text=_("File..."), icon=self.create_icon('TextFileIcon'), triggered=self.new_file, ) self.copy_paste_action = self.create_action( RemoteExplorerActions.CopyPaste, _("Copy and Paste..."), icon=self.create_icon("editcopy"), triggered=self.copy_paste_item, ) self.rename_action = self.create_action( RemoteExplorerActions.Rename, _("Rename..."), icon=self.create_icon("rename"), triggered=self.rename_item, ) self.copy_path_action = self.create_action( RemoteExplorerActions.CopyPath, _("Copy path"), triggered=self.copy_path, ) self.delete_action = self.create_action( RemoteExplorerActions.Delete, _("Delete..."), icon=self.create_icon("editclear"), triggered=self.delete_item, ) self.download_action = self.create_action( RemoteExplorerActions.Download, _("Download..."), icon=self.create_icon("fileimport"), triggered=self.download_item, ) self.upload_file_action = self.create_action( RemoteExplorerActions.Upload, _("Upload file"), icon=self.create_icon("fileexport"), triggered=self.upload_file, ) for item in [self.new_file_action, self.new_directory_action]: self.add_item_to_menu( item, new_submenu, section=RemoteViewNewSubMenuSections.General, ) for item in [self.new_module_action, self.new_package_action]: self.add_item_to_menu( item, new_submenu, section=RemoteViewNewSubMenuSections.Language, ) for item in [ new_submenu, self.rename_action, self.delete_action, ]: self.add_item_to_menu( item, self.context_menu, section=RemoteExplorerContextMenuSections.New, ) for item in [ self.copy_paste_action, self.copy_path_action, ]: self.add_item_to_menu( item, self.context_menu, section=RemoteExplorerContextMenuSections.CopyPaste, ) for item in [self.download_action]: self.add_item_to_menu( item, self.context_menu, section=RemoteExplorerContextMenuSections.Extras, ) self.setContextMenuPolicy(Qt.CustomContextMenu) self.customContextMenuRequested.connect(self._on_show_context_menu) self.model = QStandardItemModel(self) self.model.setHorizontalHeaderLabels( [ "Name", "Size", "Type", "Date Modified", ] ) self.proxy_model = RemoteQSortFilterProxyModel(self) self.proxy_model.setSourceModel(self.model) self.view = QTreeView(self) self.view.setModel(self.proxy_model) self.view.setSortingEnabled(True) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect( self._on_show_context_menu ) if files: self.set_files(files) self.view.sortByColumn(0, Qt.AscendingOrder) self.view.entered.connect(self._on_entered_item) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.view) @on_conf_change( option=[ "size_column", "type_column", "date_column", "name_filters", "show_hidden", "single_click_to_open", ] ) def on_conf_update(self, option, value): if option == "size_column": self.view.setColumnHidden(1, not value) elif option == "type_column": self.view.setColumnHidden(2, not value) elif option == "date_column": self.view.setColumnHidden(3, not value) elif option == "name_filters": if self.filter_on: self.filter_files(value) elif option == "show_hidden": self.refresh(force_current=True) elif option == "single_click_to_open": self.set_single_click_to_open(value) def _on_show_context_menu(self, position): index = self.view.indexAt(position) if not index.isValid(): self.view.setCurrentIndex(index) self.view.clearSelection() data = {} data_available = False is_file = False else: source_index = self.proxy_model.mapToSource( self.view.currentIndex() ) data_index = self.model.index(source_index.row(), 0) data = self.model.data(data_index, Qt.UserRole + 1) data_available = bool(data) is_file = ( data_available and data.get("type", "directory") == "file" ) # Disable actions that require a valid selection self.rename_action.setEnabled(data_available) self.delete_action.setEnabled(data_available) # Disable actions not suitable for directories self.copy_paste_action.setEnabled(is_file) global_position = self.mapToGlobal(position) self.context_menu.popup(global_position) def _on_entered_item(self, index): if self.get_conf("single_click_to_open"): self.view.setCursor(Qt.PointingHandCursor) self.view.header().setCursor(Qt.ArrowCursor) else: self.view.setCursor(Qt.ArrowCursor) def _on_clicked_item(self, index): source_index = self.proxy_model.mapToSource(index) data_index = self.model.index(source_index.row(), 0) data = self.model.data(data_index, Qt.UserRole + 1) if data: data_name = data["name"] data_type = data["type"] if data_type == "directory": self.chdir(data_name, emit=True) elif data_type == "ACTION" and data_name == "FETCH_MORE": self.fetch_more_files() def _handle_future_response_error(self, response, error_title, error_message): result = response.result() if isinstance(result, Exception): logger.debug(result) error_message = f"{error_message}<br><br>{result.message}" QMessageBox.critical(self, error_title, error_message) @AsyncDispatcher.QtSlot def _on_remote_new_package(self, future, package_name): self._handle_future_response_error( future, _("New Python Package error"), _("An error occured while trying to create a new Python package"), ) new_name = posixpath.join(package_name, "__init__.py") self._new_item(new_name, for_file=True, with_content=True) @AsyncDispatcher.QtSlot def _on_remote_new_module(self, future): self._handle_future_response_error( future, _("New Python File error"), _("An error occured while trying to create a new Python file"), ) self.refresh(force_current=True) @AsyncDispatcher(loop="explorer") async def _do_remote_new_module(self, new_path, file_content): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return try: file_manager = await self.remote_files_manager.open(new_path, mode="w") remote_file_response = await file_manager.write(file_content) await file_manager.close() except (RemoteOSError, OSError) as error: # Catch error raised when awaiting. The error will be available # and will be shown when handling the result with the usage of # `_handle_future_response_error` # See spyder-ide/spyder#24974 remote_file_response = error return remote_file_response @AsyncDispatcher.QtSlot def _on_remote_new(self, future): self._handle_future_response_error( future, _("New error"), _("An error occured while trying to create a file/directory"), ) self.refresh(force_current=True) @AsyncDispatcher(loop="explorer") async def _do_remote_new( self, new_path, for_file=False ): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return try: if for_file: response = await self.remote_files_manager.touch(new_path) else: response = await self.remote_files_manager.mkdir(new_path) except (RemoteOSError, OSError) as error: # Catch error raised when awaiting. The error will be available # and will be shown when handling the result with the usage of # `_handle_future_response_error` # See spyder-ide/spyder#24974 response = error return response @AsyncDispatcher.QtSlot def _on_remote_copy_paste(self, future): self._handle_future_response_error( future, _("Copy and Paste error"), _( "An error occured while trying to copy and paste a " "file/directory" ), ) self.refresh(force_current=True) @AsyncDispatcher(loop="explorer") async def _do_remote_copy_paste(self, old_path, new_path): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return return await self.remote_files_manager.copy(old_path, new_path) @AsyncDispatcher.QtSlot def _on_remote_rename(self, future): self._handle_future_response_error( future, _("Rename error"), _("An error occured while trying to rename a file"), ) self.refresh(force_current=True) @AsyncDispatcher(loop="explorer") async def _do_remote_rename(self, old_path, new_path): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return return await self.remote_files_manager.replace(old_path, new_path) @AsyncDispatcher.QtSlot def _on_remote_delete(self, future): self._handle_future_response_error( future, _("Delete error"), _("An error occured while trying to delete a file/directory"), ) self.refresh(force_current=True) @AsyncDispatcher(loop="explorer") async def _do_remote_delete(self, path, is_file=False): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return try: if is_file: response = await self.remote_files_manager.unlink(path) else: response = await self.remote_files_manager.rmdir( path, non_empty=True ) except (RemoteOSError, OSError) as error: # Catch error raised when awaiting. The error will be available # and will be shown when handling the result with the usage of # `_handle_future_response_error` # See spyder-ide/spyder#24974 response = error return response @AsyncDispatcher.QtSlot def _on_remote_download_file(self, future, remote_filename): data = future.result() filename, __ = getsavefilename( self, _("Download file"), os.path.join(getcwd_or_home(), remote_filename), _("All files") + " (*)", ) if filename: try: with open(filename, "w") as download_file: download_file.write(data) except TypeError: with open(filename, "wb") as download_file: download_file.write(data) self.sig_stop_spinner_requested.emit() @AsyncDispatcher(loop="explorer") async def _do_remote_download_directory(self, path): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return try: zip_generator = self.remote_files_manager.zip_directory(path) zip_data = io.BytesIO() async for data in zip_generator: zip_data.write(data) zip_data.seek(0) except RemoteFileServicesError as download_error: logger.debug(f"Unable to download {path}") logger.debug( f"Error while trying to download directory (compressed): " f"{download_error.message}" ) error_message = _( "An error occured while trying to download {path}" ).format(path=path) QMessageBox.critical(self, _("Download error"), error_message) return zip_data.getbuffer() @AsyncDispatcher(loop="explorer") async def _do_remote_download_file(self, path): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return try: file_manager = await self.remote_files_manager.open(path, mode="r") file_data = "" async for data in file_manager: file_data += data except RemoteFileServicesError: try: file_manager = await self.remote_files_manager.open( path, mode="rb" ) file_data = b"" async for data in file_manager: file_data += data except RemoteFileServicesError as download_error: logger.debug(f"Unable to download {path}") logger.debug( f"Error while trying to download file: " f"{download_error.message}" ) error_message = _( "An error occured while trying to download {path}" ).format(path=path) QMessageBox.critical(self, _("Download error"), error_message) await file_manager.close() return file_data @AsyncDispatcher.QtSlot def _on_remote_upload_file(self, future): self._handle_future_response_error( future, _("Upload error"), _("An error occured while trying to upload a file"), ) self.refresh(force_current=True) @AsyncDispatcher(loop="explorer") async def _do_remote_upload_file(self, local_path): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return remote_file = posixpath.join( self.root_prefix[self.server_id], os.path.basename(local_path) ) file_content = None try: try: with open(local_path, mode="r") as local_file: file_content = local_file.read() file_manager = await self.remote_files_manager.open( remote_file, mode="w" ) except UnicodeDecodeError: with open(local_path, mode="rb") as local_file: file_content = local_file.read() file_manager = await self.remote_files_manager.open( remote_file, mode="wb" ) if file_content: remote_file_response = await file_manager.write(file_content) await file_manager.close() except (RemoteOSError, OSError) as error: # Catch error raised when awaiting. The error will be available # and will be shown when handling the result with the usage of # `_handle_future_response_error` # See spyder-ide/spyder#24974 remote_file_response = error return remote_file_response @AsyncDispatcher.QtSlot def _on_remote_ls(self, future): data = future.result() self.set_files(data) @AsyncDispatcher(loop="explorer") async def _do_remote_ls(self, path, server_id): if not self.remote_files_manager: self.sig_stop_spinner_requested.emit() return for task in self.background_files_load: task.cancel() try: await task except asyncio.CancelledError: pass self.extra_files = [] self.more_files_available = False files = [] try: init_files_display = self.get_conf("init_files_display") generator = self.remote_files_manager.ls(path) async for file in generator: file_name = os.path.relpath( file["name"], self.root_prefix[self.server_id] ) file_type = file["type"] if len(files) < init_files_display: if not self.get_conf( "show_hidden" ) and file_name.startswith("."): continue if ( self.name_filters and len(self.name_filters) and file_type == "file" ): for name_filter in self.name_filters: if file_type == "file" and fnmatch.fnmatch( file_name, name_filter ): files.append(file) break else: files.append(file) else: break if len(files) == init_files_display: task = asyncio.create_task( self._get_extra_files(generator, len(files)) ) self.background_files_load.add(task) task.add_done_callback(self.background_files_load.discard) except RemoteOSError as error: # TODO: Should the error be shown in some way? logger.debug(error) except SpyderRemoteSessionClosed: self.remote_files_manager = None return files async def _get_extra_files(self, generator, already_added): self.extra_files = [] self.more_files_available = False async for file in generator: if len(self.extra_files) + already_added == self.get_conf( "max_files_display" ): self.more_files_available = True break file_name = os.path.relpath( file["name"], self.root_prefix[self.server_id] ) file_type = file["type"] if not self.get_conf("show_hidden") and file_name.startswith("."): continue if ( self.name_filters and len(self.name_filters) and file_type == "file" ): for name_filter in self.name_filters: if file_type == "file" and fnmatch.fnmatch( file_name, name_filter ): self.extra_files.append(file) break else: self.extra_files.append(file) logger.debug( f"{len(self.extra_files)} available extra files to be shown" ) def _new_item(self, new_name, for_file=False, with_content=False): new_path = posixpath.join(self.root_prefix[self.server_id], new_name) if not with_content: self._do_remote_new(new_path, for_file=for_file).connect( self._on_remote_new ) elif for_file and with_content: file_content, __, __ = get_default_file_content( get_conf_path("template.py") ) self._do_remote_new_module(new_path, file_content).connect( self._on_remote_new_module ) elif not for_file and with_content: @AsyncDispatcher.QtSlot def remote_package(future): self._on_remote_new_package(future, new_name) self._do_remote_new(new_path).connect(remote_package) self.sig_start_spinner_requested.emit() @AsyncDispatcher.QtSlot def chdir( self, directory=None, server_id=None, emit=True, browsing_history=False, remote_files_manager=None, ): if browsing_history: directory = self.history[self.histindex] elif directory in self.history: self.histindex = self.history.index(directory) else: if self.histindex is None: self.history = [] else: self.history = self.history[: self.histindex + 1] if len(self.history) == 0 or ( self.history and self.history[-1] != directory ): self.history.append(directory) self.histindex = len(self.history) - 1 if directory == self.root_prefix.get(server_id): return if server_id: self.server_id = server_id self.root_prefix[self.server_id] = directory if remote_files_manager: self.remote_files_manager = remote_files_manager self.refresh(force_current=True) if emit: self.sig_dir_opened.emit(directory, self.server_id) def set_files(self, files, reset=True): if reset: self.model.setRowCount(0) if files: logger.debug(f"Setting {len(files)} files") root = self.model.invisibleRootItem() more_files_items = self.model.match( self.model.index(0, 0), Qt.DisplayRole, _("Show more files") ) if len(more_files_items): # Remove more files item self.model.removeRow(more_files_items[-1].row()) more_files_available = self.model.match( self.model.index(0, 0), Qt.DisplayRole, _("Maximum number of files to display reached!"), ) if len(more_files_available): # Remove more items available item self.model.removeRow(more_files_available[-1].row()) for file in files: path = file["name"] name = os.path.relpath(path, self.root_prefix[self.server_id]) file_type = file["type"] icon = ima.icon("FileIcon") if file_type == "directory": icon = ima.icon("DirClosedIcon") file_name = QStandardItem(icon, name) file_name.setData(file) file_name.setToolTip(file["name"]) file_size = QStandardItem(str(file["size"])) file_type = QStandardItem(file_type) file_date_modified = QStandardItem( datetime.fromtimestamp(file["mtime"]).strftime( "%d/%m/%Y %I:%M %p" ) ) items = [ file_name, file_size, file_type, file_date_modified, ] for standard_item in items: standard_item.setEditable(False) root.appendRow(items) # Add fetch more or more items available item if len(self.extra_files): fetch_more_item = QStandardItem(_("Show more files")) fetch_more_item.setEditable(False) fetch_more_item.setData( {"name": "FETCH_MORE", "type": "ACTION"} ) root.appendRow(fetch_more_item) self.view.setFirstColumnSpanned( fetch_more_item.index().row(), root.index(), True ) elif len(self.extra_files) == 0 and self.more_files_available: more_items_available = QStandardItem( _("Maximum number of files to display reached!") ) more_items_available.setEditable(False) more_items_available.setData( {"name": "MESSAGE", "type": "ACTION"} ) root.appendRow(more_items_available) self.view.setFirstColumnSpanned( more_items_available.index().row(), root.index(), True ) self.view.resizeColumnToContents(0) def fetch_more_files(self): fetch_files_display = self.get_conf("fetch_files_display") new_files = self.extra_files[:fetch_files_display] del self.extra_files[:fetch_files_display] self.set_files(new_files, reset=False) logger.debug( f"{len(self.extra_files)} extra files remaining to be shown" ) def set_current_folder(self, folder): self.root_prefix[self.server_id] = folder return self.model.invisibleRootItem() def get_current_folder(self): return self.root_prefix[self.server_id] def go_to_parent_directory(self): parent_directory = os.path.dirname(self.root_prefix[self.server_id]) logger.debug( f"Going to parent directory of {self.root_prefix[self.server_id]}: " f"{parent_directory}" ) self.chdir(parent_directory) def go_to_previous_directory(self): self.histindex -= 1 logger.debug( f"Going to previous directory in history with index " f"{self.histindex}" ) self.chdir(browsing_history=True) def go_to_next_directory(self): self.histindex += 1 logger.debug( f"Going to next directory in history with index {self.histindex}" ) self.chdir(browsing_history=True) def refresh(self, new_path=None, force_current=False): if force_current: if new_path is None: new_path = self.root_prefix.get(self.server_id) self._do_remote_ls(new_path, self.server_id).connect( self._on_remote_ls ) self.previous_action.setEnabled(False) self.next_action.setEnabled(False) if self.histindex is not None: self.previous_action.setEnabled(self.histindex > 0) self.next_action.setEnabled(self.histindex < len(self.history) - 1) self.sig_stop_spinner_requested.emit() def set_single_click_to_open(self, value): if value: try: self.view.doubleClicked.disconnect(self._on_clicked_item) except TypeError: pass self.view.clicked.connect(self._on_clicked_item) else: try: self.view.clicked.disconnect(self._on_clicked_item) except TypeError: pass self.view.doubleClicked.connect(self._on_clicked_item) def filter_files(self, name_filters=None): """Filter files given the defined list of filters.""" if name_filters is None: name_filters = self.get_conf("name_filters") self.name_filters = [] if self.filter_on: self.name_filters = name_filters self.refresh(force_current=True) def change_filter_state(self): self.filter_on = not self.filter_on self.filter_button.setChecked(self.filter_on) self.filter_button.setToolTip(_("Filter filenames")) self.filter_files() def new_package(self): new_name, valid = QInputDialog.getText( self, _("New Python Package"), _("Name as:"), QLineEdit.Normal, "" ) if valid: self._new_item(new_name, with_content=True) def new_module(self): new_name, valid = QInputDialog.getText( self, _("New Python File"), _("Name as:"), QLineEdit.Normal, ".py" ) if valid: self._new_item(new_name, for_file=True, with_content=True) def new_directory(self): new_name, valid = QInputDialog.getText( self, _("New Folder"), _("Name as:"), QLineEdit.Normal, "" ) if valid: self._new_item(new_name) def new_file(self): new_name, valid = QInputDialog.getText( self, _("New File"), _("Name as:"), QLineEdit.Normal, "" ) if valid: self._new_item(new_name, for_file=True) def copy_paste_item(self): if ( not self.view.currentIndex() or not self.view.currentIndex().isValid() ): return source_index = self.proxy_model.mapToSource(self.view.currentIndex()) data_index = self.model.index(source_index.row(), 0) data = self.model.data(data_index, Qt.UserRole + 1) if data: old_path = data["name"] relpath = os.path.relpath( old_path, self.root_prefix[self.server_id] ) new_relpath, valid = QInputDialog.getText( self, _("Copy and Paste"), _("Paste as:"), QLineEdit.Normal, relpath, ) if valid: new_path = posixpath.join( self.root_prefix[self.server_id], new_relpath ) self._do_remote_copy_paste(old_path, new_path).connect( self._on_remote_copy_paste ) self.sig_start_spinner_requested.emit() def rename_item(self): if ( not self.view.currentIndex() or not self.view.currentIndex().isValid() ): return source_index = self.proxy_model.mapToSource(self.view.currentIndex()) data_index = self.model.index(source_index.row(), 0) data = self.model.data(data_index, Qt.UserRole + 1) if data: old_path = data["name"] relpath = os.path.relpath( old_path, self.root_prefix[self.server_id] ) new_relpath, valid = QInputDialog.getText( self, _("Rename"), _("New name:"), QLineEdit.Normal, relpath ) if valid: new_path = posixpath.join( self.root_prefix[self.server_id], new_relpath ) self._do_remote_rename(old_path, str(new_path)).connect( self._on_remote_rename ) self.sig_start_spinner_requested.emit() def copy_path(self): if ( not self.view.currentIndex() or not self.view.currentIndex().isValid() ): path = self.root_prefix[self.server_id] else: source_index = self.proxy_model.mapToSource( self.view.currentIndex() ) data_index = self.model.index(source_index.row(), 0) data = self.model.data(data_index, Qt.UserRole + 1) if data: path = data["name"] cb = QApplication.clipboard() cb.setText(path, mode=QClipboard.Mode.Clipboard) def delete_item(self): if ( not self.view.currentIndex() or not self.view.currentIndex().isValid() ): return source_index = self.proxy_model.mapToSource(self.view.currentIndex()) data_index = self.model.index(source_index.row(), 0) data = self.model.data(data_index, Qt.UserRole + 1) if data: path = data["name"] filename = os.path.relpath(path, self.root_prefix[self.server_id]) result = QMessageBox.warning( self, _("Delete"), _("Do you really want to delete <b>{filename}</b>?").format( filename=filename ), QMessageBox.Yes | QMessageBox.No, ) if result == QMessageBox.Yes: is_file = data["type"] == "file" self._do_remote_delete(path, is_file=is_file).connect( self._on_remote_delete ) self.sig_start_spinner_requested.emit() def download_item(self): if ( not self.view.currentIndex() or not self.view.currentIndex().isValid() ): return source_index = self.proxy_model.mapToSource(self.view.currentIndex()) data_index = self.model.index(source_index.row(), 0) data = self.model.data(data_index, Qt.UserRole + 1) if data: path = data["name"] filename = os.path.relpath(path, self.root_prefix[self.server_id]) is_file = data["type"] == "file" remote_filename = filename if is_file else f"{filename}.zip" @AsyncDispatcher.QtSlot def remote_download_file(future): self._on_remote_download_file(future, remote_filename) if is_file: self._do_remote_download_file(path).connect( remote_download_file ) else: self._do_remote_download_directory(path).connect( remote_download_file ) self.sig_start_spinner_requested.emit() def upload_file(self): local_path, __ = getopenfilename( self, _("Upload file"), getcwd_or_home(), _("All files") + " (*)", ) if os.path.exists(local_path): self._do_remote_upload_file(local_path).connect( self._on_remote_upload_file ) self.sig_start_spinner_requested.emit() def reset(self, server_id): self.root_prefix[server_id] = None
RemoteExplorer
python
getsentry__sentry
src/sentry/api/invite_helper.py
{ "start": 1319, "end": 1821 }
class ____: invite_token: str | None invite_member_id: int | None invite_organization_id: int | None def get_invite_details(request: HttpRequest) -> InviteDetails: """Returns tuple of (token, member_id) from request session""" return InviteDetails( invite_token=request.session.get("invite_token", None), invite_member_id=request.session.get("invite_member_id", None), invite_organization_id=request.session.get("invite_organization_id"), )
InviteDetails
python
python-pillow__Pillow
Tests/test_imagefile.py
{ "start": 8396, "end": 8575 }
class ____: @classmethod def setup_class(cls) -> None: Image.register_decoder("MOCK", MockPyDecoder) Image.register_encoder("MOCK", MockPyEncoder)
CodecsTest
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/cloud_formation.py
{ "start": 1271, "end": 3111 }
class ____(AwsBaseOperator[CloudFormationHook]): """ An operator that creates an AWS CloudFormation stack. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudFormationCreateStackOperator` :param stack_name: stack name (templated) :param cloudformation_parameters: parameters to be passed to AWS CloudFormation. :param aws_conn_id: The Airflow connection used for AWS credentials. If this is ``None`` or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). :param region_name: AWS region_name. If not specified then the default boto3 behaviour is used. :param verify: Whether or not to verify SSL certificates. See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html :param botocore_config: Configuration dictionary (key-values) for botocore client. See: https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html """ aws_hook_class = CloudFormationHook template_fields: Sequence[str] = aws_template_fields("stack_name", "cloudformation_parameters") ui_color = "#6b9659" def __init__(self, *, stack_name: str, cloudformation_parameters: dict, **kwargs): super().__init__(**kwargs) self.stack_name = stack_name self.cloudformation_parameters = cloudformation_parameters def execute(self, context: Context): self.log.info("CloudFormation parameters: %s", self.cloudformation_parameters) self.hook.create_stack(self.stack_name, self.cloudformation_parameters)
CloudFormationCreateStackOperator
python
getsentry__sentry
src/sentry/api/serializers/rest_framework/project_key.py
{ "start": 357, "end": 894 }
class ____(serializers.Serializer): """ Applies a rate limit to cap the number of errors accepted during a given time window. To disable entirely set `rateLimit` to null. ```json { "rateLimit": { "window": 7200, // time in seconds "count": 1000 // error cap } } ``` """ count = EmptyIntegerField(min_value=0, required=False, allow_null=True) window = EmptyIntegerField(min_value=0, max_value=60 * 60 * 24, required=False, allow_null=True)
RateLimitSerializer
python
doocs__leetcode
solution/2200-2299/2276.Count Integers in Intervals/Solution.py
{ "start": 1721, "end": 2085 }
class ____: def __init__(self): self.tree = SegmentTree() def add(self, left, right): self.tree.modify(left, right, 1) def count(self): return self.tree.query(1, int(1e9)) # Your CountIntervals object will be instantiated and called as such: # obj = CountIntervals() # obj.add(left, right) # param_2 = obj.count()
CountIntervals
python
walkccc__LeetCode
solutions/670. Maximum Swap/670.py
{ "start": 0, "end": 378 }
class ____: def maximumSwap(self, num: int) -> int: s = list(str(num)) dict = {c: i for i, c in enumerate(s)} for i, c in enumerate(s): for digit in reversed(string.digits): if digit <= c: break if digit in dict and dict[digit] > i: s[i], s[dict[digit]] = digit, s[i] return int(''.join(s)) return num
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 40186, "end": 40876 }
class ____(sgqlc.types.Enum): """The GitHub Enterprise Importer (GEI) migration state. Enumeration Choices: * `FAILED`: The migration has failed. * `FAILED_VALIDATION`: The migration has invalid credentials. * `IN_PROGRESS`: The migration is in progress. * `NOT_STARTED`: The migration has not started. * `PENDING_VALIDATION`: The migration needs to have its credentials validated. * `QUEUED`: The migration has been queued. * `SUCCEEDED`: The migration has succeeded. """ __schema__ = github_schema __choices__ = ("FAILED", "FAILED_VALIDATION", "IN_PROGRESS", "NOT_STARTED", "PENDING_VALIDATION", "QUEUED", "SUCCEEDED")
MigrationState
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol17.py
{ "start": 393, "end": 657 }
class ____(Protocol[_T1, _T2, _T3]): def m1(self, p0: _T1, p1: _T2, p2: _T3) -> _T1 | _T2: ... def m2(self) -> _T1: ... def m3(self) -> _T2: ... def m4(self) -> _T3: ... # This should generate an error because _T3 should be contravariant
Protocol1
python
apache__airflow
helm-tests/tests/chart_utils/helm_template_generator.py
{ "start": 5544, "end": 7754 }
class ____(subprocess.CalledProcessError): def __str__(self): return f"Helm command failed. Args: {self.args}\nStderr: \n{self.stderr.decode('utf-8')}" def render_chart( name="release-name", values=None, show_only=None, chart_dir=None, kubernetes_version=DEFAULT_KUBERNETES_VERSION, namespace=None, ): """ Function that renders a helm chart into dictionaries. For helm chart testing only """ values = values or {} chart_dir = chart_dir or str(CHART_DIR) namespace = namespace or "default" with NamedTemporaryFile() as tmp_file: content = yaml.dump(values) tmp_file.write(content.encode()) tmp_file.flush() command = [ "helm", "template", name, chart_dir, "--values", tmp_file.name, "--kube-version", kubernetes_version, "--namespace", namespace, ] if show_only: for i in show_only: command.extend(["--show-only", i]) result = subprocess.run(command, check=False, capture_output=True, cwd=chart_dir) if result.returncode: raise HelmFailedError(result.returncode, result.args, result.stdout, result.stderr) templates = result.stdout k8s_objects = yaml.full_load_all(templates) k8s_objects = [k8s_object for k8s_object in k8s_objects if k8s_object] # type: ignore for k8s_object in k8s_objects: validate_k8s_object(k8s_object, kubernetes_version) return k8s_objects def prepare_k8s_lookup_dict(k8s_objects) -> dict[tuple[str, str], dict[str, Any]]: """ Helper to create a lookup dict from k8s_objects. The keys of the dict are the k8s object's kind and name """ k8s_obj_by_key = { (k8s_object["kind"], k8s_object["metadata"]["name"]): k8s_object for k8s_object in k8s_objects } return k8s_obj_by_key def render_k8s_object(obj, type_to_render): """ Function that renders dictionaries into k8s objects. For helm chart testing only. """ return api_client._ApiClient__deserialize_model(obj, type_to_render)
HelmFailedError
python
ansible__ansible
test/integration/targets/plugin_config_for_inventory/cache_plugins/none.py
{ "start": 738, "end": 1453 }
class ____(BaseCacheModule): def __init__(self, *args, **kwargs): super(CacheModule, self).__init__(*args, **kwargs) self.empty = {} self._timeout = self.get_option('_timeout') def get(self, key): return self.empty.get(key) def set(self, key, value): return value def keys(self): return self.empty.keys() def contains(self, key): return key in self.empty def delete(self, key): del self.emtpy[key] def flush(self): self.empty = {} def copy(self): return self.empty.copy() def __getstate__(self): return self.copy() def __setstate__(self, data): self.empty = data
CacheModule
python
readthedocs__readthedocs.org
readthedocs/core/unresolver.py
{ "start": 2211, "end": 2489 }
class ____(UnresolverError): def __init__(self, project, version_slug, external_version_slug): self.project = project self.version_slug = version_slug self.external_version_slug = external_version_slug @dataclass(slots=True)
InvalidExternalVersionError
python
apache__airflow
airflow-core/tests/unit/core/test_stats.py
{ "start": 6433, "end": 10682 }
class ____: def setup_method(self): pytest.importorskip("datadog") from datadog import DogStatsd self.dogstatsd_client = Mock(spec=DogStatsd) self.dogstatsd = SafeDogStatsdLogger(self.dogstatsd_client) def test_increment_counter_with_valid_name_with_dogstatsd(self): self.dogstatsd.incr("test_stats_run") self.dogstatsd_client.increment.assert_called_once_with( metric="test_stats_run", sample_rate=1, tags=[], value=1 ) def test_stat_name_must_be_a_string_with_dogstatsd(self): self.dogstatsd.incr([]) self.dogstatsd_client.assert_not_called() def test_stat_name_must_not_exceed_max_length_with_dogstatsd(self): self.dogstatsd.incr("X" * 300) self.dogstatsd_client.assert_not_called() def test_stat_name_must_only_include_allowed_characters_with_dogstatsd(self): self.dogstatsd.incr("test/$tats") self.dogstatsd_client.assert_not_called() def test_does_send_stats_using_dogstatsd_when_dogstatsd_on(self): self.dogstatsd.incr("empty_key") self.dogstatsd_client.increment.assert_called_once_with( metric="empty_key", sample_rate=1, tags=[], value=1 ) def test_does_send_stats_using_dogstatsd_with_tags_without_enabled_metrics_tags(self): self.dogstatsd.incr("empty_key", 1, 1, tags={"key1": "value1", "key2": "value2"}) self.dogstatsd_client.increment.assert_called_once_with( metric="empty_key", sample_rate=1, tags=[], value=1 ) def test_does_send_stats_using_dogstatsd_when_statsd_and_dogstatsd_both_on(self): """Test that dogstatsd works when both statsd and dogstatsd are enabled (dogstatsd takes precedence).""" self.dogstatsd.incr("empty_key") self.dogstatsd_client.increment.assert_called_once_with( metric="empty_key", sample_rate=1, tags=[], value=1 ) @mock.patch.object(time, "perf_counter", side_effect=[0.0, 100.0]) def test_timer(self, time_mock): with self.dogstatsd.timer("empty_timer") as timer: pass self.dogstatsd_client.timed.assert_called_once_with("empty_timer", tags=[]) expected_duration = 1000.0 * 100.0 assert expected_duration == timer.duration assert time_mock.call_count == 2 def test_empty_timer(self): with self.dogstatsd.timer(): pass self.dogstatsd_client.timed.assert_not_called() def test_timing(self): import datetime self.dogstatsd.timing("empty_timer", 123) self.dogstatsd_client.timing.assert_called_once_with(metric="empty_timer", value=123, tags=[]) self.dogstatsd.timing("empty_timer", datetime.timedelta(seconds=123)) self.dogstatsd_client.timing.assert_called_with(metric="empty_timer", value=123000.0, tags=[]) def test_gauge(self): self.dogstatsd.gauge("empty", 123) self.dogstatsd_client.gauge.assert_called_once_with(metric="empty", sample_rate=1, value=123, tags=[]) def test_decr(self): self.dogstatsd.decr("empty") self.dogstatsd_client.decrement.assert_called_once_with( metric="empty", sample_rate=1, value=1, tags=[] ) def test_enabled_by_config(self): """Test that enabling this sets the right instance properties""" from datadog import DogStatsd with conf_vars({("metrics", "statsd_datadog_enabled"): "True"}): importlib.reload(airflow.stats) assert isinstance(airflow.stats.Stats.dogstatsd, DogStatsd) assert not hasattr(airflow.stats.Stats, "statsd") # Avoid side-effects importlib.reload(airflow.stats) def test_does_not_send_stats_using_statsd_when_statsd_and_dogstatsd_both_on(self): from datadog import DogStatsd with conf_vars( { ("metrics", "statsd_on"): "True", ("metrics", "statsd_datadog_enabled"): "True", } ): importlib.reload(airflow.stats) assert isinstance(airflow.stats.Stats.dogstatsd, DogStatsd) assert not hasattr(airflow.stats.Stats, "statsd") importlib.reload(airflow.stats)
TestDogStats
python
sqlalchemy__sqlalchemy
test/orm/test_froms.py
{ "start": 1762, "end": 4680 }
class ____(_fixtures.FixtureTest): run_setup_mappers = "once" run_inserts = "once" run_deletes = None @classmethod def setup_mappers(cls): ( Node, composite_pk_table, users, Keyword, items, Dingaling, order_items, item_keywords, Item, User, dingalings, Address, keywords, CompositePk, nodes, Order, orders, addresses, ) = ( cls.classes.Node, cls.tables.composite_pk_table, cls.tables.users, cls.classes.Keyword, cls.tables.items, cls.classes.Dingaling, cls.tables.order_items, cls.tables.item_keywords, cls.classes.Item, cls.classes.User, cls.tables.dingalings, cls.classes.Address, cls.tables.keywords, cls.classes.CompositePk, cls.tables.nodes, cls.classes.Order, cls.tables.orders, cls.tables.addresses, ) cls.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( Address, backref="user", order_by=addresses.c.id ), "orders": relationship( Order, backref="user", order_by=orders.c.id ), # o2m, m2o }, ) cls.mapper_registry.map_imperatively( Address, addresses, properties={ "dingaling": relationship( Dingaling, uselist=False, backref="address" ) # o2o }, ) cls.mapper_registry.map_imperatively(Dingaling, dingalings) cls.mapper_registry.map_imperatively( Order, orders, properties={ "items": relationship( Item, secondary=order_items, order_by=items.c.id ), # m2m "address": relationship(Address), # m2o }, ) cls.mapper_registry.map_imperatively( Item, items, properties={ "keywords": relationship(Keyword, secondary=item_keywords) }, ) # m2m cls.mapper_registry.map_imperatively(Keyword, keywords) cls.mapper_registry.map_imperatively( Node, nodes, properties={ "children": relationship( Node, backref=backref("parent", remote_side=[nodes.c.id]) ) }, ) cls.mapper_registry.map_imperatively(CompositePk, composite_pk_table) configure_mappers()
QueryTest
python
astropy__astropy
astropy/modeling/tests/test_parameters.py
{ "start": 1495, "end": 4561 }
class ____(FittableModel): alpha = Parameter(name="alpha", default=42) @staticmethod def evaluate(*args): pass def test__tofloat(): # iterable value = _tofloat([1, 2, 3]) assert isinstance(value, np.ndarray) assert (value == np.array([1, 2, 3])).all() assert np.all([isinstance(val, float) for val in value]) value = _tofloat(np.array([1, 2, 3])) assert isinstance(value, np.ndarray) assert (value == np.array([1, 2, 3])).all() assert np.all([isinstance(val, float) for val in value]) MESSAGE = r"Parameter of .* could not be converted to float" with pytest.raises(InputParameterError, match=MESSAGE): _tofloat("test") # quantity assert _tofloat(1 * u.m) == 1 * u.m # dimensions/scalar array value = _tofloat(np.asanyarray(3)) assert isinstance(value, float) assert value == 3 # A regular number value = _tofloat(3) assert isinstance(value, float) assert value == 3 value = _tofloat(3.0) assert isinstance(value, float) assert value == 3 value = _tofloat(np.float32(3)) assert isinstance(value, float) assert value == 3 value = _tofloat(np.float64(3)) assert isinstance(value, float) assert value == 3 value = _tofloat(np.int32(3)) assert isinstance(value, float) assert value == 3 value = _tofloat(np.int64(3)) assert isinstance(value, float) assert value == 3 # boolean MESSAGE = r"Expected parameter to be of numerical type, not boolean" with pytest.raises(InputParameterError, match=MESSAGE): _tofloat(True) with pytest.raises(InputParameterError, match=MESSAGE): _tofloat(False) # other class Value: pass MESSAGE = r"Don't know how to convert parameter of .* to float" with pytest.raises(InputParameterError, match=MESSAGE): _tofloat(Value) def test_parameter_properties(): """Test if getting / setting of Parameter properties works.""" p = Parameter("alpha", default=1) assert p.name == "alpha" # Parameter names are immutable with pytest.raises(AttributeError): p.name = "beta" assert p.fixed is False p.fixed = True assert p.fixed is True assert p.tied is False p.tied = lambda _: 0 p.tied = False assert p.tied is False assert p.min is None p.min = 42 assert p.min == 42 p.min = None assert p.min is None assert p.max is None p.max = 41 assert p.max == 41 def test_parameter_operators(): """Test if the parameter arithmetic operators work.""" par = Parameter("alpha", default=42) num = 42.0 val = 3 assert par - val == num - val assert val - par == val - num assert par / val == num / val assert val / par == val / num assert par**val == num**val assert val**par == val**num assert par < 45 assert par > 41 assert par <= par assert par >= par assert par == par assert -par == -num assert abs(par) == abs(num) # Test inherited models
MockModel
python
numba__numba
numba/core/typing/cmathdecl.py
{ "start": 728, "end": 896 }
class ____(ConcreteTemplate): cases = [signature(types.boolean, tp) for tp in sorted(types.complex_domain)] @infer_global(cmath.isfinite)
CMath_predicate
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 72400, "end": 73452 }
class ____(Response): """ Response of events.delete_for_task endpoint. :param deleted: Number of deleted events :type deleted: bool """ _service = "events" _action = "delete_for_task" _version = "2.23" _schema = { "definitions": {}, "properties": { "deleted": { "description": "Number of deleted events", "type": ["boolean", "null"], } }, "type": "object", } def __init__(self, deleted: Optional[bool] = None, **kwargs: Any) -> None: super(DeleteForTaskResponse, self).__init__(**kwargs) self.deleted = deleted @schema_property("deleted") def deleted(self) -> Optional[bool]: return self._property_deleted @deleted.setter def deleted(self, value: Optional[bool]) -> None: if value is None: self._property_deleted = None return self.assert_isinstance(value, "deleted", (bool,)) self._property_deleted = value
DeleteForTaskResponse
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_gen_ai.py
{ "start": 3187, "end": 6948 }
class ____: def dummy_get_credentials(self): pass def setup_method(self): with mock.patch( BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id ): self.hook = GenAIGenerativeModelHook(gcp_conn_id=TEST_GCP_CONN_ID) self.hook.get_credentials = self.dummy_get_credentials @mock.patch(GENERATIVE_MODEL_STRING.format("GenAIGenerativeModelHook.get_genai_client")) def test_text_embedding_model_get_embeddings(self, mock_get_client) -> None: client_mock = mock_get_client.return_value client_mock.models = mock.Mock() self.hook.embed_content( project_id=GCP_PROJECT, location=GCP_LOCATION, contents=TEST_CONTENTS, model=TEST_TEXT_EMBEDDING_MODEL, config=TEST_TEXT_EMBEDDING_CONFIG, ) client_mock.models.embed_content.assert_called_once_with( model=TEST_TEXT_EMBEDDING_MODEL, contents=TEST_CONTENTS, config=TEST_TEXT_EMBEDDING_CONFIG, ) @mock.patch(GENERATIVE_MODEL_STRING.format("GenAIGenerativeModelHook.get_genai_client")) def test_generative_model_generate_content(self, mock_get_client) -> None: client_mock = mock_get_client.return_value client_mock.models = mock.Mock() self.hook.generate_content( project_id=GCP_PROJECT, location=GCP_LOCATION, contents=TEST_CONTENTS, generation_config=TEST_GENERATION_CONFIG, model=TEST_MULTIMODAL_PRETRAINED_MODEL, ) client_mock.models.generate_content.assert_called_once_with( model=TEST_MULTIMODAL_PRETRAINED_MODEL, contents=TEST_CONTENTS, config=TEST_GENERATION_CONFIG, ) @mock.patch(GENERATIVE_MODEL_STRING.format("GenAIGenerativeModelHook.get_genai_client")) def test_supervised_fine_tuning_train(self, mock_get_client) -> None: client_mock = mock_get_client.return_value client_mock.models = mock.Mock() self.hook.supervised_fine_tuning_train( project_id=GCP_PROJECT, location=GCP_LOCATION, source_model=SOURCE_MODEL, training_dataset=TRAIN_DATASET, ) client_mock.tunings.tune.assert_called_once_with( base_model=SOURCE_MODEL, training_dataset=TRAIN_DATASET, config=None, ) @mock.patch(GENERATIVE_MODEL_STRING.format("GenAIGenerativeModelHook.get_genai_client")) def test_count_tokens(self, mock_get_client) -> None: client_mock = mock_get_client.return_value client_mock.models = mock.Mock() self.hook.count_tokens( project_id=GCP_PROJECT, contents=TEST_CONTENTS, location=GCP_LOCATION, model=TEST_MULTIMODAL_PRETRAINED_MODEL, ) client_mock.models.count_tokens.assert_called_once_with( model=TEST_MULTIMODAL_PRETRAINED_MODEL, contents=TEST_CONTENTS, config=None, ) @mock.patch(GENERATIVE_MODEL_STRING.format("GenAIGenerativeModelHook.get_genai_client")) def test_create_cached_content(self, mock_get_client) -> None: client_mock = mock_get_client.return_value client_mock.models = mock.Mock() self.hook.create_cached_content( project_id=GCP_PROJECT, location=GCP_LOCATION, model=TEST_CACHED_MODEL, cached_content_config=CACHED_CONTENT_CONFIG, ) client_mock.caches.create.assert_called_once_with( model=TEST_CACHED_MODEL, config=CACHED_CONTENT_CONFIG, )
TestGenAIGenerativeModelHookWithDefaultProjectId
python
scikit-learn__scikit-learn
sklearn/compose/_target.py
{ "start": 728, "end": 14636 }
class ____(RegressorMixin, BaseEstimator): """Meta-estimator to regress on a transformed target. Useful for applying a non-linear transformation to the target `y` in regression problems. This transformation can be given as a Transformer such as the :class:`~sklearn.preprocessing.QuantileTransformer` or as a function and its inverse such as `np.log` and `np.exp`. The computation during :meth:`fit` is:: regressor.fit(X, func(y)) or:: regressor.fit(X, transformer.transform(y)) The computation during :meth:`predict` is:: inverse_func(regressor.predict(X)) or:: transformer.inverse_transform(regressor.predict(X)) Read more in the :ref:`User Guide <transformed_target_regressor>`. .. versionadded:: 0.20 Parameters ---------- regressor : object, default=None Regressor object such as derived from :class:`~sklearn.base.RegressorMixin`. This regressor will automatically be cloned each time prior to fitting. If `regressor is None`, :class:`~sklearn.linear_model.LinearRegression` is created and used. transformer : object, default=None Estimator object such as derived from :class:`~sklearn.base.TransformerMixin`. Cannot be set at the same time as `func` and `inverse_func`. If `transformer is None` as well as `func` and `inverse_func`, the transformer will be an identity transformer. Note that the transformer will be cloned during fitting. Also, the transformer is restricting `y` to be a numpy array. func : function, default=None Function to apply to `y` before passing to :meth:`fit`. Cannot be set at the same time as `transformer`. If `func is None`, the function used will be the identity function. If `func` is set, `inverse_func` also needs to be provided. The function needs to return a 2-dimensional array. inverse_func : function, default=None Function to apply to the prediction of the regressor. Cannot be set at the same time as `transformer`. The inverse function is used to return predictions to the same space of the original training labels. If `inverse_func` is set, `func` also needs to be provided. The inverse function needs to return a 2-dimensional array. check_inverse : bool, default=True Whether to check that `transform` followed by `inverse_transform` or `func` followed by `inverse_func` leads to the original targets. Attributes ---------- regressor_ : object Fitted regressor. transformer_ : object Transformer used in :meth:`fit` and :meth:`predict`. n_features_in_ : int Number of features seen during :term:`fit`. Only defined if the underlying regressor exposes such an attribute when fit. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 See Also -------- sklearn.preprocessing.FunctionTransformer : Construct a transformer from an arbitrary callable. Notes ----- Internally, the target `y` is always converted into a 2-dimensional array to be used by scikit-learn transformers. At the time of prediction, the output will be reshaped to a have the same number of dimensions as `y`. Examples -------- >>> import numpy as np >>> from sklearn.linear_model import LinearRegression >>> from sklearn.compose import TransformedTargetRegressor >>> tt = TransformedTargetRegressor(regressor=LinearRegression(), ... func=np.log, inverse_func=np.exp) >>> X = np.arange(4).reshape(-1, 1) >>> y = np.exp(2 * X).ravel() >>> tt.fit(X, y) TransformedTargetRegressor(...) >>> tt.score(X, y) 1.0 >>> tt.regressor_.coef_ array([2.]) For a more detailed example use case refer to :ref:`sphx_glr_auto_examples_compose_plot_transformed_target.py`. """ _parameter_constraints: dict = { "regressor": [HasMethods(["fit", "predict"]), None], "transformer": [HasMethods("transform"), None], "func": [callable, None], "inverse_func": [callable, None], "check_inverse": ["boolean"], } def __init__( self, regressor=None, *, transformer=None, func=None, inverse_func=None, check_inverse=True, ): self.regressor = regressor self.transformer = transformer self.func = func self.inverse_func = inverse_func self.check_inverse = check_inverse def _fit_transformer(self, y): """Check transformer and fit transformer. Create the default transformer, fit it and make additional inverse check on a subset (optional). """ if self.transformer is not None and ( self.func is not None or self.inverse_func is not None ): raise ValueError( "'transformer' and functions 'func'/'inverse_func' cannot both be set." ) elif self.transformer is not None: self.transformer_ = clone(self.transformer) else: if (self.func is not None and self.inverse_func is None) or ( self.func is None and self.inverse_func is not None ): lacking_param, existing_param = ( ("func", "inverse_func") if self.func is None else ("inverse_func", "func") ) raise ValueError( f"When '{existing_param}' is provided, '{lacking_param}' must also" f" be provided. If {lacking_param} is supposed to be the default," " you need to explicitly pass it the identity function." ) self.transformer_ = FunctionTransformer( func=self.func, inverse_func=self.inverse_func, validate=True, check_inverse=self.check_inverse, ) # We are transforming the target here and not the features, so we set the # output of FunctionTransformer() to be a numpy array (default) and to not # depend on the global configuration: self.transformer_.set_output(transform="default") # XXX: sample_weight is not currently passed to the # transformer. However, if transformer starts using sample_weight, the # code should be modified accordingly. At the time to consider the # sample_prop feature, it is also a good use case to be considered. self.transformer_.fit(y) if self.check_inverse: idx_selected = slice(None, None, max(1, y.shape[0] // 10)) y_sel = _safe_indexing(y, idx_selected) y_sel_t = self.transformer_.transform(y_sel) if not np.allclose(y_sel, self.transformer_.inverse_transform(y_sel_t)): warnings.warn( ( "The provided functions or transformer are" " not strictly inverse of each other. If" " you are sure you want to proceed regardless" ", set 'check_inverse=False'" ), UserWarning, ) @_fit_context( # TransformedTargetRegressor.regressor/transformer are not validated yet. prefer_skip_nested_validation=False ) def fit(self, X, y, **fit_params): """Fit the model according to the given training data. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Training vector, where `n_samples` is the number of samples and `n_features` is the number of features. y : array-like of shape (n_samples,) Target values. **fit_params : dict - If `enable_metadata_routing=False` (default): Parameters directly passed to the `fit` method of the underlying regressor. - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` method of the underlying regressor. .. versionchanged:: 1.6 See :ref:`Metadata Routing User Guide <metadata_routing>` for more details. Returns ------- self : object Fitted estimator. """ if y is None: raise ValueError( f"This {self.__class__.__name__} estimator " "requires y to be passed, but the target y is None." ) y = check_array( y, input_name="y", accept_sparse=False, ensure_all_finite=True, ensure_2d=False, dtype="numeric", allow_nd=True, ) # store the number of dimension of the target to predict an array of # similar shape at predict self._training_dim = y.ndim # transformers are designed to modify X which is 2d dimensional, we # need to modify y accordingly. if y.ndim == 1: y_2d = y.reshape(-1, 1) else: y_2d = y self._fit_transformer(y_2d) # transform y and convert back to 1d array if needed y_trans = self.transformer_.transform(y_2d) # FIXME: a FunctionTransformer can return a 1D array even when validate # is set to True. Therefore, we need to check the number of dimension # first. if y_trans.ndim == 2 and y_trans.shape[1] == 1 and self._training_dim == 1: y_trans = y_trans.squeeze(axis=1) self.regressor_ = self._get_regressor(get_clone=True) if _routing_enabled(): routed_params = process_routing(self, "fit", **fit_params) else: routed_params = Bunch(regressor=Bunch(fit=fit_params)) self.regressor_.fit(X, y_trans, **routed_params.regressor.fit) if hasattr(self.regressor_, "feature_names_in_"): self.feature_names_in_ = self.regressor_.feature_names_in_ return self def predict(self, X, **predict_params): """Predict using the base regressor, applying inverse. The regressor is used to predict and the `inverse_func` or `inverse_transform` is applied before returning the prediction. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Samples. **predict_params : dict of str -> object - If `enable_metadata_routing=False` (default): Parameters directly passed to the `predict` method of the underlying regressor. - If `enable_metadata_routing=True`: Parameters safely routed to the `predict` method of the underlying regressor. .. versionchanged:: 1.6 See :ref:`Metadata Routing User Guide <metadata_routing>` for more details. Returns ------- y_hat : ndarray of shape (n_samples,) Predicted values. """ check_is_fitted(self) if _routing_enabled(): routed_params = process_routing(self, "predict", **predict_params) else: routed_params = Bunch(regressor=Bunch(predict=predict_params)) pred = self.regressor_.predict(X, **routed_params.regressor.predict) if pred.ndim == 1: pred_trans = self.transformer_.inverse_transform(pred.reshape(-1, 1)) else: pred_trans = self.transformer_.inverse_transform(pred) if ( self._training_dim == 1 and pred_trans.ndim == 2 and pred_trans.shape[1] == 1 ): pred_trans = pred_trans.squeeze(axis=1) return pred_trans def __sklearn_tags__(self): regressor = self._get_regressor() tags = super().__sklearn_tags__() tags.regressor_tags.poor_score = True tags.input_tags.sparse = get_tags(regressor).input_tags.sparse tags.target_tags.multi_output = get_tags(regressor).target_tags.multi_output return tags @property def n_features_in_(self): """Number of features seen during :term:`fit`.""" # For consistency with other estimators we raise an AttributeError so # that hasattr() returns False the estimator isn't fitted. try: check_is_fitted(self) except NotFittedError as nfe: raise AttributeError( "{} object has no n_features_in_ attribute.".format( self.__class__.__name__ ) ) from nfe return self.regressor_.n_features_in_ def get_metadata_routing(self): """Get metadata routing of this object. Please check :ref:`User Guide <metadata_routing>` on how the routing mechanism works. .. versionadded:: 1.6 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating routing information. """ router = MetadataRouter(owner=self).add( regressor=self._get_regressor(), method_mapping=MethodMapping() .add(caller="fit", callee="fit") .add(caller="predict", callee="predict"), ) return router def _get_regressor(self, get_clone=False): if self.regressor is None: return LinearRegression() return clone(self.regressor) if get_clone else self.regressor
TransformedTargetRegressor
python
cython__cython
docs/examples/userguide/language_basics/optional_subclassing.py
{ "start": 15, "end": 96 }
class ____: @cython.cfunc def foo(self): print("A") @cython.cclass
A
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/buffer.py
{ "start": 1523, "end": 4035 }
class ____: """ Immutable class that contains a completion state. """ def __init__( self, original_document: Document, completions: list[Completion] | None = None, complete_index: int | None = None, ) -> None: #: Document as it was when the completion started. self.original_document = original_document #: List of all the current Completion instances which are possible at #: this point. self.completions = completions or [] #: Position in the `completions` array. #: This can be `None` to indicate "no completion", the original text. self.complete_index = complete_index # Position in the `_completions` array. def __repr__(self) -> str: return f"{self.__class__.__name__}({self.original_document!r}, <{len(self.completions)!r}> completions, index={self.complete_index!r})" def go_to_index(self, index: int | None) -> None: """ Create a new :class:`.CompletionState` object with the new index. When `index` is `None` deselect the completion. """ if self.completions: assert index is None or 0 <= index < len(self.completions) self.complete_index = index def new_text_and_position(self) -> tuple[str, int]: """ Return (new_text, new_cursor_position) for this completion. """ if self.complete_index is None: return self.original_document.text, self.original_document.cursor_position else: original_text_before_cursor = self.original_document.text_before_cursor original_text_after_cursor = self.original_document.text_after_cursor c = self.completions[self.complete_index] if c.start_position == 0: before = original_text_before_cursor else: before = original_text_before_cursor[: c.start_position] new_text = before + c.text + original_text_after_cursor new_cursor_position = len(before) + len(c.text) return new_text, new_cursor_position @property def current_completion(self) -> Completion | None: """ Return the current completion, or return `None` when no completion is selected. """ if self.complete_index is not None: return self.completions[self.complete_index] return None _QUOTED_WORDS_RE = re.compile(r"""(\s+|".*?"|'.*?')""")
CompletionState
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/ranges.py
{ "start": 28860, "end": 30171 }
class ____(AbstractRange[Sequence[Range[_T]]]): """Base for PostgreSQL MULTIRANGE types. these are types that return a sequence of :class:`_postgresql.Range` objects. """ __abstract__ = True def _resolve_for_literal(self, value: Sequence[Range[Any]]) -> Any: if not value: # empty MultiRange, SQL datatype can't be determined here return sqltypes.NULLTYPE first = value[0] spec = first.lower if first.lower is not None else first.upper if isinstance(spec, int): # pg is unreasonably picky here: the query # "select 1::INTEGER <@ '{[1, 4),[6,19)}'::INT8MULTIRANGE" raises # "operator does not exist: integer <@ int8multirange" as of pg 16 if all(_is_int32(r) for r in value): return INT4MULTIRANGE() else: return INT8MULTIRANGE() elif isinstance(spec, (Decimal, float)): return NUMMULTIRANGE() elif isinstance(spec, datetime): return TSMULTIRANGE() if not spec.tzinfo else TSTZMULTIRANGE() elif isinstance(spec, date): return DATEMULTIRANGE() else: # empty Range, SQL datatype can't be determined here return sqltypes.NULLTYPE
AbstractMultiRange
python
ray-project__ray
python/ray/util/collective/tests/util.py
{ "start": 285, "end": 4251 }
class ____: def __init__(self): self.buffer = None self.list_buffer = None def init_tensors(self): self.buffer = cp.ones((10,), dtype=cp.float32) self.list_buffer = [cp.ones((10,), dtype=cp.float32) for _ in range(2)] cp.cuda.Stream.null.synchronize() return True def init_group(self, world_size, rank, backend=Backend.NCCL, group_name="default"): col.init_collective_group(world_size, rank, backend, group_name) return True def set_buffer(self, data): self.buffer = data return self.buffer def get_buffer(self): return self.buffer def set_list_buffer(self, list_of_arrays): self.list_buffer = list_of_arrays return self.list_buffer def do_allreduce(self, group_name="default", op=ReduceOp.SUM): col.allreduce(self.buffer, group_name, op) return self.buffer def do_reduce(self, group_name="default", dst_rank=0, op=ReduceOp.SUM): col.reduce(self.buffer, dst_rank, group_name, op) return self.buffer def do_broadcast(self, group_name="default", src_rank=0): col.broadcast(self.buffer, src_rank, group_name) return self.buffer def do_allgather(self, group_name="default"): col.allgather(self.list_buffer, self.buffer, group_name) return self.list_buffer def do_reducescatter(self, group_name="default", op=ReduceOp.SUM): col.reducescatter(self.buffer, self.list_buffer, group_name, op) return self.buffer def do_send(self, group_name="default", dst_rank=0): col.send(self.buffer, dst_rank, group_name) return self.buffer def do_recv(self, group_name="default", src_rank=0): col.recv(self.buffer, src_rank, group_name) return self.buffer def destroy_group(self, group_name="default"): col.destroy_collective_group(group_name) return True def report_rank(self, group_name="default"): rank = col.get_rank(group_name) return rank def report_world_size(self, group_name="default"): ws = col.get_collective_group_size(group_name) return ws def report_nccl_availability(self): avail = col.nccl_available() return avail def report_gloo_availability(self): avail = col.gloo_available() return avail def report_is_group_initialized(self, group_name="default"): is_init = col.is_group_initialized(group_name) return is_init def create_collective_workers(num_workers=2, group_name="default", backend="nccl"): actors = [None] * num_workers for i in range(num_workers): actor = Worker.remote() ray.get([actor.init_tensors.remote()]) actors[i] = actor world_size = num_workers init_results = ray.get( [ actor.init_group.remote(world_size, i, backend, group_name) for i, actor in enumerate(actors) ] ) return actors, init_results def init_tensors_for_gather_scatter( actors, array_size=10, dtype=cp.float32, tensor_backend="cupy" ): world_size = len(actors) for i, a in enumerate(actors): if tensor_backend == "cupy": t = cp.ones(array_size, dtype=dtype) * (i + 1) elif tensor_backend == "torch": t = torch.ones(array_size, dtype=torch.float32).cuda() * (i + 1) else: raise RuntimeError("Unsupported tensor backend.") ray.get([a.set_buffer.remote(t)]) if tensor_backend == "cupy": list_buffer = [cp.ones(array_size, dtype=dtype) for _ in range(world_size)] elif tensor_backend == "torch": list_buffer = [ torch.ones(array_size, dtype=torch.float32).cuda() for _ in range(world_size) ] else: raise RuntimeError("Unsupported tensor backend.") ray.get([a.set_list_buffer.remote(list_buffer) for a in actors]) @ray.remote(num_gpus=2)
Worker
python
walkccc__LeetCode
solutions/2983. Palindrome Rearrangement Queries/2983.py
{ "start": 0, "end": 2864 }
class ____: def canMakePalindromeQueries( self, s: str, queries: list[list[int]], ) -> list[bool]: n = len(s) # mirroredDiffs[i] := the number of different letters between the first i # letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1] mirroredDiffs = self._getMirroredDiffs(s) # counts[i] := the count of s[0..i) counts = self._getCounts(s) ans = [] def subtractArrays(a: list[int], b: list[int]): return [x - y for x, y in zip(a, b)] for a, b, c, d in queries: # Use left-closed, right-open intervals to facilitate the calculation. # ...... [a, b) ...|... [rb, ra) ...... # .... [rd, rc) .....|..... [c, d) .... b += 1 d += 1 ra = n - a # the reflected index of a in s[n / 2..n) rb = n - b # the reflected index of b in s[n / 2..n) rc = n - c # the reflected index of c in s[n / 2..n) rd = n - d # the reflected index of d in s[n / 2..n) # No difference is allowed outside the query ranges. if ((min(a, rd) > 0 and mirroredDiffs[min(a, rd)] > 0) or (n // 2 > max(b, rc) and mirroredDiffs[n // 2] - mirroredDiffs[max(b, rc)] > 0) or (rd > b and mirroredDiffs[rd] - mirroredDiffs[b] > 0) or (a > rc and mirroredDiffs[a] - mirroredDiffs[rc] > 0)): ans.append(False) else: # The `count` map of the intersection of [a, b) and [rd, rc) in # s[0..n / 2) must equate to the `count` map of the intersection of # [c, d) and [rb, ra) in s[n / 2..n). leftRangeCount = subtractArrays(counts[b], counts[a]) rightRangeCount = subtractArrays(counts[d], counts[c]) if a > rd: rightRangeCount = subtractArrays( rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd])) if rc > b: rightRangeCount = subtractArrays( rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)])) if c > rb: leftRangeCount = subtractArrays( leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb])) if ra > d: leftRangeCount = subtractArrays( leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)])) ans.append(min(leftRangeCount) >= 0 and min(rightRangeCount) >= 0 and leftRangeCount == rightRangeCount) return ans def _getMirroredDiffs(self, s: str) -> list[int]: diffs = [0] for i, j in zip(range(len(s)), reversed(range(len(s)))): if i >= j: break diffs.append(diffs[-1] + (s[i] != s[j])) return diffs def _getCounts(self, s: str) -> list[list[int]]: count = [0] * 26 counts = [count.copy()] for c in s: count[ord(c) - ord('a')] += 1 counts.append(count.copy()) return counts
Solution
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/executors/ecs/utils.py
{ "start": 5201, "end": 9759 }
class ____: """A five-way dictionary between Airflow task ids, Airflow cmds, ECS ARNs, and ECS task objects.""" def __init__(self): self.key_to_arn: dict[TaskInstanceKey, str] = {} self.arn_to_key: dict[str, TaskInstanceKey] = {} self.tasks: dict[str, EcsExecutorTask] = {} self.key_to_failure_counts: dict[TaskInstanceKey, int] = defaultdict(int) self.key_to_task_info: dict[TaskInstanceKey, EcsTaskInfo] = {} def add_task( self, task: EcsExecutorTask, airflow_task_key: TaskInstanceKey, queue: str, airflow_cmd: CommandType, exec_config: ExecutorConfigType, attempt_number: int, ): """Add a task to the collection.""" arn = task.task_arn self.tasks[arn] = task self.key_to_arn[airflow_task_key] = arn self.arn_to_key[arn] = airflow_task_key self.key_to_task_info[airflow_task_key] = EcsTaskInfo(airflow_cmd, queue, exec_config) self.key_to_failure_counts[airflow_task_key] = attempt_number def update_task(self, task: EcsExecutorTask): """Update the state of the given task based on task ARN.""" self.tasks[task.task_arn] = task def task_by_key(self, task_key: TaskInstanceKey) -> EcsExecutorTask: """Get a task by Airflow Instance Key.""" arn = self.key_to_arn[task_key] return self.task_by_arn(arn) def task_by_arn(self, arn) -> EcsExecutorTask: """Get a task by AWS ARN.""" return self.tasks[arn] def pop_by_key(self, task_key: TaskInstanceKey) -> EcsExecutorTask: """Delete task from collection based off of Airflow Task Instance Key.""" arn = self.key_to_arn[task_key] task = self.tasks[arn] del self.key_to_arn[task_key] del self.key_to_task_info[task_key] del self.arn_to_key[arn] del self.tasks[arn] if task_key in self.key_to_failure_counts: del self.key_to_failure_counts[task_key] return task def get_all_arns(self) -> list[str]: """Get all AWS ARNs in collection.""" return list(self.key_to_arn.values()) def get_all_task_keys(self) -> list[TaskInstanceKey]: """Get all Airflow Task Keys in collection.""" return list(self.key_to_arn.keys()) def failure_count_by_key(self, task_key: TaskInstanceKey) -> int: """Get the number of times a task has failed given an Airflow Task Key.""" return self.key_to_failure_counts[task_key] def increment_failure_count(self, task_key: TaskInstanceKey): """Increment the failure counter given an Airflow Task Key.""" self.key_to_failure_counts[task_key] += 1 def info_by_key(self, task_key: TaskInstanceKey) -> EcsTaskInfo: """Get the Airflow Command given an Airflow task key.""" return self.key_to_task_info[task_key] def __getitem__(self, value): """Get a task by AWS ARN.""" return self.task_by_arn(value) def __len__(self): """Determine the number of tasks in collection.""" return len(self.tasks) def _recursive_flatten_dict(nested_dict): """ Recursively unpack a nested dict and return it as a flat dict. For example, _flatten_dict({'a': 'a', 'b': 'b', 'c': {'d': 'd'}}) returns {'a': 'a', 'b': 'b', 'd': 'd'}. """ items = [] for key, value in nested_dict.items(): if isinstance(value, dict): items.extend(_recursive_flatten_dict(value).items()) else: items.append((key, value)) return dict(items) def parse_assign_public_ip(assign_public_ip, is_launch_type_ec2=False): """Convert "assign_public_ip" from True/False to ENABLE/DISABLE.""" # If the launch type is EC2, you cannot/should not provide the assignPublicIp parameter (which is # specific to Fargate) if not is_launch_type_ec2: return "ENABLED" if assign_public_ip == "True" else "DISABLED" def camelize_dict_keys(nested_dict) -> dict: """Accept a potentially nested dictionary and recursively convert all keys into camelCase.""" result = {} for key, value in nested_dict.items(): new_key = camelize(key, uppercase_first_letter=False) if isinstance(value, dict) and (key.lower() != "tags"): # The key name on tags can be whatever the user wants, and we should not mess with them. result[new_key] = camelize_dict_keys(value) else: result[new_key] = nested_dict[key] return result
EcsTaskCollection
python
django__django
tests/template_tests/syntax_tests/test_basic.py
{ "start": 14810, "end": 15833 }
class ____(SimpleTestCase): template_error_msg = ( "Invalid block tag on line 1: 'endfor'. Did you forget to register or " "load this tag?" ) def test_template_name_in_error_message(self): msg = f"Template: test.html, {self.template_error_msg}" with self.assertRaisesMessage(TemplateSyntaxError, msg): Template("{% endfor %}", origin=Origin("test.html")) def test_template_name_not_in_debug_view(self): try: Template("{% endfor %}", origin=Origin("test.html")) except TemplateSyntaxError as e: reporter = ExceptionReporter(None, e.__class__, e, None) traceback_data = reporter.get_traceback_data() self.assertEqual(traceback_data["exception_value"], self.template_error_msg) def test_unknown_source_template(self): try: Template("{% endfor %}") except TemplateSyntaxError as e: self.assertEqual(str(e), self.template_error_msg)
TemplateNameInExceptionTests
python
dagster-io__dagster
python_modules/libraries/dagster-dg-cli/dagster_dg_cli_tests/cli_tests/api_tests/schedule_tests/test_business_logic.py
{ "start": 574, "end": 7411 }
class ____: """Test the pure functions that process GraphQL responses.""" def test_process_schedules_response_success(self, snapshot): """Test processing a successful schedules GraphQL response.""" # Sample GraphQL response structure response = { "schedulesOrError": { "__typename": "Schedules", "results": [ { "id": "schedule1-id", "name": "daily_job", "cronSchedule": "0 0 * * *", "pipelineName": "daily_pipeline", "description": "Runs daily at midnight", "executionTimezone": "UTC", "scheduleState": {"status": "RUNNING"}, }, { "id": "schedule2-id", "name": "hourly_job", "cronSchedule": "0 * * * *", "pipelineName": "hourly_pipeline", "description": "Runs every hour", "executionTimezone": "America/New_York", "scheduleState": {"status": "STOPPED"}, }, ], } } result = process_schedules_response(response) # Snapshot the entire result to capture structure and data snapshot.assert_match(result) def test_process_schedules_response_empty(self, snapshot): """Test processing an empty schedules GraphQL response.""" response = {"schedulesOrError": {"__typename": "Schedules", "results": []}} result = process_schedules_response(response) # Snapshot empty result snapshot.assert_match(result) def test_process_schedules_response_missing_key(self, snapshot): """Test processing a response missing the schedulesOrError key.""" malformed_response = {} try: result = process_schedules_response(malformed_response) # If no exception, snapshot the result snapshot.assert_match(result) except Exception as e: # Snapshot the error message snapshot.assert_match({"error": str(e)}) def test_process_schedules_response_error_typename(self, snapshot): """Test processing a schedules response with error typename.""" error_response = { "schedulesOrError": { "__typename": "RepositoryNotFoundError", "message": "Repository not found", } } try: result = process_schedules_response(error_response) snapshot.assert_match(result) except Exception as e: snapshot.assert_match({"error": str(e)}) def test_process_repositories_response_success(self, snapshot): """Test processing a successful repositories GraphQL response.""" response = { "repositoriesOrError": { "__typename": "RepositoryConnection", "nodes": [ { "name": "main_repo", "location": {"name": "main_location"}, "schedules": [ { "id": "schedule1-id", "name": "daily_job", "cronSchedule": "0 0 * * *", "pipelineName": "daily_pipeline", "description": "Runs daily at midnight", "executionTimezone": "UTC", "scheduleState": {"status": "RUNNING"}, }, { "id": "schedule2-id", "name": "weekly_job", "cronSchedule": "0 0 * * 0", "pipelineName": "weekly_pipeline", "description": "Runs weekly on Sunday", "executionTimezone": None, "scheduleState": {"status": "STOPPED"}, }, ], }, { "name": "secondary_repo", "location": {"name": "secondary_location"}, "schedules": [ { "id": "schedule3-id", "name": "hourly_job", "cronSchedule": "0 * * * *", "pipelineName": "hourly_pipeline", "description": None, "executionTimezone": "America/Chicago", "scheduleState": {"status": "RUNNING"}, } ], }, ], } } result = process_repositories_response(response) # Snapshot the entire result to capture structure and data snapshot.assert_match(result) def test_process_repositories_response_empty(self, snapshot): """Test processing an empty repositories GraphQL response.""" response = {"repositoriesOrError": {"__typename": "RepositoryConnection", "nodes": []}} result = process_repositories_response(response) snapshot.assert_match(result) def test_process_schedule_response_success(self, snapshot): """Test processing a successful single schedule GraphQL response.""" response = { "scheduleOrError": { "__typename": "Schedule", "id": "single-schedule-id", "name": "critical_job", "cronSchedule": "0 0 * * *", "pipelineName": "critical_pipeline", "description": "Critical production schedule", "executionTimezone": "UTC", "scheduleState": {"status": "RUNNING"}, } } result = process_schedule_response(response) snapshot.assert_match(result) def test_process_schedule_response_not_found_error(self, snapshot): """Test processing a schedule not found error.""" error_response = { "scheduleOrError": { "__typename": "ScheduleNotFoundError", "message": "Schedule 'nonexistent_schedule' not found", } } try: result = process_schedule_response(error_response) snapshot.assert_match(result) except Exception as e: snapshot.assert_match({"error": str(e)})
TestProcessScheduleResponses
python
donnemartin__interactive-coding-challenges
graphs_trees/check_balance/test_check_balance.py
{ "start": 18, "end": 1043 }
class ____(unittest.TestCase): def test_check_balance_empty(self): bst = BstBalance(None) bst.check_balance() def test_check_balance(self): bst = BstBalance(Node(5)) self.assertEqual(bst.check_balance(), True) bst.insert(3) bst.insert(8) bst.insert(1) bst.insert(4) self.assertEqual(bst.check_balance(), True) bst = BstBalance(Node(5)) bst.insert(3) bst.insert(8) bst.insert(9) bst.insert(10) self.assertEqual(bst.check_balance(), False) bst = BstBalance(Node(3)) bst.insert(2) bst.insert(1) bst.insert(5) bst.insert(4) bst.insert(6) bst.insert(7) self.assertEqual(bst.check_balance(), True) print('Success: test_check_balance') def main(): test = TestCheckBalance() test.assertRaises(TypeError, test.test_check_balance_empty) test.test_check_balance() if __name__ == '__main__': main()
TestCheckBalance
python
langchain-ai__langchain
libs/core/langchain_core/utils/aiter.py
{ "start": 8996, "end": 10574 }
class ____(AbstractAsyncContextManager): # noqa: N801 """Async context manager to wrap an AsyncGenerator that has a `aclose()` method. Code like this: ```python async with aclosing(<module>.fetch(<arguments>)) as agen: <block> ``` is equivalent to this: ```python agen = <module>.fetch(<arguments>) try: <block> finally: await agen.aclose() ``` """ def __init__(self, thing: AsyncGenerator[Any, Any] | AsyncIterator[Any]) -> None: """Create the context manager. Args: thing: The resource to wrap. """ self.thing = thing @override async def __aenter__(self) -> AsyncGenerator[Any, Any] | AsyncIterator[Any]: return self.thing @override async def __aexit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None: if hasattr(self.thing, "aclose"): await self.thing.aclose() async def abatch_iterate( size: int, iterable: AsyncIterable[T] ) -> AsyncIterator[list[T]]: """Utility batching function for async iterables. Args: size: The size of the batch. iterable: The async iterable to batch. Yields: The batches. """ batch: list[T] = [] async for element in iterable: if len(batch) < size: batch.append(element) if len(batch) >= size: yield batch batch = [] if batch: yield batch
aclosing
python
pytorch__pytorch
torch/package/package_importer.py
{ "start": 1904, "end": 28601 }
class ____(Importer): """Importers allow you to load code written to packages by :class:`PackageExporter`. Code is loaded in a hermetic way, using files from the package rather than the normal python import system. This allows for the packaging of PyTorch model code and data so that it can be run on a server or used in the future for transfer learning. The importer for packages ensures that code in the module can only be loaded from within the package, except for modules explicitly listed as external during export. The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on. This prevents "implicit" dependencies where the package runs locally because it is importing a locally-installed package, but then fails when the package is copied to another machine. """ """The dictionary of already loaded modules from this package, equivalent to ``sys.modules`` but local to this importer. """ modules: dict[str, types.ModuleType] def __init__( self, file_or_buffer: Union[FileLike, torch._C.PyTorchFileReader], module_allowed: Callable[[str], bool] = lambda module_name: True, ): """Open ``file_or_buffer`` for importing. This checks that the imported package only requires modules allowed by ``module_allowed`` Args: file_or_buffer: a file-like object (has to implement :meth:`read`, :meth:`readline`, :meth:`tell`, and :meth:`seek`), a string, or an ``os.PathLike`` object containing a filename. module_allowed (Callable[[str], bool], optional): A method to determine if a externally provided module should be allowed. Can be used to ensure packages loaded do not depend on modules that the server does not support. Defaults to allowing anything. Raises: ImportError: If the package will use a disallowed module. """ torch._C._log_api_usage_once("torch.package.PackageImporter") self.zip_reader: Any if isinstance(file_or_buffer, torch._C.PyTorchFileReader): self.filename = "<pytorch_file_reader>" self.zip_reader = file_or_buffer elif isinstance(file_or_buffer, (os.PathLike, str)): self.filename = os.fspath(file_or_buffer) if not os.path.isdir(self.filename): self.zip_reader = torch._C.PyTorchFileReader(self.filename) else: self.zip_reader = DirectoryReader(self.filename) else: self.filename = "<binary>" self.zip_reader = torch._C.PyTorchFileReader(file_or_buffer) torch._C._log_api_usage_metadata( "torch.package.PackageImporter.metadata", { "serialization_id": self.zip_reader.serialization_id(), "file_name": self.filename, }, ) self.root = _PackageNode(None) self.modules = {} self.extern_modules = self._read_extern() for extern_module in self.extern_modules: if not module_allowed(extern_module): raise ImportError( f"package '{file_or_buffer}' needs the external module '{extern_module}' " f"but that module has been disallowed" ) self._add_extern(extern_module) for fname in self.zip_reader.get_all_records(): self._add_file(fname) self.patched_builtins = builtins.__dict__.copy() self.patched_builtins["__import__"] = self.__import__ # Allow packaged modules to reference their PackageImporter self.modules["torch_package_importer"] = self # type: ignore[assignment] self._mangler = PackageMangler() # used for reduce deserializaiton self.storage_context: Any = None self.last_map_location = None # used for torch.serialization._load self.Unpickler = lambda *args, **kwargs: PackageUnpickler(self, *args, **kwargs) def import_module(self, name: str, package=None): """Load a module from the package if it hasn't already been loaded, and then return the module. Modules are loaded locally to the importer and will appear in ``self.modules`` rather than ``sys.modules``. Args: name (str): Fully qualified name of the module to load. package ([type], optional): Unused, but present to match the signature of importlib.import_module. Defaults to ``None``. Returns: types.ModuleType: The (possibly already) loaded module. """ # We should always be able to support importing modules from this package. # This is to support something like: # obj = importer.load_pickle(...) # importer.import_module(obj.__module__) <- this string will be mangled # # Note that _mangler.demangle will not demangle any module names # produced by a different PackageImporter instance. name = self._mangler.demangle(name) return self._gcd_import(name) def load_binary(self, package: str, resource: str) -> bytes: """Load raw bytes. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. Returns: bytes: The loaded data. """ path = self._zipfile_path(package, resource) return self.zip_reader.get_record(path) def load_text( self, package: str, resource: str, encoding: str = "utf-8", errors: str = "strict", ) -> str: """Load a string. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. encoding (str, optional): Passed to ``decode``. Defaults to ``'utf-8'``. errors (str, optional): Passed to ``decode``. Defaults to ``'strict'``. Returns: str: The loaded text. """ data = self.load_binary(package, resource) return data.decode(encoding, errors) def load_pickle(self, package: str, resource: str, map_location=None) -> Any: """Unpickles the resource from the package, loading any modules that are needed to construct the objects using :meth:`import_module`. Args: package (str): The name of module package (e.g. ``"my_package.my_subpackage"``). resource (str): The unique name for the resource. map_location: Passed to `torch.load` to determine how tensors are mapped to devices. Defaults to ``None``. Returns: Any: The unpickled object. """ pickle_file = self._zipfile_path(package, resource) restore_location = _get_restore_location(map_location) loaded_storages = {} loaded_reduces = {} storage_context = torch._C.DeserializationStorageContext() def load_tensor(dtype, size, key, location, restore_location): name = f"{key}.storage" if storage_context.has_storage(name): storage = storage_context.get_storage(name, dtype)._typed_storage() else: tensor = self.zip_reader.get_storage_from_record( ".data/" + name, size, dtype ) if isinstance(self.zip_reader, torch._C.PyTorchFileReader): storage_context.add_storage(name, tensor) storage = tensor._typed_storage() loaded_storages[key] = restore_location(storage, location) def persistent_load(saved_id): assert isinstance(saved_id, tuple) typename = _maybe_decode_ascii(saved_id[0]) data = saved_id[1:] if typename == "storage": storage_type, key, location, size = data if storage_type is torch.UntypedStorage: dtype = torch.uint8 else: dtype = storage_type.dtype if key not in loaded_storages: load_tensor( dtype, size, key, _maybe_decode_ascii(location), restore_location, ) storage = loaded_storages[key] # TODO: Once we decide to break serialization FC, we can # stop wrapping with TypedStorage return torch.storage.TypedStorage( wrap_storage=storage._untyped_storage, dtype=dtype, _internal=True ) elif typename == "reduce_package": # to fix BC breaking change, objects on this load path # will be loaded multiple times erroneously if len(data) == 2: func, args = data return func(self, *args) reduce_id, func, args = data if reduce_id not in loaded_reduces: loaded_reduces[reduce_id] = func(self, *args) return loaded_reduces[reduce_id] else: f"Unknown typename for persistent_load, expected 'storage' or 'reduce_package' but got '{typename}'" # Load the data (which may in turn use `persistent_load` to load tensors) data_file = io.BytesIO(self.zip_reader.get_record(pickle_file)) unpickler = self.Unpickler(data_file) unpickler.persistent_load = persistent_load # type: ignore[assignment] @contextmanager def set_deserialization_context(): # to let reduce_package access deserializaiton context self.storage_context = storage_context self.last_map_location = map_location try: yield finally: self.storage_context = None self.last_map_location = None with set_deserialization_context(): result = unpickler.load() # TODO from zdevito: # This stateful weird function will need to be removed in our efforts # to unify the format. It has a race condition if multiple python # threads try to read independent files torch._utils._validate_loaded_sparse_tensors() return result def id(self): """ Returns internal identifier that torch.package uses to distinguish :class:`PackageImporter` instances. Looks like:: <torch_package_0> """ return self._mangler.parent_name() def file_structure( self, *, include: "GlobPattern" = "**", exclude: "GlobPattern" = () ) -> Directory: """Returns a file structure representation of package's zipfile. Args: include (Union[List[str], str]): An optional string e.g. ``"my_package.my_subpackage"``, or optional list of strings for the names of the files to be included in the zipfile representation. This can also be a glob-style pattern, as described in :meth:`PackageExporter.mock` exclude (Union[List[str], str]): An optional pattern that excludes files whose name match the pattern. Returns: :class:`Directory` """ return _create_directory_from_file_list( self.filename, self.zip_reader.get_all_records(), include, exclude ) def python_version(self): """Returns the version of python that was used to create this package. Note: this function is experimental and not Forward Compatible. The plan is to move this into a lock file later on. Returns: :class:`Optional[str]` a python version e.g. 3.8.9 or None if no version was stored with this package """ python_version_path = ".data/python_version" return ( self.zip_reader.get_record(python_version_path).decode("utf-8").strip() if self.zip_reader.has_record(python_version_path) else None ) def _read_extern(self): return ( self.zip_reader.get_record(".data/extern_modules") .decode("utf-8") .splitlines(keepends=False) ) def _make_module( self, name: str, filename: Optional[str], is_package: bool, parent: str ): mangled_filename = self._mangler.mangle(filename) if filename else None spec = importlib.machinery.ModuleSpec( name, self, # type: ignore[arg-type] origin="<package_importer>", is_package=is_package, ) module = importlib.util.module_from_spec(spec) self.modules[name] = module module.__name__ = self._mangler.mangle(name) ns = module.__dict__ ns["__spec__"] = spec ns["__loader__"] = self ns["__file__"] = mangled_filename ns["__cached__"] = None ns["__builtins__"] = self.patched_builtins ns["__torch_package__"] = True # Add this module to our private global registry. It should be unique due to mangling. assert module.__name__ not in _package_imported_modules _package_imported_modules[module.__name__] = module # preemptively install on the parent to prevent IMPORT_FROM from trying to # access sys.modules self._install_on_parent(parent, name, module) if filename is not None: assert mangled_filename is not None # preemptively install the source in `linecache` so that stack traces, # `inspect`, etc. work. assert filename not in linecache.cache # type: ignore[attr-defined] linecache.lazycache(mangled_filename, ns) code = self._compile_source(filename, mangled_filename) exec(code, ns) return module def _load_module(self, name: str, parent: str): cur: _PathNode = self.root for atom in name.split("."): if not isinstance(cur, _PackageNode) or atom not in cur.children: if name in IMPLICIT_IMPORT_ALLOWLIST: module = self.modules[name] = importlib.import_module(name) return module raise ModuleNotFoundError( f'No module named "{name}" in self-contained archive "{self.filename}"' f" and the module is also not in the list of allowed external modules: {self.extern_modules}", name=name, ) cur = cur.children[atom] if isinstance(cur, _ExternNode): module = self.modules[name] = importlib.import_module(name) if compat_mapping := EXTERN_IMPORT_COMPAT_NAME_MAPPING.get(name): for old_name, new_name in compat_mapping.items(): module.__dict__.setdefault(old_name, new_name) return module return self._make_module( name, cur.source_file, # type: ignore[attr-defined] isinstance(cur, _PackageNode), parent, ) def _compile_source(self, fullpath: str, mangled_filename: str): source = self.zip_reader.get_record(fullpath) source = _normalize_line_endings(source) return compile(source, mangled_filename, "exec", dont_inherit=True) # note: named `get_source` so that linecache can find the source # when this is the __loader__ of a module. def get_source(self, module_name) -> str: # linecache calls `get_source` with the `module.__name__` as the argument, so we must demangle it here. module = self.import_module(demangle(module_name)) return self.zip_reader.get_record(demangle(module.__file__)).decode("utf-8") # note: named `get_resource_reader` so that importlib.resources can find it. # This is otherwise considered an internal method. def get_resource_reader(self, fullname): try: package = self._get_package(fullname) except ImportError: return None if package.__loader__ is not self: return None return _PackageResourceReader(self, fullname) def _install_on_parent(self, parent: str, name: str, module: types.ModuleType): if not parent: return # Set the module as an attribute on its parent. parent_module = self.modules[parent] if parent_module.__loader__ is self: setattr(parent_module, name.rpartition(".")[2], module) # note: copied from cpython's import code, with call to create module replaced with _make_module def _do_find_and_load(self, name): parent = name.rpartition(".")[0] module_name_no_parent = name.rpartition(".")[-1] if parent: if parent not in self.modules: self._gcd_import(parent) # Crazy side-effects! if name in self.modules: return self.modules[name] parent_module = self.modules[parent] try: parent_module.__path__ # type: ignore[attr-defined] except AttributeError: # when we attempt to import a package only containing pybinded files, # the parent directory isn't always a package as defined by python, # so we search if the package is actually there or not before calling the error. if isinstance( parent_module.__loader__, importlib.machinery.ExtensionFileLoader, ): if name not in self.extern_modules: msg = ( _ERR_MSG + "; {!r} is a c extension module which was not externed. C extension modules \ need to be externed by the PackageExporter in order to be used as we do not support interning them.}." ).format(name, name) raise ModuleNotFoundError(msg, name=name) from None if not isinstance( parent_module.__dict__.get(module_name_no_parent), types.ModuleType, ): msg = ( _ERR_MSG + "; {!r} is a c extension package which does not contain {!r}." ).format(name, parent, name) raise ModuleNotFoundError(msg, name=name) from None else: msg = (_ERR_MSG + "; {!r} is not a package").format(name, parent) raise ModuleNotFoundError(msg, name=name) from None module = self._load_module(name, parent) self._install_on_parent(parent, name, module) return module # note: copied from cpython's import code def _find_and_load(self, name): module = self.modules.get(name, _NEEDS_LOADING) if module is _NEEDS_LOADING: return self._do_find_and_load(name) if module is None: message = f"import of {name} halted; None in sys.modules" raise ModuleNotFoundError(message, name=name) # To handle https://github.com/pytorch/pytorch/issues/57490, where std's # creation of fake submodules via the hacking of sys.modules is not import # friendly if name == "os": self.modules["os.path"] = cast(Any, module).path elif name == "typing": if sys.version_info < (3, 13): self.modules["typing.io"] = cast(Any, module).io self.modules["typing.re"] = cast(Any, module).re return module def _gcd_import(self, name, package=None, level=0): """Import and return the module based on its name, the package the call is being made from, and the level adjustment. This function represents the greatest common denominator of functionality between import_module and __import__. This includes setting __package__ if the loader did not. """ _sanity_check(name, package, level) if level > 0: name = _resolve_name(name, package, level) return self._find_and_load(name) # note: copied from cpython's import code def _handle_fromlist(self, module, fromlist, *, recursive=False): """Figure out what __import__ should return. The import_ parameter is a callable which takes the name of module to import. It is required to decouple the function from assuming importlib's import implementation is desired. """ module_name = demangle(module.__name__) # The hell that is fromlist ... # If a package was imported, try to import stuff from fromlist. if hasattr(module, "__path__"): for x in fromlist: if not isinstance(x, str): if recursive: where = module_name + ".__all__" else: where = "``from list''" raise TypeError( f"Item in {where} must be str, not {type(x).__name__}" ) elif x == "*": if not recursive and hasattr(module, "__all__"): self._handle_fromlist(module, module.__all__, recursive=True) elif not hasattr(module, x): from_name = f"{module_name}.{x}" try: self._gcd_import(from_name) except ModuleNotFoundError as exc: # Backwards-compatibility dictates we ignore failed # imports triggered by fromlist for modules that don't # exist. if ( exc.name == from_name and self.modules.get(from_name, _NEEDS_LOADING) is not None ): continue raise return module def __import__(self, name, globals=None, locals=None, fromlist=(), level=0): if level == 0: module = self._gcd_import(name) else: globals_ = globals if globals is not None else {} package = _calc___package__(globals_) module = self._gcd_import(name, package, level) if not fromlist: # Return up to the first dot in 'name'. This is complicated by the fact # that 'name' may be relative. if level == 0: return self._gcd_import(name.partition(".")[0]) elif not name: return module else: # Figure out where to slice the module's name up to the first dot # in 'name'. cut_off = len(name) - len(name.partition(".")[0]) # Slice end needs to be positive to alleviate need to special-case # when ``'.' not in name``. module_name = demangle(module.__name__) return self.modules[module_name[: len(module_name) - cut_off]] else: return self._handle_fromlist(module, fromlist) def _get_package(self, package): """Take a package name or module object and return the module. If a name, the module is imported. If the passed or imported module object is not a package, raise an exception. """ if hasattr(package, "__spec__"): if package.__spec__.submodule_search_locations is None: raise TypeError(f"{package.__spec__.name!r} is not a package") else: return package else: module = self.import_module(package) if module.__spec__.submodule_search_locations is None: raise TypeError(f"{package!r} is not a package") else: return module def _zipfile_path(self, package, resource=None): package = self._get_package(package) assert package.__loader__ is self name = demangle(package.__name__) if resource is not None: resource = _normalize_path(resource) return f"{name.replace('.', '/')}/{resource}" else: return f"{name.replace('.', '/')}" def _get_or_create_package( self, atoms: list[str] ) -> "Union[_PackageNode, _ExternNode]": cur = self.root for i, atom in enumerate(atoms): node = cur.children.get(atom, None) if node is None: node = cur.children[atom] = _PackageNode(None) if isinstance(node, _ExternNode): return node if isinstance(node, _ModuleNode): name = ".".join(atoms[:i]) raise ImportError( f"inconsistent module structure. module {name} is not a package, but has submodules" ) assert isinstance(node, _PackageNode) cur = node return cur def _add_file(self, filename: str): """Assembles a Python module out of the given file. Will ignore files in the .data directory. Args: filename (str): the name of the file inside of the package archive to be added """ *prefix, last = filename.split("/") if len(prefix) > 1 and prefix[0] == ".data": return package = self._get_or_create_package(prefix) if isinstance(package, _ExternNode): raise ImportError( f"inconsistent module structure. package contains a module file {filename}" f" that is a subpackage of a module marked external." ) if last == "__init__.py": package.source_file = filename elif last.endswith(".py"): package_name = last[: -len(".py")] package.children[package_name] = _ModuleNode(filename) def _add_extern(self, extern_name: str): *prefix, last = extern_name.split(".") package = self._get_or_create_package(prefix) if isinstance(package, _ExternNode): return # the shorter extern covers this extern case package.children[last] = _ExternNode() _NEEDS_LOADING = object() _ERR_MSG_PREFIX = "No module named " _ERR_MSG = _ERR_MSG_PREFIX + "{!r}"
PackageImporter
python
ansible__ansible
test/units/module_utils/basic/test_log.py
{ "start": 302, "end": 1140 }
class ____: DATA = [u'Text string', u'Toshio くらとみ non-ascii test'] DATA = DATA + [d.encode('utf-8') for d in DATA] DATA += [b'non-utf8 :\xff: test'] @pytest.mark.parametrize('msg, stdin', ((m, {}) for m in DATA), indirect=['stdin']) def test_smoketest_syslog(self, am, mocker, msg): # These talk to the live daemons on the system. Need to do this to # show that what we send doesn't cause an issue once it gets to the # daemon. These are just smoketests to test that we don't fail. mocker.patch('ansible.module_utils.basic.has_journal', False) am.log(u'Text string') am.log(u'Toshio くらとみ non-ascii test') am.log(b'Byte string') am.log(u'Toshio くらとみ non-ascii test'.encode('utf-8')) am.log(b'non-utf8 :\xff: test')
TestAnsibleModuleLogSmokeTest
python
python-openxml__python-docx
tests/oxml/test_ns.py
{ "start": 99, "end": 1634 }
class ____: def it_behaves_like_a_string_when_you_want_it_to(self, nsptag): s = "- %s -" % nsptag assert s == "- a:foobar -" def it_knows_its_clark_name(self, nsptag, clark_name): assert nsptag.clark_name == clark_name def it_can_construct_from_a_clark_name(self, clark_name, nsptag): _nsptag = NamespacePrefixedTag.from_clark_name(clark_name) assert _nsptag == nsptag def it_knows_its_local_part(self, nsptag, local_part): assert nsptag.local_part == local_part def it_can_compose_a_single_entry_nsmap_for_itself(self, nsptag, namespace_uri_a): expected_nsmap = {"a": namespace_uri_a} assert nsptag.nsmap == expected_nsmap def it_knows_its_namespace_prefix(self, nsptag): assert nsptag.nspfx == "a" def it_knows_its_namespace_uri(self, nsptag, namespace_uri_a): assert nsptag.nsuri == namespace_uri_a # fixtures ------------------------------------------------------- @pytest.fixture def clark_name(self, namespace_uri_a, local_part): return "{%s}%s" % (namespace_uri_a, local_part) @pytest.fixture def local_part(self): return "foobar" @pytest.fixture def namespace_uri_a(self): return "http://schemas.openxmlformats.org/drawingml/2006/main" @pytest.fixture def nsptag(self, nsptag_str): return NamespacePrefixedTag(nsptag_str) @pytest.fixture def nsptag_str(self, local_part): return "a:%s" % local_part
DescribeNamespacePrefixedTag
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/util.py
{ "start": 32510, "end": 38818 }
class ____(visitors.ReplacingExternalTraversal): """Clones and modifies clauses based on column correspondence. E.g.:: table1 = Table( "sometable", metadata, Column("col1", Integer), Column("col2", Integer), ) table2 = Table( "someothertable", metadata, Column("col1", Integer), Column("col2", Integer), ) condition = table1.c.col1 == table2.c.col1 make an alias of table1:: s = table1.alias("foo") calling ``ClauseAdapter(s).traverse(condition)`` converts condition to read:: s.c.col1 == table2.c.col1 """ __slots__ = ( "__traverse_options__", "selectable", "include_fn", "exclude_fn", "equivalents", "adapt_on_names", "adapt_from_selectables", ) def __init__( self, selectable: Selectable, equivalents: Optional[_EquivalentColumnMap] = None, include_fn: Optional[Callable[[ClauseElement], bool]] = None, exclude_fn: Optional[Callable[[ClauseElement], bool]] = None, adapt_on_names: bool = False, anonymize_labels: bool = False, adapt_from_selectables: Optional[AbstractSet[FromClause]] = None, ): self.__traverse_options__ = { "stop_on": [selectable], "anonymize_labels": anonymize_labels, } self.selectable = selectable self.include_fn = include_fn self.exclude_fn = exclude_fn self.equivalents = util.column_dict(equivalents or {}) self.adapt_on_names = adapt_on_names self.adapt_from_selectables = adapt_from_selectables if TYPE_CHECKING: @overload def traverse(self, obj: Literal[None]) -> None: ... # note this specializes the ReplacingExternalTraversal.traverse() # method to state # that we will return the same kind of ExternalTraversal object as # we were given. This is probably not 100% true, such as it's # possible for us to swap out Alias for Table at the top level. # Ideally there could be overloads specific to ColumnElement and # FromClause but Mypy is not accepting those as compatible with # the base ReplacingExternalTraversal @overload def traverse(self, obj: _ET) -> _ET: ... def traverse( self, obj: Optional[ExternallyTraversible] ) -> Optional[ExternallyTraversible]: ... def _corresponding_column( self, col, require_embedded, _seen=util.EMPTY_SET ): newcol = self.selectable.corresponding_column( col, require_embedded=require_embedded ) if newcol is None and col in self.equivalents and col not in _seen: for equiv in self.equivalents[col]: newcol = self._corresponding_column( equiv, require_embedded=require_embedded, _seen=_seen.union([col]), ) if newcol is not None: return newcol if ( self.adapt_on_names and newcol is None and isinstance(col, NamedColumn) ): newcol = self.selectable.exported_columns.get(col.name) return newcol @util.preload_module("sqlalchemy.sql.functions") def replace( self, col: _ET, _include_singleton_constants: bool = False ) -> Optional[_ET]: functions = util.preloaded.sql_functions # TODO: cython candidate if self.include_fn and not self.include_fn(col): # type: ignore return None elif self.exclude_fn and self.exclude_fn(col): # type: ignore return None if isinstance(col, FromClause) and not isinstance( col, functions.FunctionElement ): if self.selectable.is_derived_from(col): if self.adapt_from_selectables: for adp in self.adapt_from_selectables: if adp.is_derived_from(col): break else: return None return self.selectable # type: ignore elif isinstance(col, Alias) and isinstance( col.element, TableClause ): # we are a SELECT statement and not derived from an alias of a # table (which nonetheless may be a table our SELECT derives # from), so return the alias to prevent further traversal # or # we are an alias of a table and we are not derived from an # alias of a table (which nonetheless may be the same table # as ours) so, same thing return col else: # other cases where we are a selectable and the element # is another join or selectable that contains a table which our # selectable derives from, that we want to process return None elif not isinstance(col, ColumnElement): return None elif not _include_singleton_constants and col._is_singleton_constant: # dont swap out NULL, TRUE, FALSE for a label name # in a SQL statement that's being rewritten, # leave them as the constant. This is first noted in #6259, # however the logic to check this moved here as of #7154 so that # it is made specific to SQL rewriting and not all column # correspondence return None if "adapt_column" in col._annotations: col = col._annotations["adapt_column"] if TYPE_CHECKING: assert isinstance(col, KeyedColumnElement) if self.adapt_from_selectables and col not in self.equivalents: for adp in self.adapt_from_selectables: if adp.c.corresponding_column(col, False) is not None: break else: return None if TYPE_CHECKING: assert isinstance(col, KeyedColumnElement) return self._corresponding_column( # type: ignore col, require_embedded=True )
ClauseAdapter
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/bigquery_to_bigquery.py
{ "start": 1334, "end": 10827 }
class ____(BaseOperator): """ Copies data from one BigQuery table to another. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:BigQueryToBigQueryOperator` .. seealso:: For more details about these parameters: https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.copy :param source_project_dataset_tables: One or more dotted ``(project:|project.)<dataset>.<table>`` BigQuery tables to use as the source data. If ``<project>`` is not included, project will be the project defined in the connection json. Use a list if there are multiple source tables. (templated) :param destination_project_dataset_table: The destination BigQuery table. Format is: ``(project:|project.)<dataset>.<table>`` (templated) :param write_disposition: The write disposition if the table already exists. :param create_disposition: The create disposition if the table doesn't exist. :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param labels: a dictionary containing labels for the job/query, passed to BigQuery :param encryption_configuration: [Optional] Custom encryption configuration (e.g., Cloud KMS keys). .. code-block:: python encryption_configuration = { "kmsKeyName": "projects/testp/locations/us/keyRings/test-kr/cryptoKeys/test-key", } :param location: The geographic location of the job. You must specify the location to run the job if the location to run a job is not in the US or the EU multi-regional location or the location is in a single region (for example, us-central1). For more details check: https://cloud.google.com/bigquery/docs/locations#specifying_your_location :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param project_id: Google Cloud Project where the job is running """ template_fields: Sequence[str] = ( "source_project_dataset_tables", "destination_project_dataset_table", "labels", "impersonation_chain", ) template_ext: Sequence[str] = (".sql",) ui_color = "#e6f0e4" operator_extra_links = (BigQueryTableLink(),) def __init__( self, *, source_project_dataset_tables: list[str] | str, destination_project_dataset_table: str, write_disposition: str = "WRITE_EMPTY", create_disposition: str = "CREATE_IF_NEEDED", gcp_conn_id: str = "google_cloud_default", project_id: str = PROVIDE_PROJECT_ID, labels: dict | None = None, encryption_configuration: dict | None = None, location: str | None = None, impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.source_project_dataset_tables = source_project_dataset_tables self.destination_project_dataset_table = destination_project_dataset_table self.write_disposition = write_disposition self.create_disposition = create_disposition self.gcp_conn_id = gcp_conn_id self.labels = labels self.encryption_configuration = encryption_configuration self.location = location self.impersonation_chain = impersonation_chain self.hook: BigQueryHook | None = None self._job_conf: dict = {} self.project_id = project_id def _prepare_job_configuration(self): self.source_project_dataset_tables = ( [self.source_project_dataset_tables] if not isinstance(self.source_project_dataset_tables, list) else self.source_project_dataset_tables ) source_project_dataset_tables_fixup = [] for source_project_dataset_table in self.source_project_dataset_tables: source_project, source_dataset, source_table = self.hook.split_tablename( table_input=source_project_dataset_table, default_project_id=self.project_id, var_name="source_project_dataset_table", ) source_project_dataset_tables_fixup.append( {"projectId": source_project, "datasetId": source_dataset, "tableId": source_table} ) destination_project, destination_dataset, destination_table = self.hook.split_tablename( table_input=self.destination_project_dataset_table, default_project_id=self.project_id, ) configuration = { "copy": { "createDisposition": self.create_disposition, "writeDisposition": self.write_disposition, "sourceTables": source_project_dataset_tables_fixup, "destinationTable": { "projectId": destination_project, "datasetId": destination_dataset, "tableId": destination_table, }, } } if self.labels: configuration["labels"] = self.labels if self.encryption_configuration: configuration["copy"]["destinationEncryptionConfiguration"] = self.encryption_configuration return configuration def execute(self, context: Context) -> None: self.log.info( "Executing copy of %s into: %s", self.source_project_dataset_tables, self.destination_project_dataset_table, ) self.hook = BigQueryHook( gcp_conn_id=self.gcp_conn_id, location=self.location, impersonation_chain=self.impersonation_chain, ) if not self.project_id: self.project_id = self.hook.project_id configuration = self._prepare_job_configuration() self._job_conf = self.hook.insert_job( configuration=configuration, project_id=self.project_id ).to_api_repr() dest_table_info = self._job_conf["configuration"]["copy"]["destinationTable"] BigQueryTableLink.persist( context=context, dataset_id=dest_table_info["datasetId"], project_id=dest_table_info["projectId"], table_id=dest_table_info["tableId"], ) def get_openlineage_facets_on_complete(self, task_instance): """Implement on_complete as we will include final BQ job id.""" from airflow.providers.common.compat.openlineage.facet import ( Dataset, ExternalQueryRunFacet, ) from airflow.providers.google.cloud.openlineage.utils import ( BIGQUERY_NAMESPACE, get_facets_from_bq_table, get_identity_column_lineage_facet, ) from airflow.providers.openlineage.extractors import OperatorLineage if not self.hook: self.hook = BigQueryHook( gcp_conn_id=self.gcp_conn_id, location=self.location, impersonation_chain=self.impersonation_chain, ) if not self._job_conf: self.log.debug("OpenLineage could not find BQ job configuration.") return OperatorLineage() bq_job_id = self._job_conf["jobReference"]["jobId"] source_tables_info = self._job_conf["configuration"]["copy"]["sourceTables"] dest_table_info = self._job_conf["configuration"]["copy"]["destinationTable"] run_facets = { "externalQuery": ExternalQueryRunFacet(externalQueryId=bq_job_id, source="bigquery"), } input_datasets = [] for in_table_info in source_tables_info: table_id = ".".join( (in_table_info["projectId"], in_table_info["datasetId"], in_table_info["tableId"]) ) table_object = self.hook.get_client().get_table(table_id) input_datasets.append( Dataset( namespace=BIGQUERY_NAMESPACE, name=table_id, facets=get_facets_from_bq_table(table_object) ) ) out_table_id = ".".join( (dest_table_info["projectId"], dest_table_info["datasetId"], dest_table_info["tableId"]) ) out_table_object = self.hook.get_client().get_table(out_table_id) output_dataset_facets = { **get_facets_from_bq_table(out_table_object), **get_identity_column_lineage_facet( dest_field_names=[field.name for field in out_table_object.schema], input_datasets=input_datasets, ), } output_dataset = Dataset( namespace=BIGQUERY_NAMESPACE, name=out_table_id, facets=output_dataset_facets, ) return OperatorLineage(inputs=input_datasets, outputs=[output_dataset], run_facets=run_facets)
BigQueryToBigQueryOperator
python
weaviate__weaviate-python-client
weaviate/collections/queries/fetch_objects/generate/sync.py
{ "start": 320, "end": 473 }
class ____( Generic[Properties, References], _FetchObjectsGenerateExecutor[ConnectionSync, Properties, References], ): pass
_FetchObjectsGenerate