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
sympy__sympy
sympy/solvers/ode/single.py
{ "start": 15106, "end": 19549 }
class ____(SinglePatternODESolver): r""" Solves 1st order exact ordinary differential equations. A 1st order differential equation is called exact if it is the total differential of a function. That is, the differential equation .. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0 is exact if there is some function `F(x, y)` such that `P(x, y) = \partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can be shown that a necessary and sufficient condition for a first order ODE to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`. Then, the solution will be as given below:: >>> from sympy import Function, Eq, Integral, symbols, pprint >>> x, y, t, x0, y0, C1= symbols('x,y,t,x0,y0,C1') >>> P, Q, F= map(Function, ['P', 'Q', 'F']) >>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) + ... Integral(Q(x0, t), (t, y0, y))), C1)) x y / / | | F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1 | | / / x0 y0 Where the first partials of `P` and `Q` exist and are continuous in a simply connected region. A note: SymPy currently has no way to represent inert substitution on an expression, so the hint ``1st_exact_Integral`` will return an integral with `dy`. This is supposed to represent the function that you are solving for. Examples ======== >>> from sympy import Function, dsolve, cos, sin >>> from sympy.abc import x >>> f = Function('f') >>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x), ... f(x), hint='1st_exact') Eq(x*cos(f(x)) + f(x)**3/3, C1) References ========== - https://en.wikipedia.org/wiki/Exact_differential_equation - M. Tenenbaum & H. Pollard, "Ordinary Differential Equations", Dover 1963, pp. 73 # indirect doctest """ hint = "1st_exact" has_integral = True order = [1] def _wilds(self, f, x, order): P = Wild('P', exclude=[f(x).diff(x)]) Q = Wild('Q', exclude=[f(x).diff(x)]) return P, Q def _equation(self, fx, x, order): P, Q = self.wilds() return P + Q*fx.diff(x) def _verify(self, fx) -> bool: P, Q = self.wilds() x = self.ode_problem.sym y = Dummy('y') m, n = self.wilds_match() m = m.subs(fx, y) n = n.subs(fx, y) numerator = cancel(m.diff(y) - n.diff(x)) if numerator.is_zero: # Is exact return True else: # The following few conditions try to convert a non-exact # differential equation into an exact one. # References: # 1. Differential equations with applications # and historical notes - George E. Simmons # 2. https://math.okstate.edu/people/binegar/2233-S99/2233-l12.pdf factor_n = cancel(numerator/n) factor_m = cancel(-numerator/m) if y not in factor_n.free_symbols: # If (dP/dy - dQ/dx) / Q = f(x) # then exp(integral(f(x))*equation becomes exact factor = factor_n integration_variable = x elif x not in factor_m.free_symbols: # If (dP/dy - dQ/dx) / -P = f(y) # then exp(integral(f(y))*equation becomes exact factor = factor_m integration_variable = y else: # Couldn't convert to exact return False factor = exp(Integral(factor, integration_variable)) m *= factor n *= factor self._wilds_match[P] = m.subs(y, fx) self._wilds_match[Q] = n.subs(y, fx) return True def _get_general_solution(self, *, simplify_flag: bool = True): m, n = self.wilds_match() fx = self.ode_problem.func x = self.ode_problem.sym (C1,) = self.ode_problem.get_numbered_constants(num=1) y = Dummy('y') m = m.subs(fx, y) n = n.subs(fx, y) gen_sol = Eq(Subs(Integral(m, x) + Integral(n - Integral(m, x).diff(y), y), y, fx), C1) return [gen_sol]
FirstExact
python
astropy__astropy
astropy/io/ascii/fixedwidth.py
{ "start": 381, "end": 1926 }
class ____(core.BaseSplitter): """ Split line based on fixed start and end positions for each ``col`` in ``self.cols``. This class requires that the Header class will have defined ``col.start`` and ``col.end`` for each column. The reference to the ``header.cols`` gets put in the splitter object by the base Reader.read() function just in time for splitting data lines by a ``data`` object. Note that the ``start`` and ``end`` positions are defined in the pythonic style so line[start:end] is the desired substring for a column. This splitter class does not have a hook for ``process_lines`` since that is generally not useful for fixed-width input. """ delimiter_pad = "" bookend = False delimiter = "|" def __call__(self, lines): for line in lines: vals = [line[x.start : x.end] for x in self.cols] if self.process_val: yield [self.process_val(x) for x in vals] else: yield vals def join(self, vals, widths): pad = self.delimiter_pad or "" delimiter = self.delimiter or "" padded_delim = pad + delimiter + pad if self.bookend: bookend_left = delimiter + pad bookend_right = pad + delimiter else: bookend_left = "" bookend_right = "" vals = [" " * (width - len(val)) + val for val, width in zip(vals, widths)] return bookend_left + padded_delim.join(vals) + bookend_right
FixedWidthSplitter
python
huggingface__transformers
tests/models/got_ocr2/test_image_processing_got_ocr2.py
{ "start": 3030, "end": 8687 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = GotOcr2ImageProcessor if is_vision_available() else None fast_image_processing_class = GotOcr2ImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = GotOcr2ImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processor, "do_resize")) self.assertTrue(hasattr(image_processor, "size")) self.assertTrue(hasattr(image_processor, "do_normalize")) self.assertTrue(hasattr(image_processor, "image_mean")) self.assertTrue(hasattr(image_processor, "image_std")) self.assertTrue(hasattr(image_processor, "do_convert_rgb")) def test_slow_fast_equivalence_crop_to_patches(self): dummy_image = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)[0] image_processor_slow = self.image_processing_class(**self.image_processor_dict, crop_to_patches=True) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict, crop_to_patches=True) encoding_slow = image_processor_slow(dummy_image, return_tensors="pt") encoding_fast = image_processor_fast(dummy_image, return_tensors="pt") torch.testing.assert_close(encoding_slow.num_patches, encoding_fast.num_patches) self._assert_slow_fast_tensors_equivalence(encoding_slow.pixel_values, encoding_fast.pixel_values) def test_slow_fast_equivalence_batched_crop_to_patches(self): # Prepare image inputs so that we have two groups of images with equal resolution with a group of images with # different resolutions in between dummy_images = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True) dummy_images += self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) dummy_images += self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True) image_processor_slow = self.image_processing_class(**self.image_processor_dict, crop_to_patches=True) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict, crop_to_patches=True) encoding_slow = image_processor_slow(dummy_images, return_tensors="pt") encoding_fast = image_processor_fast(dummy_images, return_tensors="pt") torch.testing.assert_close(encoding_slow.num_patches, encoding_fast.num_patches) self._assert_slow_fast_tensors_equivalence(encoding_slow.pixel_values, encoding_fast.pixel_values) def test_crop_to_patches(self): # test slow image processor image_processor = self.image_processor_list[0](**self.image_processor_dict) image = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True)[0] processed_images = image_processor.crop_image_to_patches( image, min_patches=1, max_patches=6, use_thumbnail=True, patch_size={"height": 20, "width": 20}, ) self.assertEqual(len(processed_images), 5) self.assertEqual(processed_images[0].shape[:2], (20, 20)) # test fast image processor (process batch) image_processor = self.image_processor_list[1](**self.image_processor_dict) image = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)[0] processed_images = image_processor.crop_image_to_patches( image.unsqueeze(0), min_patches=1, max_patches=6, use_thumbnail=True, patch_size=SizeDict(height=20, width=20), ) self.assertEqual(len(processed_images[0]), 5) self.assertEqual(processed_images.shape[-2:], (20, 20)) def test_get_num_patches_without_images(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) num_patches = image_processing.get_number_of_image_patches(height=100, width=100, images_kwargs={}) self.assertEqual(num_patches, 1) num_patches = image_processing.get_number_of_image_patches( height=300, width=500, images_kwargs={"crop_to_patches": False} ) self.assertEqual(num_patches, 1) num_patches = image_processing.get_number_of_image_patches( height=20, width=20, images_kwargs={"crop_to_patches": True} ) self.assertEqual(num_patches, 1) num_patches = image_processing.get_number_of_image_patches( height=60, width=60, images_kwargs={"crop_to_patches": True} ) self.assertEqual(num_patches, 10) num_patches = image_processing.get_number_of_image_patches( height=100, width=100, images_kwargs={"crop_to_patches": True} ) self.assertEqual(num_patches, 10) num_patches = image_processing.get_number_of_image_patches( height=100, width=100, images_kwargs={"crop_to_patches": True, "max_patches": 200} ) self.assertEqual(num_patches, 50)
GotOcr2ProcessingTest
python
google__jax
jax/_src/pallas/mosaic/core.py
{ "start": 7782, "end": 7926 }
class ____(jax_core.AbstractValue): sem_type: SemaphoreType @dataclasses.dataclass(init=False, kw_only=True, unsafe_hash=True)
AbstractSemaphore
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/xcom_arg.py
{ "start": 14374, "end": 14700 }
class ____(Sequence): value: Sequence | dict callables: MapCallables def __getitem__(self, index: Any) -> Any: value = self.value[index] for f in self.callables: value = f(value) return value def __len__(self) -> int: return len(self.value) @attrs.define
_MapResult
python
ZoranPandovski__al-go-rithms
backtracking/Hamiltonian Cycle/python/Hamiltonian.py
{ "start": 102, "end": 2021 }
class ____(): def __init__(self, vertices): self.graph = [[0 for column in range(vertices)] for row in range(vertices)] self.V = vertices ''' Check if this vertex is an adjacent vertex of the previously added vertex and is not included in the path earlier ''' def isSafe(self, v, pos, path): # Check if current vertex and last vertex # in path are adjacent if self.graph[ path[pos-1] ][v] == 0: return False # Check if current vertex not already in path for vertex in path: if vertex == v: return False return True # A recursive utility function to solve # hamiltonian cycle problem def hamCycleUtil(self, path, pos): # base case: if all vertices are # included in the path if pos == self.V: # Last vertex must be adjacent to the # first vertex in path to make a cyle if self.graph[ path[pos-1] ][ path[0] ] == 1: return True else: return False # Try different vertices as a next candidate # in Hamiltonian Cycle. We don't try for 0 as # we included 0 as starting point in hamCycle() for v in range(1,self.V): if self.isSafe(v, pos, path) == True: path[pos] = v if self.hamCycleUtil(path, pos+1) == True: return True # Remove current vertex if it doesn't # lead to a solution path[pos] = -1 return False def hamCycle(self): path = [-1] * self.V ''' Let us put vertex 0 as the first vertex in the path. If there is a Hamiltonian Cycle, then the path can be started from any point of the cycle as the graph is undirected ''' path[0] = 0 if self.hamCycleUtil(path,1) == False: print("Solution does not exist\n") return False self.printSolution(path) return True def printSolution(self, path): print("Solution Exists: Following is one Hamiltonian Cycle") for vertex in path: print(vertex, end=' ') print(path[0], "\n")
Graph
python
django__django
tests/template_tests/utils.py
{ "start": 2473, "end": 3337 }
class ____: def __init__(self): self.otherclass = OtherClass() def method(self): return "SomeClass.method" def method2(self, o): return o def method3(self): raise SomeException def method4(self): raise SomeOtherException def method5(self): raise TypeError def __getitem__(self, key): if key == "silent_fail_key": raise SomeException elif key == "noisy_fail_key": raise SomeOtherException raise KeyError @property def silent_fail_attribute(self): raise SomeException @property def noisy_fail_attribute(self): raise SomeOtherException @property def attribute_error_attribute(self): raise AttributeError @property def type_error_attribute(self): raise TypeError
SomeClass
python
doocs__leetcode
solution/2300-2399/2344.Minimum Deletions to Make Array Divisible/Solution.py
{ "start": 0, "end": 304 }
class ____: def minOperations(self, nums: List[int], numsDivide: List[int]) -> int: x = numsDivide[0] for v in numsDivide[1:]: x = gcd(x, v) nums.sort() for i, v in enumerate(nums): if x % v == 0: return i return -1
Solution
python
openai__openai-python
src/openai/types/responses/response_text_config.py
{ "start": 289, "end": 1352 }
class ____(BaseModel): format: Optional[ResponseFormatTextConfig] = None """An object specifying the format that the model must output. Configuring `{ "type": "json_schema" }` enables Structured Outputs, which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). The default format is `{ "type": "text" }` with no additional options. **Not recommended for gpt-4o and newer models:** Setting to `{ "type": "json_object" }` enables the older JSON mode, which ensures the message the model generates is valid JSON. Using `json_schema` is preferred for models that support it. """ verbosity: Optional[Literal["low", "medium", "high"]] = None """Constrains the verbosity of the model's response. Lower values will result in more concise responses, while higher values will result in more verbose responses. Currently supported values are `low`, `medium`, and `high`. """
ResponseTextConfig
python
dagster-io__dagster
python_modules/dagster/dagster_tests/launcher_tests/pending_repository.py
{ "start": 246, "end": 2757 }
class ____(CacheableAssetsDefinition): def compute_cacheable_data(self): # used for tracking how many times we've executed this function instance = DagsterInstance.get() kvs_key = f"compute_cacheable_data_called_{self.unique_id}" compute_cacheable_data_called = int( instance.run_storage.get_cursor_values({kvs_key}).get(kvs_key, "0") ) instance.run_storage.set_cursor_values({kvs_key: str(compute_cacheable_data_called + 1)}) return [ AssetsDefinitionCacheableData( keys_by_input_name={"inp": dg.AssetKey(f"upstream_{self.unique_id}")}, keys_by_output_name={"result": dg.AssetKey(f"foo_{self.unique_id}")}, internal_asset_deps={"result": {dg.AssetKey(f"upstream_{self.unique_id}")}}, group_name="some_group", metadata_by_output_name={ "result": { "a": 1, "b": "foo", "c": 1.75, "d": MetadataValue.md("### something \n```\na\n```"), "e": {"foo": "bar", "baz": 1}, }, }, can_subset=False, extra_metadata={"foo": None, "bar": {"hi": 1.75, "x": ["y", {"z": "w"}, 2]}}, ) ] def build_definitions(self, data): # used for tracking how many times we've executed this function instance = DagsterInstance.get() kvs_key = f"get_definitions_called_{self.unique_id}" get_definitions_called = int( instance.run_storage.get_cursor_values({kvs_key}).get(kvs_key, "0") ) instance.run_storage.set_cursor_values({kvs_key: str(get_definitions_called + 1)}) @dg.op(name=f"my_op_{self.unique_id}", ins={"inp": dg.In(dg.Nothing)}) def my_op(): return 1 return [ AssetsDefinition.from_op( my_op, keys_by_input_name=cd.keys_by_input_name, keys_by_output_name=cd.keys_by_output_name, key_prefix=cd.key_prefix, group_name=cd.group_name, metadata_by_output_name=cd.metadata_by_output_name, ) for cd in (data or []) ] @dg.asset def c(foo_a, foo_b): return foo_a + foo_b + 1 @dg.repository def pending(): return [MyAssets("a"), MyAssets("b"), c, dg.define_asset_job("my_cool_asset_job")]
MyAssets
python
readthedocs__readthedocs.org
readthedocs/invitations/models.py
{ "start": 698, "end": 2627 }
class ____(models.QuerySet): """Invitation queryset.""" def expired(self, obj=None): queryset = self.filter(expiration_date__lte=timezone.now()) if obj: queryset = self._for_object(obj=obj, queryset=queryset) return queryset def pending(self, obj=None): queryset = self.filter(expiration_date__gt=timezone.now()) if obj: queryset = self._for_object(obj=obj, queryset=queryset) return queryset def invite(self, from_user, obj, to_user=None, to_email=None, request=None): """ Create and send an invitation for `to_user` or `to_email` to join `object`. If the invitation already exists, we don't send the invitation again. :param request: If given, a log entry will be created. """ if not to_user and not to_email: raise ValueError("A user or email must be provided") fields = { "content_type": ContentType.objects.get_for_model(obj), "object_id": obj.pk, } if to_user: fields["to_user"] = to_user else: fields["to_email"] = to_email invitation, created = self.get_or_create( **fields, defaults={ "from_user": from_user, }, ) if created: if request: invitation.create_audit_log( action=AuditLog.INVITATION_SENT, request=request, user=request.user, ) invitation.send() return invitation, created def for_object(self, obj): return self._for_object(obj=obj, queryset=self.all()) @staticmethod def _for_object(obj, queryset): return queryset.filter( object_id=obj.pk, content_type=ContentType.objects.get_for_model(obj), )
InvitationQueryset
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py
{ "start": 56659, "end": 58800 }
class ____(nn.Module): def __init__(self, config: Sam3TrackerVideoMaskDecoderConfig): super().__init__() self.config = config self.num_hidden_layers = config.num_hidden_layers self.layers = nn.ModuleList() for i in range(self.num_hidden_layers): self.layers.append(Sam3TrackerVideoTwoWayAttentionBlock(config, skip_first_layer_pe=(i == 0))) self.final_attn_token_to_image = Sam3TrackerVideoAttention(config) self.layer_norm_final_attn = nn.LayerNorm(config.hidden_size) def forward( self, point_embeddings: Tensor, image_embeddings: Tensor, image_positional_embeddings: Tensor, attention_similarity: Tensor, target_embedding=None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, BaseModelOutput]: if image_embeddings is None: raise ValueError("You have to specify an image_embedding") image_embeddings = image_embeddings.flatten(2).permute(0, 2, 1).unsqueeze(1) image_positional_embeddings = image_positional_embeddings.flatten(2).permute(0, 2, 1).unsqueeze(1) # Prepare queries queries = point_embeddings keys = image_embeddings # Apply transformer blocks and final layernorm for layer in self.layers: if target_embedding is not None: queries += target_embedding queries, keys, _ = layer( queries=queries, keys=keys, query_point_embedding=point_embeddings, key_point_embedding=image_positional_embeddings, attention_similarity=attention_similarity, **kwargs, ) # Apply the final attention layer from the points to the image query = queries + point_embeddings key = keys + image_positional_embeddings attn_out, _ = self.final_attn_token_to_image(query=query, key=key, value=keys) queries = queries + attn_out queries = self.layer_norm_final_attn(queries) return queries, keys
Sam3TrackerVideoTwoWayTransformer
python
sqlalchemy__sqlalchemy
test/sql/test_insert_exec.py
{ "start": 15264, "end": 23902 }
class ____(fixtures.TablesTest): """test for consistent insert behavior across dialects regarding the inline() method, values() method, lower-case 't' tables. """ run_create_tables = "each" __sparse_driver_backend__ = True @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, normalize_sequence(config, Sequence("t_id_seq")), primary_key=True, ), Column("data", String(50)), Column("x", Integer), ) Table( "foo_no_seq", metadata, # note this will have full AUTO INCREMENT on MariaDB # whereas "foo" will not due to sequence support Column( "id", Integer, primary_key=True, ), Column("data", String(50)), Column("x", Integer), ) def _fixture(self, types=True): if types: t = sql.table( "foo", sql.column("id", Integer), sql.column("data", String), sql.column("x", Integer), ) else: t = sql.table( "foo", sql.column("id"), sql.column("data"), sql.column("x") ) return t def _test( self, connection, stmt, row, returning=None, inserted_primary_key=False, table=None, parameters=None, ): if parameters is not None: r = connection.execute(stmt, parameters) else: r = connection.execute(stmt) if returning: returned = r.first() eq_(returned, returning) elif inserted_primary_key is not False: eq_(r.inserted_primary_key, inserted_primary_key) if table is None: table = self.tables.foo eq_(connection.execute(table.select()).first(), row) def _test_multi(self, connection, stmt, rows, data): connection.execute(stmt, rows) eq_( connection.execute( self.tables.foo.select().order_by(self.tables.foo.c.id) ).all(), data, ) @testing.requires.sequences def test_explicit_sequence(self, connection): t = self._fixture() self._test( connection, t.insert().values( id=func.next_value( normalize_sequence(config, Sequence("t_id_seq")) ), data="data", x=5, ), (testing.db.dialect.default_sequence_base, "data", 5), ) def test_uppercase(self, connection): t = self.tables.foo self._test( connection, t.insert().values(id=1, data="data", x=5), (1, "data", 5), inserted_primary_key=(1,), ) def test_uppercase_inline(self, connection): t = self.tables.foo self._test( connection, t.insert().inline().values(id=1, data="data", x=5), (1, "data", 5), inserted_primary_key=(1,), ) @testing.crashes( "mssql+pyodbc", "Pyodbc + SQL Server + Py3K, some decimal handling issue", ) def test_uppercase_inline_implicit(self, connection): t = self.tables.foo self._test( connection, t.insert().inline().values(data="data", x=5), (1, "data", 5), inserted_primary_key=(None,), ) def test_uppercase_implicit(self, connection): t = self.tables.foo self._test( connection, t.insert().values(data="data", x=5), (testing.db.dialect.default_sequence_base, "data", 5), inserted_primary_key=(testing.db.dialect.default_sequence_base,), ) def test_uppercase_direct_params(self, connection): t = self.tables.foo self._test( connection, t.insert().values(id=1, data="data", x=5), (1, "data", 5), inserted_primary_key=(1,), ) @testing.requires.insert_returning def test_uppercase_direct_params_returning(self, connection): t = self.tables.foo self._test( connection, t.insert().values(id=1, data="data", x=5).returning(t.c.id, t.c.x), (1, "data", 5), returning=(1, 5), ) @testing.requires.sql_expressions_inserted_as_primary_key def test_sql_expr_lastrowid(self, connection): # see also test.orm.test_unitofwork.py # ClauseAttributesTest.test_insert_pk_expression t = self.tables.foo_no_seq self._test( connection, t.insert().values(id=literal(5) + 10, data="data", x=5), (15, "data", 5), inserted_primary_key=(15,), table=self.tables.foo_no_seq, ) def test_direct_params(self, connection): t = self._fixture() self._test( connection, t.insert().values(id=1, data="data", x=5), (1, "data", 5), inserted_primary_key=(), ) @testing.requires.insert_returning def test_direct_params_returning(self, connection): t = self._fixture() self._test( connection, t.insert().values(id=1, data="data", x=5).returning(t.c.id, t.c.x), (testing.db.dialect.default_sequence_base, "data", 5), returning=(testing.db.dialect.default_sequence_base, 5), ) # there's a non optional Sequence in the metadata, which if the dialect # supports sequences, it means the CREATE TABLE should *not* have # autoincrement, so the INSERT below would fail because the "t" fixture # does not indicate the Sequence @testing.fails_if(testing.requires.sequences) @testing.requires.emulated_lastrowid def test_implicit_pk(self, connection): t = self._fixture() self._test( connection, t.insert().values(data="data", x=5), (testing.db.dialect.default_sequence_base, "data", 5), inserted_primary_key=(), ) @testing.fails_if(testing.requires.sequences) @testing.requires.emulated_lastrowid def test_implicit_pk_multi_rows(self, connection): t = self._fixture() self._test_multi( connection, t.insert(), [ {"data": "d1", "x": 5}, {"data": "d2", "x": 6}, {"data": "d3", "x": 7}, ], [(1, "d1", 5), (2, "d2", 6), (3, "d3", 7)], ) @testing.fails_if(testing.requires.sequences) @testing.requires.emulated_lastrowid def test_implicit_pk_inline(self, connection): t = self._fixture() self._test( connection, t.insert().inline().values(data="data", x=5), (testing.db.dialect.default_sequence_base, "data", 5), inserted_primary_key=(), ) @testing.requires.database_discards_null_for_autoincrement def test_explicit_null_pk_values_db_ignores_it(self, connection): """test new use case in #7998""" # NOTE: this use case uses cursor.lastrowid on SQLite, MySQL, MariaDB, # however when SQLAlchemy 2.0 adds support for RETURNING to SQLite # and MariaDB, it should work there as well. t = self.tables.foo_no_seq self._test( connection, t.insert().values(id=None, data="data", x=5), (testing.db.dialect.default_sequence_base, "data", 5), inserted_primary_key=(testing.db.dialect.default_sequence_base,), table=t, ) @testing.requires.database_discards_null_for_autoincrement def test_explicit_null_pk_params_db_ignores_it(self, connection): """test new use case in #7998""" # NOTE: this use case uses cursor.lastrowid on SQLite, MySQL, MariaDB, # however when SQLAlchemy 2.0 adds support for RETURNING to SQLite # and MariaDB, it should work there as well. t = self.tables.foo_no_seq self._test( connection, t.insert(), (testing.db.dialect.default_sequence_base, "data", 5), inserted_primary_key=(testing.db.dialect.default_sequence_base,), table=t, parameters=dict(id=None, data="data", x=5), )
TableInsertTest
python
wandb__wandb
wandb/vendor/pygments/lexers/rnc.py
{ "start": 400, "end": 1990 }
class ____(RegexLexer): """ For `RelaxNG-compact <http://relaxng.org>`_ syntax. .. versionadded:: 2.2 """ name = 'Relax-NG Compact' aliases = ['rnc', 'rng-compact'] filenames = ['*.rnc'] tokens = { 'root': [ (r'namespace\b', Keyword.Namespace), (r'(?:default|datatypes)\b', Keyword.Declaration), (r'##.*$', Comment.Preproc), (r'#.*$', Comment.Single), (r'"[^"]*"', String.Double), # TODO single quoted strings and escape sequences outside of # double-quoted strings (r'(?:element|attribute|mixed)\b', Keyword.Declaration, 'variable'), (r'(text\b|xsd:[^ ]+)', Keyword.Type, 'maybe_xsdattributes'), (r'[,?&*=|~]|>>', Operator), (r'[(){}]', Punctuation), (r'.', Text), ], # a variable has been declared using `element` or `attribute` 'variable': [ (r'[^{]+', Name.Variable), (r'\{', Punctuation, '#pop'), ], # after an xsd:<datatype> declaration there may be attributes 'maybe_xsdattributes': [ (r'\{', Punctuation, 'xsdattributes'), (r'\}', Punctuation, '#pop'), (r'.', Text), ], # attributes take the form { key1 = value1 key2 = value2 ... } 'xsdattributes': [ (r'[^ =}]', Name.Attribute), (r'=', Operator), (r'"[^"]*"', String.Double), (r'\}', Punctuation, '#pop'), (r'.', Text), ], }
RNCCompactLexer
python
tensorflow__tensorflow
tensorflow/python/ops/weak_tensor_special_math_ops_test.py
{ "start": 1419, "end": 3457 }
class ____(test.TestCase, parameterized.TestCase): @test_util.run_in_graph_and_eager_modes def test_dawsn_boundary(self): self.assertAllClose(0., special_math_ops.dawsn(0.)) self.assertTrue(np.isnan(self.evaluate(special_math_ops.dawsn(np.nan)))) @parameterized.parameters(np.float32, np.float64) def test_dawsn_odd(self, dtype): x = _get_weak_tensor( np.random.uniform(-100.0, 100.0, size=int(1e4)).astype(dtype) ) y = special_math_ops.dawsn(x) neg_y = -special_math_ops.dawsn(-x) self.assertIsInstance(y, WeakTensor) self.assertIsInstance(neg_y, WeakTensor) self.assertAllClose(self.evaluate(y), self.evaluate(neg_y)) @parameterized.parameters(np.float32, np.float64) def test_dawsn_small(self, dtype): x = np.random.uniform(-1., 1., size=int(1e4)).astype(dtype) x_wt = _get_weak_tensor(x) y_wt = special_math_ops.dawsn(x_wt) self.assertIsInstance(y_wt, WeakTensor) try: from scipy import special # pylint: disable=g-import-not-at-top self.assertAllClose(special.dawsn(x), self.evaluate(y_wt)) except ImportError as e: tf_logging.warn('Cannot test special functions: %s' % str(e)) @parameterized.parameters(np.float32, np.float64) def test_dawsn_larger(self, dtype): x = np.random.uniform(1., 100., size=int(1e4)).astype(dtype) x_wt = _get_weak_tensor(x) y_wt = special_math_ops.dawsn(x_wt) self.assertIsInstance(y_wt, WeakTensor) try: from scipy import special # pylint: disable=g-import-not-at-top self.assertAllClose(special.dawsn(x), y_wt) except ImportError as e: tf_logging.warn('Cannot test special functions: %s' % str(e)) def test_dawsn_gradient(self): inputs = [_get_weak_tensor(np.random.uniform(-50.0, 50.0, size=int(1e2)))] analytical, numerical = gradient_checker_v2.compute_gradient( special_math_ops.dawsn, inputs) self.assertLess(gradient_checker_v2.max_error(analytical, numerical), 1e-4) @test_util.run_all_in_graph_and_eager_modes
DawsnTest
python
tensorflow__tensorflow
tensorflow/python/ops/init_ops_v2_test.py
{ "start": 13716, "end": 16398 }
class ____(InitializersTest): @test_util.run_in_graph_and_eager_modes def testRangeInitializer(self): self._range_test( init_ops_v2.Orthogonal(seed=123), shape=(20, 20), target_mean=0.) @test_util.run_in_graph_and_eager_modes def testInitializerIdentical(self): self.skipTest("Doesn't work without the graphs") init1 = init_ops_v2.Orthogonal(seed=1) init2 = init_ops_v2.Orthogonal(seed=1) self._identical_test(init1, init2, True, (10, 10)) @test_util.run_in_graph_and_eager_modes def testInitializerDifferent(self): init1 = init_ops_v2.Orthogonal(seed=1) init2 = init_ops_v2.Orthogonal(seed=2) self._identical_test(init1, init2, False, (10, 10)) @test_util.run_in_graph_and_eager_modes def testDuplicatedInitializer(self): init = init_ops_v2.Orthogonal() self._duplicated_test(init, (10, 10)) @test_util.run_in_graph_and_eager_modes def testInvalidDataType(self): init = init_ops_v2.Orthogonal() self.assertRaises(ValueError, init, shape=(10, 10), dtype=dtypes.string) @test_util.run_in_graph_and_eager_modes def testInvalidShape(self): init = init_ops_v2.Orthogonal() with test_util.use_gpu(): self.assertRaises(ValueError, init, shape=[5]) @test_util.run_in_graph_and_eager_modes def testGain(self): self.skipTest("Doesn't work without the graphs") init1 = init_ops_v2.Orthogonal(seed=1) init2 = init_ops_v2.Orthogonal(gain=3.14, seed=1) with test_util.use_gpu(): t1 = self.evaluate(init1(shape=(10, 10))) t2 = self.evaluate(init2(shape=(10, 10))) self.assertAllClose(t1, t2 / 3.14) @test_util.run_in_graph_and_eager_modes def testShapesValues(self): for shape in [(10, 10), (10, 9, 8), (100, 5, 5), (50, 40), (40, 50)]: init = init_ops_v2.Orthogonal() tol = 1e-5 with test_util.use_gpu(): # Check the shape t = self.evaluate(init(shape)) self.assertAllEqual(shape, t.shape) # Check orthogonality by computing the inner product t = t.reshape((np.prod(t.shape[:-1]), t.shape[-1])) if t.shape[0] > t.shape[1]: self.assertAllClose( np.dot(t.T, t), np.eye(t.shape[1]), rtol=tol, atol=tol) else: self.assertAllClose( np.dot(t, t.T), np.eye(t.shape[0]), rtol=tol, atol=tol) @test_util.run_in_graph_and_eager_modes def testPartition(self): init = init_ops_v2.Orthogonal(seed=1) with self.assertRaisesWithLiteralMatch( ValueError, r"Orthogonal initializer doesn't support partition-related arguments"): init((4, 2), dtype=dtypes.float32, partition_shape=(2, 2))
OrthogonalInitializerTest
python
pydantic__pydantic
pydantic/fields.py
{ "start": 3287, "end": 3453 }
class ____(TypedDict, closed=True): # TODO PEP 747: use TypeForm: annotation: Any metadata: list[Any] attributes: dict[str, Any] @final
_FieldInfoAsDict
python
ray-project__ray
python/ray/experimental/channel/common.py
{ "start": 11659, "end": 15460 }
class ____(ReaderInterface): def __init__( self, input_channels: List[ChannelInterface], ): super().__init__(input_channels) def start(self): pass def _read_list(self, timeout: Optional[float] = None) -> List[Any]: self._consume_leftover_channels_if_needed(timeout) # We don't update `remaining_timeout` here because in the worst case, # consuming leftover channels requires reading all `_input_channels`, # which users expect to complete within the original `timeout`. Updating # `remaining_timeout` could cause unexpected timeouts in subsequent read # operations. # It is a special case that `timeout` is set to 0, which means # read once for each channel. is_zero_timeout = timeout == 0 results = [None for _ in range(len(self._input_channels))] if timeout is None or timeout == -1: timeout = float("inf") timeout_point = time.monotonic() + timeout remaining_timeout = timeout from ray.dag import DAGContext ctx = DAGContext.get_current() iteration_timeout = ctx.read_iteration_timeout # Iterate over the input channels with a shorter timeout for each iteration # to detect RayTaskError early and fail fast. done_channels = set() while len(done_channels) < len(self._input_channels): for i, c in enumerate(self._input_channels): if c in done_channels: continue try: result = c.read(min(remaining_timeout, iteration_timeout)) results[i] = result done_channels.add(c) if isinstance(result, ray.exceptions.RayTaskError): # If we raise an exception immediately, it will be considered # as a system error which will cause the execution loop to # exit. Hence, return immediately and let `_process_return_vals` # handle the exception. # # Return a list of RayTaskError so that the caller will not # get an undefined partial result. self._leftover_channels = [ c for c in self._input_channels if c not in done_channels ] return [result for _ in range(len(self._input_channels))] except ray.exceptions.RayChannelTimeoutError as e: remaining_timeout = max(timeout_point - time.monotonic(), 0) if remaining_timeout == 0: raise e continue remaining_timeout = max(timeout_point - time.monotonic(), 0) if remaining_timeout == 0 and not is_zero_timeout: raise ray.exceptions.RayChannelTimeoutError( f"Cannot read all channels within {timeout} seconds" ) return results def release_channel_buffers(self, timeout: Optional[float] = None) -> None: for c in self._input_channels: start_time = time.monotonic() assert hasattr( c, "release_buffer" ), "release_buffer() is only supported for shared memory channel " "(e.g., Channel, BufferedSharedMemoryChannel, CompositeChannel) " "and used between the last actor and the driver, but got a channel" f" of type {type(c)}." c.release_buffer(timeout) if timeout is not None: timeout -= time.monotonic() - start_time timeout = max(timeout, 0) @DeveloperAPI
SynchronousReader
python
kamyu104__LeetCode-Solutions
Python/print-in-order.py
{ "start": 48, "end": 1283 }
class ____(object): def __init__(self): self.__cv = threading.Condition() self.__has_first = False self.__has_second = False def first(self, printFirst): """ :type printFirst: method :rtype: void """ with self.__cv: # printFirst() outputs "first". Do not change or remove this line. printFirst() self.__has_first = True self.__cv.notifyAll() def second(self, printSecond): """ :type printSecond: method :rtype: void """ with self.__cv: while not self.__has_first: self.__cv.wait() # printSecond() outputs "second". Do not change or remove this line. printSecond() self.__has_second = True self.__cv.notifyAll() def third(self, printThird): """ :type printThird: method :rtype: void """ with self.__cv: while not self.__has_second: self.__cv.wait() # printThird() outputs "third". Do not change or remove this line. printThird() self.__cv.notifyAll()
Foo
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/pipeline_job.py
{ "start": 1875, "end": 11518 }
class ____(GoogleCloudBaseOperator): """ Create and run a Pipeline job. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :param display_name: Required. The user-defined name of this Pipeline. :param template_path: Required. The path of PipelineJob or PipelineSpec JSON or YAML file. It can be a local path, a Google Cloud Storage URI (e.g. "gs://project.name"), an Artifact Registry URI (e.g. "https://us-central1-kfp.pkg.dev/proj/repo/pack/latest"), or an HTTPS URI. :param job_id: Optional. The unique ID of the job run. If not specified, pipeline name + timestamp will be used. :param pipeline_root: Optional. The root of the pipeline outputs. If not set, the staging bucket set in aiplatform.init will be used. If that's not set a pipeline-specific artifacts bucket will be used. :param parameter_values: Optional. The mapping from runtime parameter names to its values that control the pipeline run. :param input_artifacts: Optional. The mapping from the runtime parameter name for this artifact to its resource id. For example: "vertex_model":"456". Note: full resource name ("projects/123/locations/us-central1/metadataStores/default/artifacts/456") cannot be used. :param enable_caching: Optional. Whether to turn on caching for the run. If this is not set, defaults to the compile time settings, which are True for all tasks by default, while users may specify different caching options for individual tasks. If this is set, the setting applies to all tasks in the pipeline. Overrides the compile time settings. :param encryption_spec_key_name: Optional. The Cloud KMS resource identifier of the customer managed encryption key used to protect the job. Has the form: ``projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key``. The key needs to be in the same region as where the compute resource is created. If this is set, then all resources created by the PipelineJob will be encrypted with the provided encryption key. Overrides encryption_spec_key_name set in aiplatform.init. :param labels: Optional. The user defined metadata to organize PipelineJob. :param failure_policy: Optional. The failure policy - "slow" or "fast". Currently, the default of a pipeline is that the pipeline will continue to run until no more tasks can be executed, also known as PIPELINE_FAILURE_POLICY_FAIL_SLOW (corresponds to "slow"). However, if a pipeline is set to PIPELINE_FAILURE_POLICY_FAIL_FAST (corresponds to "fast"), it will stop scheduling any new tasks when a task has failed. Any scheduled tasks will continue to completion. :param service_account: Optional. Specifies the service account for workload run-as account. Users submitting jobs must have act-as permission on this run-as account. :param network: Optional. The full name of the Compute Engine network to which the job should be peered. For example, projects/12345/global/networks/myVPC. Private services access must already be configured for the network. If left unspecified, the network set in aiplatform.init will be used. Otherwise, the job is not peered with any network. :param create_request_timeout: Optional. The timeout for the create request in seconds. :param experiment: Optional. The Vertex AI experiment name or instance to associate to this PipelineJob. Metrics produced by the PipelineJob as system.Metric Artifacts will be associated as metrics to the current Experiment Run. Pipeline parameters will be associated as parameters to the current Experiment Run. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :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 deferrable: If True, run the task in the deferrable mode. :param poll_interval: Time (seconds) to wait between two consecutive calls to check the job. The default is 300 seconds. """ template_fields = [ "region", "project_id", "input_artifacts", "impersonation_chain", "template_path", "pipeline_root", "parameter_values", "service_account", ] operator_extra_links = (VertexAIPipelineJobLink(),) def __init__( self, *, project_id: str, region: str, display_name: str, template_path: str, job_id: str | None = None, pipeline_root: str | None = None, parameter_values: dict[str, Any] | None = None, input_artifacts: dict[str, str] | None = None, enable_caching: bool | None = None, encryption_spec_key_name: str | None = None, labels: dict[str, str] | None = None, failure_policy: str | None = None, service_account: str | None = None, network: str | None = None, create_request_timeout: float | None = None, experiment: str | experiment_resources.Experiment | None = None, gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False), poll_interval: int = 5 * 60, **kwargs, ) -> None: super().__init__(**kwargs) self.region = region self.project_id = project_id self.display_name = display_name self.template_path = template_path self.job_id = job_id self.pipeline_root = pipeline_root self.parameter_values = parameter_values self.input_artifacts = input_artifacts self.enable_caching = enable_caching self.encryption_spec_key_name = encryption_spec_key_name self.labels = labels self.failure_policy = failure_policy self.service_account = service_account self.network = network self.create_request_timeout = create_request_timeout self.experiment = experiment self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain self.deferrable = deferrable self.poll_interval = poll_interval @property def extra_links_params(self) -> dict[str, Any]: return { "region": self.region, "project_id": self.project_id, } def execute(self, context: Context): self.log.info("Running Pipeline job") pipeline_job_obj: PipelineJob = self.hook.submit_pipeline_job( project_id=self.project_id, region=self.region, display_name=self.display_name, template_path=self.template_path, job_id=self.job_id, pipeline_root=self.pipeline_root, parameter_values=self.parameter_values, input_artifacts=self.input_artifacts, enable_caching=self.enable_caching, encryption_spec_key_name=self.encryption_spec_key_name, labels=self.labels, failure_policy=self.failure_policy, service_account=self.service_account, network=self.network, create_request_timeout=self.create_request_timeout, experiment=self.experiment, ) pipeline_job_id = pipeline_job_obj.job_id self.log.info("Pipeline job was created. Job id: %s", pipeline_job_id) context["ti"].xcom_push(key="pipeline_job_id", value=pipeline_job_id) VertexAIPipelineJobLink.persist(context=context, pipeline_id=pipeline_job_id) if self.deferrable: pipeline_job_obj.wait_for_resource_creation() self.defer( trigger=RunPipelineJobTrigger( conn_id=self.gcp_conn_id, project_id=self.project_id, location=pipeline_job_obj.location, job_id=pipeline_job_id, poll_interval=self.poll_interval, impersonation_chain=self.impersonation_chain, ), method_name="execute_complete", ) pipeline_job_obj.wait() pipeline_job = pipeline_job_obj.to_dict() return pipeline_job def execute_complete(self, context: Context, event: dict[str, Any]) -> dict[str, Any]: if event["status"] == "error": raise AirflowException(event["message"]) return event["job"] def on_kill(self) -> None: """Act as a callback called when the operator is killed; cancel any running job.""" if self.hook: self.hook.cancel_pipeline_job() @cached_property def hook(self) -> PipelineJobHook: return PipelineJobHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, )
RunPipelineJobOperator
python
sphinx-doc__sphinx
sphinx/domains/javascript.py
{ "start": 1119, "end": 9774 }
class ____(ObjectDescription[tuple[str, str]]): """Description of a JavaScript object.""" #: If set to ``True`` this object is callable and a `desc_parameterlist` is #: added has_arguments = False #: If ``allow_nesting`` is ``True``, the object prefixes will be accumulated #: based on directive nesting allow_nesting = False option_spec: ClassVar[OptionSpec] = { 'no-index': directives.flag, 'no-index-entry': directives.flag, 'no-contents-entry': directives.flag, 'no-typesetting': directives.flag, 'noindex': directives.flag, 'noindexentry': directives.flag, 'nocontentsentry': directives.flag, 'single-line-parameter-list': directives.flag, } def get_display_prefix(self) -> list[Node]: #: what is displayed right before the documentation entry return [] def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]: """Breaks down construct signatures Parses out prefix and argument list from construct definition. The namespace and class will be determined by the nesting of domain directives. """ sig = sig.strip() if '(' in sig and sig[-1:] == ')': member, _, arglist = sig.partition('(') member = member.strip() arglist = arglist[:-1].strip() else: member = sig arglist = None # If construct is nested, prefix the current prefix prefix = self.env.ref_context.get('js:object', None) mod_name = self.env.ref_context.get('js:module') name = member try: member_prefix, member_name = member.rsplit('.', 1) except ValueError: member_name = name member_prefix = '' finally: name = member_name if prefix and member_prefix: prefix = f'{prefix}.{member_prefix}' elif prefix is None and member_prefix: prefix = member_prefix fullname = name if prefix: fullname = f'{prefix}.{name}' signode['module'] = mod_name signode['object'] = prefix signode['fullname'] = fullname max_len = ( self.config.javascript_maximum_signature_line_length or self.config.maximum_signature_line_length or 0 ) multi_line_parameter_list = ( 'single-line-parameter-list' not in self.options and (len(sig) > max_len > 0) ) trailing_comma = ( self.env.config.javascript_trailing_comma_in_multi_line_signatures ) display_prefix = self.get_display_prefix() if display_prefix: signode += addnodes.desc_annotation('', '', *display_prefix) actual_prefix = None if prefix: actual_prefix = prefix elif mod_name: actual_prefix = mod_name if actual_prefix: add_name = addnodes.desc_addname('', '') for p in actual_prefix.split('.'): add_name += addnodes.desc_sig_name(p, p) add_name += addnodes.desc_sig_punctuation('.', '.') signode += add_name signode += addnodes.desc_name('', '', addnodes.desc_sig_name(name, name)) if self.has_arguments: if not arglist: signode += addnodes.desc_parameterlist() else: _pseudo_parse_arglist( signode, arglist, multi_line_parameter_list=multi_line_parameter_list, trailing_comma=trailing_comma, env=self.env, ) return fullname, prefix # type: ignore[return-value] def _object_hierarchy_parts(self, sig_node: desc_signature) -> tuple[str, ...]: if 'fullname' not in sig_node: return () modname = sig_node.get('module') fullname = sig_node['fullname'] if modname: return (modname, *fullname.split('.')) else: return tuple(fullname.split('.')) def add_target_and_index( self, name_obj: tuple[str, str], sig: str, signode: desc_signature ) -> None: mod_name = self.env.ref_context.get('js:module', '') fullname = (f'{mod_name}.' if mod_name else '') + name_obj[0] node_id = make_id(self.env, self.state.document, '', fullname) signode['ids'].append(node_id) self.state.document.note_explicit_target(signode) domain = self.env.domains.javascript_domain domain.note_object(fullname, self.objtype, node_id, location=signode) if 'no-index-entry' not in self.options: if index_text := self.get_index_text(mod_name, name_obj): self.indexnode['entries'].append(( 'single', index_text, node_id, '', None, )) def get_index_text(self, objectname: str, name_obj: tuple[str, str]) -> str: name, obj = name_obj if self.objtype == 'function': if not obj: return _('%s() (built-in function)') % name return _('%s() (%s method)') % (name, obj) elif self.objtype == 'class': return _('%s() (class)') % name elif self.objtype == 'data': return _('%s (global variable or constant)') % name elif self.objtype == 'attribute': return _('%s (%s attribute)') % (name, obj) return '' def before_content(self) -> None: """Handle object nesting before content :py:class:`JSObject` represents JavaScript language constructs. For constructs that are nestable, this method will build up a stack of the nesting hierarchy so that it can be later de-nested correctly, in :py:meth:`after_content`. For constructs that aren't nestable, the stack is bypassed, and instead only the most recent object is tracked. This object prefix name will be removed with :py:meth:`after_content`. The following keys are used in ``self.env.ref_context``: js:objects Stores the object prefix history. With each nested element, we add the object prefix to this list. When we exit that object's nesting level, :py:meth:`after_content` is triggered and the prefix is removed from the end of the list. js:object Current object prefix. This should generally reflect the last element in the prefix history """ prefix = None if self.names: (obj_name, obj_name_prefix) = self.names.pop() prefix = obj_name_prefix.strip('.') if obj_name_prefix else None if self.allow_nesting: prefix = obj_name if prefix: self.env.ref_context['js:object'] = prefix if self.allow_nesting: objects = self.env.ref_context.setdefault('js:objects', []) objects.append(prefix) def after_content(self) -> None: """Handle object de-nesting after content If this class is a nestable object, removing the last nested class prefix ends further nesting in the object. If this class is not a nestable object, the list of classes should not be altered as we didn't affect the nesting levels in :py:meth:`before_content`. """ objects = self.env.ref_context.setdefault('js:objects', []) if self.allow_nesting: with contextlib.suppress(IndexError): objects.pop() self.env.ref_context['js:object'] = objects[-1] if len(objects) > 0 else None def _toc_entry_name(self, sig_node: desc_signature) -> str: if not sig_node.get('_toc_parts'): return '' config = self.config objtype = sig_node.parent.get('objtype') if config.add_function_parentheses and objtype in {'function', 'method'}: parens = '()' else: parens = '' *parents, name = sig_node['_toc_parts'] if config.toc_object_entries_show_parents == 'domain': return sig_node.get('fullname', name) + parens if config.toc_object_entries_show_parents == 'hide': return name + parens if config.toc_object_entries_show_parents == 'all': return '.'.join([*parents, name + parens]) return ''
JSObject
python
sphinx-doc__sphinx
sphinx/domains/cpp/_ast.py
{ "start": 25223, "end": 26061 }
class ____(ASTPostfixOp): def __init__(self, name: ASTNestedName) -> None: self.name = name def __eq__(self, other: object) -> bool: if not isinstance(other, ASTPostfixMember): return NotImplemented return self.name == other.name def __hash__(self) -> int: return hash(self.name) def _stringify(self, transform: StringifyTransform) -> str: return '.' + transform(self.name) def get_id(self, idPrefix: str, version: int) -> str: return 'dt' + idPrefix + self.name.get_id(version) def describe_signature( self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol ) -> None: signode += addnodes.desc_sig_punctuation('.', '.') self.name.describe_signature(signode, 'noneIsName', env, symbol)
ASTPostfixMember
python
wandb__wandb
wandb/sdk/artifacts/_generated/artifact_collection_membership_file_urls.py
{ "start": 1017, "end": 1243 }
class ____( GQLResult ): files: Optional[ ArtifactCollectionMembershipFileUrlsProjectArtifactCollectionArtifactMembershipFiles ]
ArtifactCollectionMembershipFileUrlsProjectArtifactCollectionArtifactMembership
python
django-debug-toolbar__django-debug-toolbar
debug_toolbar/panels/profiling.py
{ "start": 306, "end": 4470 }
class ____: def __init__( self, statobj, func, depth=0, stats=None, id=0, parent_ids=None, hsv=(0, 0.5, 1) ): self.statobj = statobj self.func = func if stats: self.stats = stats else: self.stats = statobj.stats[func][:4] self.depth = depth self.id = id self.parent_ids = parent_ids or [] self.hsv = hsv self.has_subfuncs = False def parent_classes(self): return self.parent_classes def background(self): r, g, b = hsv_to_rgb(*self.hsv) return f"rgb({r * 100:f}%,{g * 100:f}%,{b * 100:f}%)" def is_project_func(self): """ Check if the function is from the project code. Project code is identified by the BASE_DIR setting which is used in Django projects by default. """ if hasattr(settings, "BASE_DIR"): file_name, _, _ = self.func base_dir = str(settings.BASE_DIR) file_name = os.path.normpath(file_name) base_dir = os.path.normpath(base_dir) return file_name.startswith(base_dir) and not any( directory in file_name.split(os.path.sep) for directory in ["site-packages", "dist-packages"] ) return None def func_std_string(self): # match what old profile produced func_name = self.func if func_name[:2] == ("~", 0): # special case for built-in functions name = func_name[2] if name.startswith("<") and name.endswith(">"): return f"{{{name[1:-1]}}}" else: return name else: file_name, line_num, method = self.func idx = file_name.find("/site-packages/") if idx > -1: file_name = file_name[(idx + 14) :] split_path = file_name.rsplit(os.sep, 1) if len(split_path) > 1: file_path, file_name = file_name.rsplit(os.sep, 1) else: file_path = "<module>" return format_html( '<span class="djdt-path">{0}/</span>' '<span class="djdt-file">{1}</span>' ' in <span class="djdt-func">{3}</span>' '(<span class="djdt-lineno">{2}</span>)', file_path, file_name, line_num, method, ) def subfuncs(self): h, s, v = self.hsv count = len(self.statobj.all_callees[self.func]) for i, (func, stats) in enumerate(self.statobj.all_callees[self.func].items()): h1 = h + ((i + 1) / count) / (self.depth + 1) s1 = 0 if self.stats[3] == 0 else s * (stats[3] / self.stats[3]) yield FunctionCall( self.statobj, func, self.depth + 1, stats=stats, id=str(self.id) + "_" + str(i), parent_ids=self.parent_ids + [self.id], hsv=(h1, s1, 1), ) def count(self): return self.stats[1] def tottime(self): return self.stats[2] def cumtime(self): cc, nc, tt, ct = self.stats return self.stats[3] def tottime_per_call(self): cc, nc, tt, ct = self.stats if nc == 0: return 0 return tt / nc def cumtime_per_call(self): cc, nc, tt, ct = self.stats if cc == 0: return 0 return ct / cc def indent(self): return 16 * self.depth def serialize(self): return { "has_subfuncs": self.has_subfuncs, "id": self.id, "parent_ids": self.parent_ids, "is_project_func": self.is_project_func(), "indent": self.indent(), "func_std_string": self.func_std_string(), "cumtime": self.cumtime(), "cumtime_per_call": self.cumtime_per_call(), "tottime": self.tottime(), "tottime_per_call": self.tottime_per_call(), "count": self.count(), }
FunctionCall
python
Netflix__metaflow
test/core/tests/secrets_decorator.py
{ "start": 337, "end": 1516 }
class ____(MetaflowTest): """ Test that checks that the timeout decorator works as intended. """ SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] @tag("secrets(sources=%s)" % repr(INLINE_SECRETS_VARS)) @steps(1, ["all"]) def step_all(self): import os from metaflow import current if ( self._graph[current.step_name].parallel_step and current.parallel.node_index != 0 and os.environ.get("METAFLOW_RUNTIME_ENVIRONMENT", "local") == "local" ): # We don't check worker task secrets when there is a parallel step # run locally. # todo (future): support the case where secrets need to be passsed to the # control task in a parallel step when run locally. return assert os.environ.get("secret_1") == "Pizza is a vegetable." assert os.environ.get("SECRET_2") == "How do eels reproduce?"
SecretsDecoratorTest
python
dask__dask
dask/tests/test_task_spec.py
{ "start": 11933, "end": 12047 }
class ____(namedtuple("PlainNamedTuple", "value")): """Namedtuple with a default constructor."""
PlainNamedTuple
python
crytic__slither
slither/printers/abstract_printer.py
{ "start": 297, "end": 1756 }
class ____(metaclass=abc.ABCMeta): ARGUMENT = "" # run the printer with slither.py --ARGUMENT HELP = "" # help information WIKI = "" def __init__(self, slither: "Slither", logger: Optional[Logger]) -> None: self.slither = slither self.contracts = slither.contracts self.filename = slither.filename self.logger = logger if not self.HELP: raise IncorrectPrinterInitialization( f"HELP is not initialized {self.__class__.__name__}" ) if not self.ARGUMENT: raise IncorrectPrinterInitialization( f"ARGUMENT is not initialized {self.__class__.__name__}" ) if not self.WIKI: raise IncorrectPrinterInitialization( f"WIKI is not initialized {self.__class__.__name__}" ) def info(self, info: str) -> None: if self.logger: self.logger.info(info) def generate_output( self, info: Union[str, List[Union[str, SupportedOutput]]], additional_fields: Optional[Dict] = None, ) -> output.Output: if additional_fields is None: additional_fields = {} printer_output = output.Output(info, additional_fields) printer_output.data["printer"] = self.ARGUMENT return printer_output @abc.abstractmethod def output(self, filename: str) -> output.Output: pass
AbstractPrinter
python
getsentry__sentry
src/sentry/monitors/processing_errors/errors.py
{ "start": 3426, "end": 3635 }
class ____(TypedDict): """ The maximum number of monitors allowed per project has been exceeded """ type: Literal[ProcessingErrorType.MONITOR_LIMIT_EXCEEDED] reason: str
MonitorLimitExceeded
python
uqfoundation__dill
dill/_dill.py
{ "start": 12261, "end": 12324 }
class ____(PickleWarning, PicklingError): pass
PicklingWarning
python
django__django
django/contrib/auth/management/commands/createsuperuser.py
{ "start": 598, "end": 13576 }
class ____(BaseCommand): help = "Used to create a superuser." requires_migrations_checks = True stealth_options = ("stdin",) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.UserModel = get_user_model() self.username_field = self.UserModel._meta.get_field( self.UserModel.USERNAME_FIELD ) def add_arguments(self, parser): parser.add_argument( "--%s" % self.UserModel.USERNAME_FIELD, help="Specifies the login for the superuser.", ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help=( "Tells Django to NOT prompt the user for input of any kind. " "You must use --%s with --noinput, along with an option for " "any other required field. Superusers created with --noinput will " "not be able to log in until they're given a valid password." % self.UserModel.USERNAME_FIELD ), ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help='Specifies the database to use. Default is "default".', ) for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) if field.many_to_many: if ( field.remote_field.through and not field.remote_field.through._meta.auto_created ): raise CommandError( "Required field '%s' specifies a many-to-many " "relation through model, which is not supported." % field_name ) else: parser.add_argument( "--%s" % field_name, action="append", help=( "Specifies the %s for the superuser. Can be used " "multiple times." % field_name, ), ) else: parser.add_argument( "--%s" % field_name, help="Specifies the %s for the superuser." % field_name, ) def execute(self, *args, **options): self.stdin = options.get("stdin", sys.stdin) # Used for testing return super().execute(*args, **options) def handle(self, *args, **options): username = options[self.UserModel.USERNAME_FIELD] database = options["database"] user_data = {} verbose_field_name = self.username_field.verbose_name try: self.UserModel._meta.get_field(PASSWORD_FIELD) except exceptions.FieldDoesNotExist: pass else: # If not provided, create the user with an unusable password. user_data[PASSWORD_FIELD] = None try: if options["interactive"]: # Same as user_data but without many to many fields and with # foreign keys as fake model instances instead of raw IDs. fake_user_data = {} if hasattr(self.stdin, "isatty") and not self.stdin.isatty(): raise NotRunningInTTYException default_username = get_default_username(database=database) if username: error_msg = self._validate_username( username, verbose_field_name, database ) if error_msg: self.stderr.write(error_msg) username = None elif username == "": raise CommandError( "%s cannot be blank." % capfirst(verbose_field_name) ) # Prompt for username. while username is None: message = self._get_input_message( self.username_field, default_username ) username = self.get_input_data( self.username_field, message, default_username ) if username: error_msg = self._validate_username( username, verbose_field_name, database ) if error_msg: self.stderr.write(error_msg) username = None continue user_data[self.UserModel.USERNAME_FIELD] = username fake_user_data[self.UserModel.USERNAME_FIELD] = ( self.username_field.remote_field.model(username) if self.username_field.remote_field else username ) # Prompt for required fields. for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = options[field_name] if user_data[field_name] is not None: user_data[field_name] = field.clean(user_data[field_name], None) while user_data[field_name] is None: message = self._get_input_message(field) input_value = self.get_input_data(field, message) user_data[field_name] = input_value if field.many_to_many and input_value: if not input_value.strip(): user_data[field_name] = None self.stderr.write("Error: This field cannot be blank.") continue user_data[field_name] = [ pk.strip() for pk in input_value.split(",") ] if not field.many_to_many: fake_user_data[field_name] = user_data[field_name] # Wrap any foreign keys in fake model instances. if field.many_to_one: fake_user_data[field_name] = field.remote_field.model( user_data[field_name] ) # Prompt for a password if the model has one. while PASSWORD_FIELD in user_data and user_data[PASSWORD_FIELD] is None: password = getpass.getpass() password2 = getpass.getpass("Password (again): ") if password != password2: self.stderr.write("Error: Your passwords didn't match.") # Don't validate passwords that don't match. continue if password.strip() == "": self.stderr.write("Error: Blank passwords aren't allowed.") # Don't validate blank passwords. continue try: validate_password(password2, self.UserModel(**fake_user_data)) except exceptions.ValidationError as err: self.stderr.write("\n".join(err.messages)) response = input( "Bypass password validation and create user anyway? [y/N]: " ) if response.lower() != "y": continue user_data[PASSWORD_FIELD] = password else: # Non-interactive mode. # Use password from environment variable, if provided. if ( PASSWORD_FIELD in user_data and "DJANGO_SUPERUSER_PASSWORD" in os.environ ): user_data[PASSWORD_FIELD] = os.environ["DJANGO_SUPERUSER_PASSWORD"] # Use username from environment variable, if not provided in # options. if username is None: username = os.environ.get( "DJANGO_SUPERUSER_" + self.UserModel.USERNAME_FIELD.upper() ) if username is None: raise CommandError( "You must use --%s with --noinput." % self.UserModel.USERNAME_FIELD ) else: error_msg = self._validate_username( username, verbose_field_name, database ) if error_msg: raise CommandError(error_msg) user_data[self.UserModel.USERNAME_FIELD] = username for field_name in self.UserModel.REQUIRED_FIELDS: env_var = "DJANGO_SUPERUSER_" + field_name.upper() value = options[field_name] or os.environ.get(env_var) field = self.UserModel._meta.get_field(field_name) if not value: if field.blank and ( options[field_name] == "" or os.environ.get(env_var) == "" ): continue raise CommandError( "You must use --%s with --noinput." % field_name ) user_data[field_name] = field.clean(value, None) if field.many_to_many and isinstance(user_data[field_name], str): user_data[field_name] = [ pk.strip() for pk in user_data[field_name].split(",") ] self.UserModel._default_manager.db_manager(database).create_superuser( **user_data ) if options["verbosity"] >= 1: self.stdout.write("Superuser created successfully.") except KeyboardInterrupt: self.stderr.write("\nOperation cancelled.") sys.exit(1) except exceptions.ValidationError as e: raise CommandError("; ".join(e.messages)) except NotRunningInTTYException: self.stdout.write( "Superuser creation skipped due to not running in a TTY. " "You can run `manage.py createsuperuser` in your project " "to create one manually." ) def get_input_data(self, field, message, default=None): """ Override this method if you want to customize data inputs or validation exceptions. """ raw_value = input(message) if default and raw_value == "": raw_value = default try: val = field.clean(raw_value, None) except exceptions.ValidationError as e: self.stderr.write("Error: %s" % "; ".join(e.messages)) val = None return val def _get_input_message(self, field, default=None): return "%s%s%s: " % ( capfirst(field.verbose_name), " (leave blank to use '%s')" % default if default else "", ( " (%s.%s)" % ( field.remote_field.model._meta.object_name, ( field.m2m_target_field_name() if field.many_to_many else field.remote_field.field_name ), ) if field.remote_field else "" ), ) @cached_property def username_is_unique(self): if self.username_field.unique: return True return any( len(unique_constraint.fields) == 1 and unique_constraint.fields[0] == self.username_field.name for unique_constraint in self.UserModel._meta.total_unique_constraints ) def _validate_username(self, username, verbose_field_name, database): """Validate username. If invalid, return a string error message.""" if self.username_is_unique: try: self.UserModel._default_manager.db_manager(database).get_by_natural_key( username ) except self.UserModel.DoesNotExist: pass else: return "Error: That %s is already taken." % verbose_field_name if not username: return "%s cannot be blank." % capfirst(verbose_field_name) try: self.username_field.clean(username, None) except exceptions.ValidationError as e: return "; ".join(e.messages)
Command
python
getsentry__sentry
src/sentry/sentry_apps/api/serializers/sentry_app_webhook_request.py
{ "start": 753, "end": 834 }
class ____(TypedDict): name: str slug: str id: int
OrganizationResponse
python
tensorflow__tensorflow
tensorflow/python/keras/callbacks.py
{ "start": 70859, "end": 73064 }
class ____(Callback): """Callback used to stream events to a server. Requires the `requests` library. Events are sent to `root + '/publish/epoch/end/'` by default. Calls are HTTP POST, with a `data` argument which is a JSON-encoded dictionary of event data. If `send_as_json=True`, the content type of the request will be `"application/json"`. Otherwise the serialized JSON will be sent within a form. Args: root: String; root url of the target server. path: String; path relative to `root` to which the events will be sent. field: String; JSON field under which the data will be stored. The field is used only if the payload is sent within a form (i.e. send_as_json is set to False). headers: Dictionary; optional custom HTTP headers. send_as_json: Boolean; whether the request should be sent as `"application/json"`. """ def __init__(self, root='http://localhost:9000', path='/publish/epoch/end/', field='data', headers=None, send_as_json=False): super(RemoteMonitor, self).__init__() self.root = root self.path = path self.field = field self.headers = headers self.send_as_json = send_as_json def on_epoch_end(self, epoch, logs=None): if requests is None: raise ImportError('RemoteMonitor requires the `requests` library.') logs = logs or {} send = {} send['epoch'] = epoch for k, v in logs.items(): # np.ndarray and np.generic are not scalar types # therefore we must unwrap their scalar values and # pass to the json-serializable dict 'send' if isinstance(v, (np.ndarray, np.generic)): send[k] = v.item() else: send[k] = v try: if self.send_as_json: requests.post(self.root + self.path, json=send, headers=self.headers) else: requests.post( self.root + self.path, {self.field: json.dumps(send)}, headers=self.headers) except requests.exceptions.RequestException: logging.warning('Warning: could not reach RemoteMonitor ' 'root server at ' + str(self.root))
RemoteMonitor
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 81042, "end": 81509 }
class ____(BaseModel, extra="forbid"): key: str = Field(..., description="Payload key to order by") direction: Optional["Direction"] = Field( default=None, description="Direction of ordering: `asc` or `desc`. Default is ascending." ) start_from: Optional["StartFrom"] = Field( default=None, description="Which payload value to start scrolling from. Default is the lowest value for `asc` and the highest for `desc`", )
OrderBy
python
pytest-dev__pytest
testing/test_pathlib.py
{ "start": 4215, "end": 21564 }
class ____: """ Most of the tests here were copied from py lib's tests for "py.local.path.pyimport". Having our own pyimport-like function is inline with removing py.path dependency in the future. """ @pytest.fixture(scope="session") def path1(self, tmp_path_factory: TempPathFactory) -> Generator[Path]: path = tmp_path_factory.mktemp("path") self.setuptestfs(path) yield path assert path.joinpath("samplefile").exists() @pytest.fixture(autouse=True) def preserve_sys(self): with unittest.mock.patch.dict(sys.modules): with unittest.mock.patch.object(sys, "path", list(sys.path)): yield def setuptestfs(self, path: Path) -> None: # print "setting up test fs for", repr(path) samplefile = path / "samplefile" samplefile.write_text("samplefile\n", encoding="utf-8") execfile = path / "execfile" execfile.write_text("x=42", encoding="utf-8") execfilepy = path / "execfile.py" execfilepy.write_text("x=42", encoding="utf-8") d = {1: 2, "hello": "world", "answer": 42} path.joinpath("samplepickle").write_bytes(pickle.dumps(d, 1)) sampledir = path / "sampledir" sampledir.mkdir() sampledir.joinpath("otherfile").touch() otherdir = path / "otherdir" otherdir.mkdir() otherdir.joinpath("__init__.py").touch() module_a = otherdir / "a.py" module_a.write_text("from .b import stuff as result\n", encoding="utf-8") module_b = otherdir / "b.py" module_b.write_text('stuff="got it"\n', encoding="utf-8") module_c = otherdir / "c.py" module_c.write_text( dedent( """ import pluggy; import otherdir.a value = otherdir.a.result """ ), encoding="utf-8", ) module_d = otherdir / "d.py" module_d.write_text( dedent( """ import pluggy; from otherdir import a value2 = a.result """ ), encoding="utf-8", ) def test_smoke_test(self, path1: Path, ns_param: bool) -> None: obj = import_path( path1 / "execfile.py", root=path1, consider_namespace_packages=ns_param ) assert obj.x == 42 assert obj.__name__ == "execfile" def test_import_path_missing_file(self, path1: Path, ns_param: bool) -> None: with pytest.raises(ImportPathMismatchError): import_path( path1 / "sampledir", root=path1, consider_namespace_packages=ns_param ) def test_renamed_dir_creates_mismatch( self, tmp_path: Path, monkeypatch: MonkeyPatch, ns_param: bool ) -> None: tmp_path.joinpath("a").mkdir() p = tmp_path.joinpath("a", "test_x123.py") p.touch() import_path(p, root=tmp_path, consider_namespace_packages=ns_param) tmp_path.joinpath("a").rename(tmp_path.joinpath("b")) with pytest.raises(ImportPathMismatchError): import_path( tmp_path.joinpath("b", "test_x123.py"), root=tmp_path, consider_namespace_packages=ns_param, ) # Errors can be ignored. monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "1") import_path( tmp_path.joinpath("b", "test_x123.py"), root=tmp_path, consider_namespace_packages=ns_param, ) # PY_IGNORE_IMPORTMISMATCH=0 does not ignore error. monkeypatch.setenv("PY_IGNORE_IMPORTMISMATCH", "0") with pytest.raises(ImportPathMismatchError): import_path( tmp_path.joinpath("b", "test_x123.py"), root=tmp_path, consider_namespace_packages=ns_param, ) def test_messy_name(self, tmp_path: Path, ns_param: bool) -> None: # https://bitbucket.org/hpk42/py-trunk/issue/129 path = tmp_path / "foo__init__.py" path.touch() module = import_path(path, root=tmp_path, consider_namespace_packages=ns_param) assert module.__name__ == "foo__init__" def test_dir(self, tmp_path: Path, ns_param: bool) -> None: p = tmp_path / "hello_123" p.mkdir() p_init = p / "__init__.py" p_init.touch() m = import_path(p, root=tmp_path, consider_namespace_packages=ns_param) assert m.__name__ == "hello_123" m = import_path(p_init, root=tmp_path, consider_namespace_packages=ns_param) assert m.__name__ == "hello_123" def test_a(self, path1: Path, ns_param: bool) -> None: otherdir = path1 / "otherdir" mod = import_path( otherdir / "a.py", root=path1, consider_namespace_packages=ns_param ) assert mod.result == "got it" assert mod.__name__ == "otherdir.a" def test_b(self, path1: Path, ns_param: bool) -> None: otherdir = path1 / "otherdir" mod = import_path( otherdir / "b.py", root=path1, consider_namespace_packages=ns_param ) assert mod.stuff == "got it" assert mod.__name__ == "otherdir.b" def test_c(self, path1: Path, ns_param: bool) -> None: otherdir = path1 / "otherdir" mod = import_path( otherdir / "c.py", root=path1, consider_namespace_packages=ns_param ) assert mod.value == "got it" def test_d(self, path1: Path, ns_param: bool) -> None: otherdir = path1 / "otherdir" mod = import_path( otherdir / "d.py", root=path1, consider_namespace_packages=ns_param ) assert mod.value2 == "got it" def test_import_after(self, tmp_path: Path, ns_param: bool) -> None: tmp_path.joinpath("xxxpackage").mkdir() tmp_path.joinpath("xxxpackage", "__init__.py").touch() mod1path = tmp_path.joinpath("xxxpackage", "module1.py") mod1path.touch() mod1 = import_path( mod1path, root=tmp_path, consider_namespace_packages=ns_param ) assert mod1.__name__ == "xxxpackage.module1" from xxxpackage import module1 assert module1 is mod1 def test_check_filepath_consistency( self, monkeypatch: MonkeyPatch, tmp_path: Path, ns_param: bool ) -> None: name = "pointsback123" p = tmp_path.joinpath(name + ".py") p.touch() with monkeypatch.context() as mp: for ending in (".pyc", ".pyo"): mod = ModuleType(name) pseudopath = tmp_path.joinpath(name + ending) pseudopath.touch() mod.__file__ = str(pseudopath) mp.setitem(sys.modules, name, mod) newmod = import_path( p, root=tmp_path, consider_namespace_packages=ns_param ) assert mod == newmod mod = ModuleType(name) pseudopath = tmp_path.joinpath(name + "123.py") pseudopath.touch() mod.__file__ = str(pseudopath) monkeypatch.setitem(sys.modules, name, mod) with pytest.raises(ImportPathMismatchError) as excinfo: import_path(p, root=tmp_path, consider_namespace_packages=ns_param) modname, modfile, orig = excinfo.value.args assert modname == name assert modfile == str(pseudopath) assert orig == p assert issubclass(ImportPathMismatchError, ImportError) def test_ensuresyspath_append(self, tmp_path: Path, ns_param: bool) -> None: root1 = tmp_path / "root1" root1.mkdir() file1 = root1 / "x123.py" file1.touch() assert str(root1) not in sys.path import_path( file1, mode="append", root=tmp_path, consider_namespace_packages=ns_param ) assert str(root1) == sys.path[-1] assert str(root1) not in sys.path[:-1] def test_invalid_path(self, tmp_path: Path, ns_param: bool) -> None: with pytest.raises(ImportError): import_path( tmp_path / "invalid.py", root=tmp_path, consider_namespace_packages=ns_param, ) @pytest.fixture def simple_module( self, tmp_path: Path, request: pytest.FixtureRequest ) -> Iterator[Path]: name = f"mymod_{request.node.name}" fn = tmp_path / f"_src/tests/{name}.py" fn.parent.mkdir(parents=True) fn.write_text("def foo(x): return 40 + x", encoding="utf-8") module_name = module_name_from_path(fn, root=tmp_path) yield fn sys.modules.pop(module_name, None) def test_importmode_importlib( self, simple_module: Path, tmp_path: Path, request: pytest.FixtureRequest, ns_param: bool, ) -> None: """`importlib` mode does not change sys.path.""" module = import_path( simple_module, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param, ) assert module.foo(2) == 42 assert str(simple_module.parent) not in sys.path assert module.__name__ in sys.modules assert module.__name__ == f"_src.tests.mymod_{request.node.name}" assert "_src" in sys.modules assert "_src.tests" in sys.modules def test_remembers_previous_imports( self, simple_module: Path, tmp_path: Path, ns_param: bool ) -> None: """`importlib` mode called remembers previous module (#10341, #10811).""" module1 = import_path( simple_module, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param, ) module2 = import_path( simple_module, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param, ) assert module1 is module2 def test_no_meta_path_found( self, simple_module: Path, monkeypatch: MonkeyPatch, tmp_path: Path, ns_param: bool, ) -> None: """Even without any meta_path should still import module.""" monkeypatch.setattr(sys, "meta_path", []) module = import_path( simple_module, mode="importlib", root=tmp_path, consider_namespace_packages=ns_param, ) assert module.foo(2) == 42 # mode='importlib' fails if no spec is found to load the module import importlib.util # Force module to be re-imported. del sys.modules[module.__name__] monkeypatch.setattr( importlib.util, "spec_from_file_location", lambda *args, **kwargs: None ) with pytest.raises(ImportError): import_path( simple_module, mode="importlib", root=tmp_path, consider_namespace_packages=False, ) def test_resolve_package_path(tmp_path: Path) -> None: pkg = tmp_path / "pkg1" pkg.mkdir() (pkg / "__init__.py").touch() (pkg / "subdir").mkdir() (pkg / "subdir/__init__.py").touch() assert resolve_package_path(pkg) == pkg assert resolve_package_path(pkg / "subdir/__init__.py") == pkg def test_package_unimportable(tmp_path: Path) -> None: pkg = tmp_path / "pkg1-1" pkg.mkdir() pkg.joinpath("__init__.py").touch() subdir = pkg / "subdir" subdir.mkdir() (pkg / "subdir/__init__.py").touch() assert resolve_package_path(subdir) == subdir xyz = subdir / "xyz.py" xyz.touch() assert resolve_package_path(xyz) == subdir assert not resolve_package_path(pkg) def test_access_denied_during_cleanup(tmp_path: Path, monkeypatch: MonkeyPatch) -> None: """Ensure that deleting a numbered dir does not fail because of OSErrors (#4262).""" path = tmp_path / "temp-1" path.mkdir() def renamed_failed(*args): raise OSError("access denied") monkeypatch.setattr(Path, "rename", renamed_failed) lock_path = get_lock_path(path) maybe_delete_a_numbered_dir(path) assert not lock_path.is_file() def test_long_path_during_cleanup(tmp_path: Path) -> None: """Ensure that deleting long path works (particularly on Windows (#6775)).""" path = (tmp_path / ("a" * 250)).resolve() if sys.platform == "win32": # make sure that the full path is > 260 characters without any # component being over 260 characters assert len(str(path)) > 260 extended_path = "\\\\?\\" + str(path) else: extended_path = str(path) os.mkdir(extended_path) assert os.path.isdir(extended_path) maybe_delete_a_numbered_dir(path) assert not os.path.isdir(extended_path) def test_get_extended_length_path_str() -> None: assert get_extended_length_path_str(r"c:\foo") == r"\\?\c:\foo" assert get_extended_length_path_str(r"\\share\foo") == r"\\?\UNC\share\foo" assert get_extended_length_path_str(r"\\?\UNC\share\foo") == r"\\?\UNC\share\foo" assert get_extended_length_path_str(r"\\?\c:\foo") == r"\\?\c:\foo" def test_suppress_error_removing_lock(tmp_path: Path) -> None: """ensure_deletable should be resilient if lock file cannot be removed (#5456, #7491)""" path = tmp_path / "dir" path.mkdir() lock = get_lock_path(path) lock.touch() mtime = lock.stat().st_mtime with unittest.mock.patch.object(Path, "unlink", side_effect=OSError) as m: assert not ensure_deletable( path, consider_lock_dead_if_created_before=mtime + 30 ) assert m.call_count == 1 assert lock.is_file() with unittest.mock.patch.object(Path, "is_file", side_effect=OSError) as m: assert not ensure_deletable( path, consider_lock_dead_if_created_before=mtime + 30 ) assert m.call_count == 1 assert lock.is_file() # check now that we can remove the lock file in normal circumstances assert ensure_deletable(path, consider_lock_dead_if_created_before=mtime + 30) assert not lock.is_file() def test_bestrelpath() -> None: curdir = Path("/foo/bar/baz/path") assert bestrelpath(curdir, curdir) == "." assert bestrelpath(curdir, curdir / "hello" / "world") == "hello" + os.sep + "world" assert bestrelpath(curdir, curdir.parent / "sister") == ".." + os.sep + "sister" assert bestrelpath(curdir, curdir.parent) == ".." assert bestrelpath(curdir, Path("hello")) == "hello" def test_commonpath() -> None: path = Path("/foo/bar/baz/path") subpath = path / "sampledir" assert commonpath(path, subpath) == path assert commonpath(subpath, path) == path assert commonpath(Path(str(path) + "suffix"), path) == path.parent assert commonpath(path, path.parent.parent) == path.parent.parent def test_visit_ignores_errors(tmp_path: Path) -> None: symlink_or_skip("recursive", tmp_path / "recursive") tmp_path.joinpath("foo").write_bytes(b"") tmp_path.joinpath("bar").write_bytes(b"") assert [ entry.name for entry in visit(str(tmp_path), recurse=lambda entry: False) ] == ["bar", "foo"] @pytest.mark.skipif(not sys.platform.startswith("win"), reason="Windows only") def test_samefile_false_negatives(tmp_path: Path, monkeypatch: MonkeyPatch) -> None: """ import_file() should not raise ImportPathMismatchError if the paths are exactly equal on Windows. It seems directories mounted as UNC paths make os.path.samefile return False, even when they are clearly equal. """ module_path = tmp_path.joinpath("my_module.py") module_path.write_text("def foo(): return 42", encoding="utf-8") monkeypatch.syspath_prepend(tmp_path) with monkeypatch.context() as mp: # Forcibly make os.path.samefile() return False here to ensure we are comparing # the paths too. Using a context to narrow the patch as much as possible given # this is an important system function. mp.setattr(os.path, "samefile", lambda x, y: False) module = import_path( module_path, root=tmp_path, consider_namespace_packages=False ) assert getattr(module, "foo")() == 42 def test_scandir_with_non_existent_directory() -> None: # Test with a directory that does not exist non_existent_dir = "path_to_non_existent_dir" result = scandir(non_existent_dir) # Assert that the result is an empty list assert result == [] def test_scandir_handles_os_error() -> None: # Create a mock entry that will raise an OSError when is_file is called mock_entry = unittest.mock.MagicMock() mock_entry.is_file.side_effect = OSError("some permission error") # Mock os.scandir to return an iterator with our mock entry with unittest.mock.patch("os.scandir") as mock_scandir: mock_scandir.return_value.__enter__.return_value = [mock_entry] # Call the scandir function with a path # We expect an OSError to be raised here with pytest.raises(OSError, match="some permission error"): scandir("/fake/path") # Verify that the is_file method was called on the mock entry mock_entry.is_file.assert_called_once()
TestImportPath
python
kubernetes-client__python
kubernetes/client/models/v1_named_rule_with_operations.py
{ "start": 383, "end": 10692 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'api_groups': 'list[str]', 'api_versions': 'list[str]', 'operations': 'list[str]', 'resource_names': 'list[str]', 'resources': 'list[str]', 'scope': 'str' } attribute_map = { 'api_groups': 'apiGroups', 'api_versions': 'apiVersions', 'operations': 'operations', 'resource_names': 'resourceNames', 'resources': 'resources', 'scope': 'scope' } def __init__(self, api_groups=None, api_versions=None, operations=None, resource_names=None, resources=None, scope=None, local_vars_configuration=None): # noqa: E501 """V1NamedRuleWithOperations - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._api_groups = None self._api_versions = None self._operations = None self._resource_names = None self._resources = None self._scope = None self.discriminator = None if api_groups is not None: self.api_groups = api_groups if api_versions is not None: self.api_versions = api_versions if operations is not None: self.operations = operations if resource_names is not None: self.resource_names = resource_names if resources is not None: self.resources = resources if scope is not None: self.scope = scope @property def api_groups(self): """Gets the api_groups of this V1NamedRuleWithOperations. # noqa: E501 APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :return: The api_groups of this V1NamedRuleWithOperations. # noqa: E501 :rtype: list[str] """ return self._api_groups @api_groups.setter def api_groups(self, api_groups): """Sets the api_groups of this V1NamedRuleWithOperations. APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :param api_groups: The api_groups of this V1NamedRuleWithOperations. # noqa: E501 :type: list[str] """ self._api_groups = api_groups @property def api_versions(self): """Gets the api_versions of this V1NamedRuleWithOperations. # noqa: E501 APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :return: The api_versions of this V1NamedRuleWithOperations. # noqa: E501 :rtype: list[str] """ return self._api_versions @api_versions.setter def api_versions(self, api_versions): """Sets the api_versions of this V1NamedRuleWithOperations. APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :param api_versions: The api_versions of this V1NamedRuleWithOperations. # noqa: E501 :type: list[str] """ self._api_versions = api_versions @property def operations(self): """Gets the operations of this V1NamedRuleWithOperations. # noqa: E501 Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :return: The operations of this V1NamedRuleWithOperations. # noqa: E501 :rtype: list[str] """ return self._operations @operations.setter def operations(self, operations): """Sets the operations of this V1NamedRuleWithOperations. Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required. # noqa: E501 :param operations: The operations of this V1NamedRuleWithOperations. # noqa: E501 :type: list[str] """ self._operations = operations @property def resource_names(self): """Gets the resource_names of this V1NamedRuleWithOperations. # noqa: E501 ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. # noqa: E501 :return: The resource_names of this V1NamedRuleWithOperations. # noqa: E501 :rtype: list[str] """ return self._resource_names @resource_names.setter def resource_names(self, resource_names): """Sets the resource_names of this V1NamedRuleWithOperations. ResourceNames is an optional white list of names that the rule applies to. An empty set means that everything is allowed. # noqa: E501 :param resource_names: The resource_names of this V1NamedRuleWithOperations. # noqa: E501 :type: list[str] """ self._resource_names = resource_names @property def resources(self): """Gets the resources of this V1NamedRuleWithOperations. # noqa: E501 Resources is a list of resources this rule applies to. For example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources. If wildcard is present, the validation rule will ensure resources do not overlap with each other. Depending on the enclosing object, subresources might not be allowed. Required. # noqa: E501 :return: The resources of this V1NamedRuleWithOperations. # noqa: E501 :rtype: list[str] """ return self._resources @resources.setter def resources(self, resources): """Sets the resources of this V1NamedRuleWithOperations. Resources is a list of resources this rule applies to. For example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources. If wildcard is present, the validation rule will ensure resources do not overlap with each other. Depending on the enclosing object, subresources might not be allowed. Required. # noqa: E501 :param resources: The resources of this V1NamedRuleWithOperations. # noqa: E501 :type: list[str] """ self._resources = resources @property def scope(self): """Gets the scope of this V1NamedRuleWithOperations. # noqa: E501 scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\". # noqa: E501 :return: The scope of this V1NamedRuleWithOperations. # noqa: E501 :rtype: str """ return self._scope @scope.setter def scope(self, scope): """Sets the scope of this V1NamedRuleWithOperations. scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\". # noqa: E501 :param scope: The scope of this V1NamedRuleWithOperations. # noqa: E501 :type: str """ self._scope = scope def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1NamedRuleWithOperations): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1NamedRuleWithOperations): return True return self.to_dict() != other.to_dict()
V1NamedRuleWithOperations
python
jmcnamara__XlsxWriter
xlsxwriter/test/styles/test_write_fonts.py
{ "start": 332, "end": 1045 }
class ____(unittest.TestCase): """ Test the Styles _write_fonts() method. """ def setUp(self): self.fh = StringIO() self.styles = Styles() self.styles._set_filehandle(self.fh) def test_write_fonts(self): """Test the _write_fonts() method""" xf_format = Format() xf_format.has_font = True self.styles._set_style_properties([[xf_format], None, 1, 0, 0, 0, [], [], 0]) self.styles._write_fonts() exp = """<fonts count="1"><font><sz val="11"/><color theme="1"/><name val="Calibri"/><family val="2"/><scheme val="minor"/></font></fonts>""" got = self.fh.getvalue() self.assertEqual(exp, got)
TestWriteFonts
python
pytorch__pytorch
torch/_inductor/mkldnn_ir.py
{ "start": 17578, "end": 19381 }
class ____(ExternKernelAlloc): def __init__( self, layout, inputs, constant_args=(), ) -> None: self.device_type = get_device_type(inputs[0]) super().__init__( layout, inputs, constant_args, None, op_overload=torch.ops.mkldnn._convolution_transpose_pointwise.default, cpp_kernel_name=f"aoti_torch_{self.device_type}_mkldnn__convolution_transpose_pointwise", ) def codegen(self, wrapper): wrapper.include_extra_header( f"torch/csrc/inductor/aoti_torch/c/shim_{self.device_type}.h" ) super().codegen(wrapper) @classmethod def create( cls, x: "TensorBox", weight: "TensorBox", bias: "TensorBox", padding_: list[int], output_padding_: list[int], stride_: list[int], dilation_: list[int], groups_: int, attr, scalars: Optional[list[Any]], algorithm, ): transposed = True ( inputs, constant_args, kernel_layout, _, _, ) = _prepare_convolution_fusion_create( cls, x, weight, bias, padding_, stride_, dilation_, groups_, transposed, output_padding_, ) constant_args = constant_args + [ attr, may_convert_to_optional(scalars), algorithm, ] packed = ConvolutionTransposeUnary( layout=kernel_layout, inputs=inputs, constant_args=constant_args, ) return _create_output_node(packed)
ConvolutionTransposeUnary
python
tensorflow__tensorflow
tensorflow/python/keras/layers/pooling.py
{ "start": 47047, "end": 49322 }
class ____(GlobalPooling3D): """Global Max pooling operation for 3D data. Args: data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, spatial_dim1, spatial_dim2, spatial_dim3, channels)` while `channels_first` corresponds to inputs with shape `(batch, channels, spatial_dim1, spatial_dim2, spatial_dim3)`. It defaults to the `image_data_format` value found in your Keras config file at `~/.keras/keras.json`. If you never set it, then it will be "channels_last". keepdims: A boolean, whether to keep the spatial dimensions or not. If `keepdims` is `False` (default), the rank of the tensor is reduced for spatial dimensions. If `keepdims` is `True`, the spatial dimensions are retained with length 1. The behavior is the same as for `tf.reduce_max` or `np.max`. Input shape: - If `data_format='channels_last'`: 5D tensor with shape: `(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)` - If `data_format='channels_first'`: 5D tensor with shape: `(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)` Output shape: - If `keepdims`=False: 2D tensor with shape `(batch_size, channels)`. - If `keepdims`=True: - If `data_format='channels_last'`: 5D tensor with shape `(batch_size, 1, 1, 1, channels)` - If `data_format='channels_first'`: 5D tensor with shape `(batch_size, channels, 1, 1, 1)` """ def call(self, inputs): if self.data_format == 'channels_last': return backend.max(inputs, axis=[1, 2, 3], keepdims=self.keepdims) else: return backend.max(inputs, axis=[2, 3, 4], keepdims=self.keepdims) # Aliases AvgPool1D = AveragePooling1D MaxPool1D = MaxPooling1D AvgPool2D = AveragePooling2D MaxPool2D = MaxPooling2D AvgPool3D = AveragePooling3D MaxPool3D = MaxPooling3D GlobalMaxPool1D = GlobalMaxPooling1D GlobalMaxPool2D = GlobalMaxPooling2D GlobalMaxPool3D = GlobalMaxPooling3D GlobalAvgPool1D = GlobalAveragePooling1D GlobalAvgPool2D = GlobalAveragePooling2D GlobalAvgPool3D = GlobalAveragePooling3D
GlobalMaxPooling3D
python
FactoryBoy__factory_boy
factory/declarations.py
{ "start": 15354, "end": 15662 }
class ____(SubFactory): """Fill a list with standard declarations.""" FORCE_SEQUENCE = True def __init__(self, params, list_factory='factory.ListFactory'): params = {str(i): v for i, v in enumerate(params)} super().__init__(list_factory, **params) # Parameters # ==========
List
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/unnecessaryIsInstance1.py
{ "start": 1227, "end": 1275 }
class ____: text: ClassVar[str] = "BAZ"
ClassB
python
pytorch__pytorch
torch/autograd/function.py
{ "start": 26896, "end": 30564 }
class ____(Function): r""" This class is here only for backward compatibility reasons. Use :class:`Function` instead of this for any new use case. """ def __init__(self, inplace=False): super().__init__() self.inplace = inplace def _nested_map(condition, fn, condition_msg=None): def _map(obj): if condition(obj): return fn(obj) elif obj is None: return None elif isinstance(obj, (list, tuple)): mapped = (_map(x) for x in obj) if hasattr(obj, "_fields"): # obj is namedtuple return type(obj)(*mapped) return type(obj)(mapped) elif isinstance(obj, dict): return {x: _map(obj[x]) for x in obj} else: raise ValueError( "Auto nesting doesn't know how to process " "an input object of type " + torch.typename(obj) + ( ". Accepted types: " + condition_msg + ", or lists/tuples of them" if condition_msg else "" ) ) return _map def _jit_unwrap_structured(obj): if hasattr(obj, "_jit_unwrap"): return obj._jit_unwrap() return obj def _iter_filter(condition, allow_unknown=False, condition_msg=None, conversion=None): def _iter(obj): if conversion is not None: obj = conversion(obj) if condition(obj): yield obj elif obj is None: return elif isinstance(obj, (list, tuple)): for o in obj: yield from _iter(o) elif isinstance(obj, dict): # We only accept primitive key types, so we needn't inspect them for o in obj.values(): yield from _iter(o) elif allow_unknown: yield obj else: raise ValueError( "Auto nesting doesn't know how to process " "an input object of type " + torch.typename(obj) + ( ". Accepted types: " + condition_msg + ", or lists/tuples of them" if condition_msg else "" ) ) return _iter def _unflatten(input, proto): # unflatten a list or tuple input into a nested list/tuple structure # specified by proto def unflatten_helper(input, proto): res: list[Optional[torch.Tensor]] = [] if hasattr(proto, "_jit_wrap"): return proto._jit_wrap(input) if not isinstance(proto, (list, tuple)): return input[0], input[1:] for e in proto: if e is None: res.append(e) else: res_e, input = unflatten_helper(input, e) res.append(res_e) return type(proto)(res), input return unflatten_helper(input, proto)[0] _iter_jit_values = _iter_filter( lambda o: o is None or isinstance(o, torch._C.Value), condition_msg="jit's Values or None", ) _iter_tensors = _iter_filter( lambda x: isinstance(x, torch.Tensor), condition_msg="Tensors", conversion=_jit_unwrap_structured, ) _iter_tensors_permissive = _iter_filter( lambda x: isinstance(x, torch.Tensor), allow_unknown=True, condition_msg="Tensors (permissive)", ) _iter_None_tensors = _iter_filter( lambda o: o is None or isinstance(o, torch.Tensor), condition_msg="Tensors or None" ) _map_tensor_data = _nested_map( lambda x: isinstance(x, torch.Tensor), lambda o: o.data, condition_msg="Tensors" )
InplaceFunction
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/init_ops_test.py
{ "start": 37628, "end": 39470 }
class ____(test.TestCase): @test_util.run_deprecated_v1 def testInitializerIdentical(self): for dtype in [dtypes.float32, dtypes.float64]: init1 = init_ops.convolutional_orthogonal_2d(seed=1, dtype=dtype) init2 = init_ops.convolutional_orthogonal_2d(seed=1, dtype=dtype) self.assertTrue(identicaltest(self, init1, init2, (3, 3, 10, 10))) @test_util.run_deprecated_v1 def testInitializerDifferent(self): for dtype in [dtypes.float32, dtypes.float64]: init1 = init_ops.convolutional_orthogonal_2d(seed=1, dtype=dtype) init2 = init_ops.convolutional_orthogonal_2d(seed=2, dtype=dtype) self.assertFalse(identicaltest(self, init1, init2, (3, 3, 10, 10))) @test_util.run_deprecated_v1 def testDuplicatedInitializer(self): init = init_ops.convolutional_orthogonal_2d() self.assertFalse(duplicated_initializer(self, init, 1, (3, 3, 10, 10))) def testInvalidDataType(self): self.assertRaises( ValueError, init_ops.convolutional_orthogonal_2d, dtype=dtypes.string) def testInvalidShape(self): init1 = init_ops.convolutional_orthogonal_2d() with self.session(graph=ops.Graph(), use_gpu=True): self.assertRaises(ValueError, init1, shape=[3, 3, 6, 5]) @test_util.run_deprecated_v1 def testGain(self): shape = (3, 3, 10, 10) for dtype in [dtypes.float32, dtypes.float64]: init1 = init_ops.convolutional_orthogonal_2d(seed=1, dtype=dtype) init2 = init_ops.convolutional_orthogonal_2d( gain=3.14, seed=1, dtype=dtype) with self.session(graph=ops.Graph(), use_gpu=True): t1 = init1(shape).eval() t2 = init2(shape).eval() self.assertAllClose(t1, t2 / 3.14) @test_util.run_all_without_tensor_float_32( "Tests convolutional_orthogonal_3d, which calls matmul")
ConvolutionOrthogonal2dInitializerTest
python
scrapy__scrapy
tests/spiders.py
{ "start": 5398, "end": 5701 }
class ____(SimpleSpider): name = "asyncdef_asyncio_gen_exc" async def parse(self, response): for i in range(10): await asyncio.sleep(0.1) yield {"foo": i} if i > 5: raise ValueError("Stopping the processing")
AsyncDefAsyncioGenExcSpider
python
tensorflow__tensorflow
tensorflow/lite/python/lite.py
{ "start": 51746, "end": 60512 }
class ____(TFLiteConverterBase): """Converter subclass to share functionality between V2 converters.""" def __init__(self): """Constructor for TFLiteConverter.""" super(TFLiteConverterBaseV2, self).__init__() self.inference_input_type = _dtypes.float32 self.inference_output_type = _dtypes.float32 self._metadata.environment.apiVersion = 2 def _validate_inference_input_output_types(self, quant_mode): """Validate inference_input_type and inference_output_type flags.""" default_types = [_dtypes.float32] # We support integer input/output for integer quantized models only. if quant_mode.is_integer_quantization(): if quant_mode.is_post_training_int16x8_quantization(): all_types = default_types + [_dtypes.int16] else: all_types = default_types + [_dtypes.int8, _dtypes.uint8, _dtypes.int16] if ( self.inference_input_type not in all_types or self.inference_output_type not in all_types ): all_types_names = ["tf." + t.name for t in all_types] raise ValueError( "The inference_input_type and inference_output_type " "must be in {}.".format(all_types_names) ) elif ( self.inference_input_type not in default_types or self.inference_output_type not in default_types ): raise ValueError( "The inference_input_type and inference_output_type " "must be tf.float32." ) @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.LOAD_SAVED_MODEL) def _load_saved_model(self, saved_model_dir, saved_model_tags): """Load graph_def from saved model with the default serving signature key. Args: saved_model_dir: Directory of the SavedModel. saved_model_tags: Set of tags identifying the MetaGraphDef within the SavedModel to analyze. Returns: graph_def: The loaded GraphDef. input_tensors: List of input tensors. output_tensors: List of output tensors. """ graph = _ops.Graph() saved_model = _loader_impl.SavedModelLoader(saved_model_dir) saved_model.load_graph(graph, tags=saved_model_tags) meta_graph = saved_model.get_meta_graph_def_from_tags(saved_model_tags) graph_def = meta_graph.graph_def signature_def = meta_graph.signature_def[ _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY ] input_tensors = [ graph.get_tensor_by_name(signature_def.inputs[key].name) for key in signature_def.inputs ] output_tensors = [ graph.get_tensor_by_name(signature_def.outputs[key].name) for key in signature_def.outputs ] return graph_def, input_tensors, output_tensors @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.VALIDATE_INPUTS) def _validate_inputs(self, graph_def, input_tensors): """Validate the input parameters. Args: graph_def: The TensorFlow GraphDef. input_tensors: List of input tensors. Raise: ValueError: Input shape is not specified. Invalid quantization parameters. """ # Update conversion params with graph_def. self._save_conversion_params_metric(graph_def) self._quant_mode = QuantizationMode( self.optimizations, self.target_spec, self.representative_dataset, graph_def, self._experimental_disable_per_channel, self.experimental_new_dynamic_range_quantizer, self._experimental_low_bit_qat, self._experimental_full_integer_quantization_bias_type, self._experimental_variable_quantization, self._experimental_strict_qdq, ) self._validate_inference_input_output_types(self._quant_mode) if not self._is_unknown_shapes_allowed(): # Checks dimensions in input tensor. for tensor in input_tensors: # Note that shape_list might be empty for scalar shapes. shape_list = tensor.shape.as_list() if None in shape_list[1:]: raise ValueError( "None is only supported in the 1st dimension. Tensor '{0}' has " "invalid shape '{1}'.".format( _get_tensor_name(tensor), shape_list ) ) elif shape_list and shape_list[0] is None: # Set the batch size to 1 if undefined. shape = tensor.shape.as_list() shape[0] = 1 tensor.set_shape(shape) if self._trackable_obj is None or not hasattr( self._trackable_obj, "graph_debug_info" ): self._debug_info = _get_debug_info( _build_debug_info_func(self._funcs[0].graph), graph_def ) else: self._debug_info = _get_debug_info( _convert_debug_info_func(self._trackable_obj.graph_debug_info), graph_def, ) @convert_phase(Component.PREPARE_TF_MODEL, SubComponent.OPTIMIZE_TF_MODEL) def _optimize_tf_model( self, graph_def, input_tensors, output_tensors, frozen_func ): """Run a Grappler pass to optimize the TensorFlow graph. Args: graph_def: Frozen GraphDef to be optimized. input_tensors: List of input tensors. output_tensors: List of output tensors. frozen_func: TensorFlow Graph. Returns: The optimized TensorFlow graph. """ grappler_config = self._grappler_config() # Skip running grappler when there are no optimizers to run. If not, # grappler will run with the default optimizer set and it will lead to # causing an unexpected behavior. if grappler_config.graph_options.rewrite_options.optimizers: graph_def = _run_graph_optimizations( graph_def, input_tensors, output_tensors, config=grappler_config, graph=frozen_func.graph, ) return graph_def def _convert_from_saved_model(self, graph_def): """Helper method that converts saved model. Args: graph_def: GraphDef object for the model, used only for stats. Returns: The converted TFLite model. """ # Update conversion params with graph_def. self._save_conversion_params_metric(graph_def) # Get quantization options and do some sanity checks. quant_mode = QuantizationMode( self.optimizations, self.target_spec, self.representative_dataset, graph_def, self._experimental_disable_per_channel, self.experimental_new_dynamic_range_quantizer, self._experimental_low_bit_qat, self._experimental_full_integer_quantization_bias_type, self._experimental_variable_quantization, self._experimental_strict_qdq, ) self._validate_inference_input_output_types(quant_mode) converter_kwargs = { "enable_tflite_resource_variables": ( self.experimental_enable_resource_variables ) } converter_kwargs.update(self._get_base_converter_args()) converter_kwargs.update(quant_mode.converter_flags()) result = _convert_saved_model(**converter_kwargs) return self._optimize_tflite_model( result, quant_mode, _build_conversion_flags(**converter_kwargs).debug_options, quant_io=self.experimental_new_quantizer, ) def convert(self, graph_def, input_tensors, output_tensors): """Converts a TensorFlow GraphDef based on instance variables. Args: graph_def: Frozen TensorFlow GraphDef. input_tensors: List of input tensors. output_tensors: List of output tensors. Returns: The converted data in serialized format. Raises: ValueError: No concrete function is specified. Multiple concrete functions are specified. Input shape is not specified. Invalid quantization parameters. """ self._validate_inputs(graph_def, input_tensors) converter_kwargs = self._get_base_converter_args() converter_kwargs.update(self._quant_mode.converter_flags()) if not self.experimental_new_converter: logging.warning( "Please consider switching to the new converter by setting " "experimental_new_converter=True. " "The old converter is deprecated." ) else: logging.info( "Using new converter: If you encounter a problem " "please file a bug. You can opt-out " "by setting experimental_new_converter=False" ) # Converts model. result = _convert_graphdef( input_data=graph_def, input_tensors=input_tensors, output_tensors=output_tensors, **converter_kwargs, ) return self._optimize_tflite_model( result, self._quant_mode, _build_conversion_flags(**converter_kwargs).debug_options, quant_io=self.experimental_new_quantizer, )
TFLiteConverterBaseV2
python
huggingface__transformers
src/transformers/models/align/modeling_align.py
{ "start": 12390, "end": 13543 }
class ____(nn.Module): r""" This corresponds to the final phase of each block in the original implementation. """ def __init__( self, config: AlignVisionConfig, in_dim: int, out_dim: int, stride: int, drop_rate: float, id_skip: bool ): super().__init__() self.apply_dropout = stride == 1 and not id_skip self.project_conv = nn.Conv2d( in_channels=in_dim, out_channels=out_dim, kernel_size=1, padding="same", bias=False, ) self.project_bn = nn.BatchNorm2d( num_features=out_dim, eps=config.batch_norm_eps, momentum=config.batch_norm_momentum ) self.dropout = nn.Dropout(p=drop_rate) def forward(self, embeddings: torch.FloatTensor, hidden_states: torch.FloatTensor) -> torch.Tensor: hidden_states = self.project_conv(hidden_states) hidden_states = self.project_bn(hidden_states) if self.apply_dropout: hidden_states = self.dropout(hidden_states) hidden_states = hidden_states + embeddings return hidden_states
AlignVisionFinalBlockLayer
python
facebook__pyre-check
client/commands/infer.py
{ "start": 2749, "end": 3292 }
class ____(json_mixins.CamlCaseAndExcludeJsonMixin, RawAnnotation): parent: Optional[str] = None return_: Optional[str] = dataclasses.field( metadata=dataclasses_json.config(field_name="return"), default=None ) parameters: List[RawParameter] = dataclasses.field(default_factory=list) is_async: bool = dataclasses.field( metadata=dataclasses_json.config(field_name="async"), default=False ) TAnnotation = TypeVar("TAnnotation", bound=RawAnnotation) @dataclasses.dataclass(frozen=True)
RawDefineAnnotation
python
huggingface__transformers
src/transformers/models/internvl/modular_internvl.py
{ "start": 16554, "end": 17384 }
class ____(nn.Module): def __init__(self, config: InternVLConfig): super().__init__() self.layer_norm = nn.LayerNorm(config.vision_config.hidden_size * int(1 / config.downsample_ratio) ** 2) self.linear_1 = nn.Linear( config.vision_config.hidden_size * int(1 / config.downsample_ratio) ** 2, config.text_config.hidden_size ) self.act = ACT2FN[config.projector_hidden_act] self.linear_2 = nn.Linear(config.text_config.hidden_size, config.text_config.hidden_size) def forward(self, image_features): hidden_states = self.layer_norm(image_features) hidden_states = self.linear_1(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.linear_2(hidden_states) return hidden_states
InternVLMultiModalProjector
python
django-haystack__django-haystack
test_haystack/solr_tests/test_solr_backend.py
{ "start": 61152, "end": 61749 }
class ____(TestCase): def setUp(self): super().setUp() self.sb = connections["solr"].get_backend() def test_content_extraction(self): f = open( os.path.join(os.path.dirname(__file__), "content_extraction", "test.pdf"), "rb", ) data = self.sb.extract_file_contents(f) self.assertTrue("haystack" in data["contents"]) self.assertEqual(data["metadata"]["Content-Type"], ["application/pdf"]) self.assertTrue(any(i for i in data["metadata"]["Keywords"] if "SolrCell" in i))
LiveSolrContentExtractionTestCase
python
Textualize__textual
src/textual/cache.py
{ "start": 6526, "end": 9357 }
class ____(Generic[CacheKey, CacheValue]): """A simple cache that discards the first added key when full (First In First Out). This has a lower overhead than LRUCache, but won't manage a working set as efficiently. It is most suitable for a cache with a relatively low maximum size that is not expected to do many lookups. """ __slots__ = [ "_maxsize", "_cache", "hits", "misses", ] def __init__(self, maxsize: int) -> None: """Initialize a FIFOCache. Args: maxsize: Maximum size of cache before discarding items. """ self._maxsize = maxsize self._cache: dict[CacheKey, CacheValue] = {} self.hits = 0 self.misses = 0 def __bool__(self) -> bool: return bool(self._cache) def __len__(self) -> int: return len(self._cache) def __repr__(self) -> str: return ( f"<FIFOCache maxsize={self._maxsize} hits={self.hits} misses={self.misses}>" ) def clear(self) -> None: """Clear the cache.""" self._cache.clear() def keys(self) -> KeysView[CacheKey]: """Get cache keys.""" # Mostly for tests return self._cache.keys() def set(self, key: CacheKey, value: CacheValue) -> None: """Set a value. Args: key: Key. value: Value. """ if key not in self._cache and len(self._cache) >= self._maxsize: for first_key in self._cache: self._cache.pop(first_key) break self._cache[key] = value __setitem__ = set if TYPE_CHECKING: @overload def get(self, key: CacheKey) -> CacheValue | None: ... @overload def get( self, key: CacheKey, default: DefaultValue ) -> CacheValue | DefaultValue: ... def get( self, key: CacheKey, default: DefaultValue | None = None ) -> CacheValue | DefaultValue | None: """Get a value from the cache, or return a default if the key is not present. Args: key: Key default: Default to return if key is not present. Returns: Either the value or a default. """ try: result = self._cache[key] except KeyError: self.misses += 1 return default else: self.hits += 1 return result def __getitem__(self, key: CacheKey) -> CacheValue: try: result = self._cache[key] except KeyError: self.misses += 1 raise KeyError(key) from None else: self.hits += 1 return result def __contains__(self, key: CacheKey) -> bool: return key in self._cache
FIFOCache
python
wandb__wandb
wandb/vendor/pygments/lexers/graphics.py
{ "start": 12431, "end": 19613 }
class ____(RegexLexer): """ For `Gnuplot <http://gnuplot.info/>`_ plotting scripts. .. versionadded:: 0.11 """ name = 'Gnuplot' aliases = ['gnuplot'] filenames = ['*.plot', '*.plt'] mimetypes = ['text/x-gnuplot'] tokens = { 'root': [ include('whitespace'), (_shortened('bi$nd'), Keyword, 'bind'), (_shortened_many('ex$it', 'q$uit'), Keyword, 'quit'), (_shortened('f$it'), Keyword, 'fit'), (r'(if)(\s*)(\()', bygroups(Keyword, Text, Punctuation), 'if'), (r'else\b', Keyword), (_shortened('pa$use'), Keyword, 'pause'), (_shortened_many('p$lot', 'rep$lot', 'sp$lot'), Keyword, 'plot'), (_shortened('sa$ve'), Keyword, 'save'), (_shortened('se$t'), Keyword, ('genericargs', 'optionarg')), (_shortened_many('sh$ow', 'uns$et'), Keyword, ('noargs', 'optionarg')), (_shortened_many('low$er', 'ra$ise', 'ca$ll', 'cd$', 'cl$ear', 'h$elp', '\\?$', 'hi$story', 'l$oad', 'pr$int', 'pwd$', 're$read', 'res$et', 'scr$eendump', 'she$ll', 'sy$stem', 'up$date'), Keyword, 'genericargs'), (_shortened_many('pwd$', 're$read', 'res$et', 'scr$eendump', 'she$ll', 'test$'), Keyword, 'noargs'), ('([a-zA-Z_]\w*)(\s*)(=)', bygroups(Name.Variable, Text, Operator), 'genericargs'), ('([a-zA-Z_]\w*)(\s*\(.*?\)\s*)(=)', bygroups(Name.Function, Text, Operator), 'genericargs'), (r'@[a-zA-Z_]\w*', Name.Constant), # macros (r';', Keyword), ], 'comment': [ (r'[^\\\n]', Comment), (r'\\\n', Comment), (r'\\', Comment), # don't add the newline to the Comment token default('#pop'), ], 'whitespace': [ ('#', Comment, 'comment'), (r'[ \t\v\f]+', Text), ], 'noargs': [ include('whitespace'), # semicolon and newline end the argument list (r';', Punctuation, '#pop'), (r'\n', Text, '#pop'), ], 'dqstring': [ (r'"', String, '#pop'), (r'\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|[0-7]{1,3})', String.Escape), (r'[^\\"\n]+', String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # stray backslash (r'\n', String, '#pop'), # newline ends the string too ], 'sqstring': [ (r"''", String), # escaped single quote (r"'", String, '#pop'), (r"[^\\'\n]+", String), # all other characters (r'\\\n', String), # line continuation (r'\\', String), # normal backslash (r'\n', String, '#pop'), # newline ends the string too ], 'genericargs': [ include('noargs'), (r'"', String, 'dqstring'), (r"'", String, 'sqstring'), (r'(\d+\.\d*|\.\d+|\d+)[eE][+-]?\d+', Number.Float), (r'(\d+\.\d*|\.\d+)', Number.Float), (r'-?\d+', Number.Integer), ('[,.~!%^&*+=|?:<>/-]', Operator), ('[{}()\[\]]', Punctuation), (r'(eq|ne)\b', Operator.Word), (r'([a-zA-Z_]\w*)(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[a-zA-Z_]\w*', Name), (r'@[a-zA-Z_]\w*', Name.Constant), # macros (r'\\\n', Text), ], 'optionarg': [ include('whitespace'), (_shortened_many( "a$ll", "an$gles", "ar$row", "au$toscale", "b$ars", "bor$der", "box$width", "cl$abel", "c$lip", "cn$trparam", "co$ntour", "da$ta", "data$file", "dg$rid3d", "du$mmy", "enc$oding", "dec$imalsign", "fit$", "font$path", "fo$rmat", "fu$nction", "fu$nctions", "g$rid", "hid$den3d", "his$torysize", "is$osamples", "k$ey", "keyt$itle", "la$bel", "li$nestyle", "ls$", "loa$dpath", "loc$ale", "log$scale", "mac$ros", "map$ping", "map$ping3d", "mar$gin", "lmar$gin", "rmar$gin", "tmar$gin", "bmar$gin", "mo$use", "multi$plot", "mxt$ics", "nomxt$ics", "mx2t$ics", "nomx2t$ics", "myt$ics", "nomyt$ics", "my2t$ics", "nomy2t$ics", "mzt$ics", "nomzt$ics", "mcbt$ics", "nomcbt$ics", "of$fsets", "or$igin", "o$utput", "pa$rametric", "pm$3d", "pal$ette", "colorb$ox", "p$lot", "poi$ntsize", "pol$ar", "pr$int", "obj$ect", "sa$mples", "si$ze", "st$yle", "su$rface", "table$", "t$erminal", "termo$ptions", "ti$cs", "ticsc$ale", "ticsl$evel", "timef$mt", "tim$estamp", "tit$le", "v$ariables", "ve$rsion", "vi$ew", "xyp$lane", "xda$ta", "x2da$ta", "yda$ta", "y2da$ta", "zda$ta", "cbda$ta", "xl$abel", "x2l$abel", "yl$abel", "y2l$abel", "zl$abel", "cbl$abel", "xti$cs", "noxti$cs", "x2ti$cs", "nox2ti$cs", "yti$cs", "noyti$cs", "y2ti$cs", "noy2ti$cs", "zti$cs", "nozti$cs", "cbti$cs", "nocbti$cs", "xdti$cs", "noxdti$cs", "x2dti$cs", "nox2dti$cs", "ydti$cs", "noydti$cs", "y2dti$cs", "noy2dti$cs", "zdti$cs", "nozdti$cs", "cbdti$cs", "nocbdti$cs", "xmti$cs", "noxmti$cs", "x2mti$cs", "nox2mti$cs", "ymti$cs", "noymti$cs", "y2mti$cs", "noy2mti$cs", "zmti$cs", "nozmti$cs", "cbmti$cs", "nocbmti$cs", "xr$ange", "x2r$ange", "yr$ange", "y2r$ange", "zr$ange", "cbr$ange", "rr$ange", "tr$ange", "ur$ange", "vr$ange", "xzeroa$xis", "x2zeroa$xis", "yzeroa$xis", "y2zeroa$xis", "zzeroa$xis", "zeroa$xis", "z$ero"), Name.Builtin, '#pop'), ], 'bind': [ ('!', Keyword, '#pop'), (_shortened('all$windows'), Name.Builtin), include('genericargs'), ], 'quit': [ (r'gnuplot\b', Keyword), include('noargs'), ], 'fit': [ (r'via\b', Name.Builtin), include('plot'), ], 'if': [ (r'\)', Punctuation, '#pop'), include('genericargs'), ], 'pause': [ (r'(mouse|any|button1|button2|button3)\b', Name.Builtin), (_shortened('key$press'), Name.Builtin), include('genericargs'), ], 'plot': [ (_shortened_many('ax$es', 'axi$s', 'bin$ary', 'ev$ery', 'i$ndex', 'mat$rix', 's$mooth', 'thru$', 't$itle', 'not$itle', 'u$sing', 'w$ith'), Name.Builtin), include('genericargs'), ], 'save': [ (_shortened_many('f$unctions', 's$et', 't$erminal', 'v$ariables'), Name.Builtin), include('genericargs'), ], }
GnuplotLexer
python
automl__auto-sklearn
test/test_pipeline/components/regression/test_sgd.py
{ "start": 146, "end": 971 }
class ____(BaseRegressionComponentTest): __test__ = True # Values are extremely bad because the invscaling does not drop the # learning rate aggressively enough! res = dict() res["default_boston"] = -1.1811672998629865e28 res["boston_n_calls"] = 6 res["default_boston_iterative"] = res["default_boston"] res["default_boston_sparse"] = -1.1518512489347601e28 res["default_boston_iterative_sparse"] = res["default_boston_sparse"] res["default_diabetes"] = 0.27420813549185374 res["diabetes_n_calls"] = 10 res["default_diabetes_iterative"] = res["default_diabetes"] res["default_diabetes_sparse"] = 0.034801785011824404 res["default_diabetes_iterative_sparse"] = res["default_diabetes_sparse"] sk_mod = sklearn.linear_model.SGDRegressor module = SGD
SGDComponentTest
python
openai__openai-python
src/openai/types/beta/threads/runs/function_tool_call_delta.py
{ "start": 648, "end": 1076 }
class ____(BaseModel): index: int """The index of the tool call in the tool calls array.""" type: Literal["function"] """The type of tool call. This is always going to be `function` for this type of tool call. """ id: Optional[str] = None """The ID of the tool call object.""" function: Optional[Function] = None """The definition of the function that was called."""
FunctionToolCallDelta
python
xlwings__xlwings
xlwings/constants.py
{ "start": 42814, "end": 43038 }
class ____: xlCheckInMajorVersion = 1 # from enum XlCheckInVersionType xlCheckInMinorVersion = 0 # from enum XlCheckInVersionType xlCheckInOverwriteVersion = 2 # from enum XlCheckInVersionType
CheckInVersionType
python
django-import-export__django-import-export
import_export/exceptions.py
{ "start": 204, "end": 319 }
class ____(ImportExportError): """Raised when there is a misconfiguration with a Widget.""" pass
WidgetError
python
pytorch__pytorch
torch/ao/nn/quantized/reference/modules/sparse.py
{ "start": 219, "end": 2250 }
class ____(nn.Embedding, ReferenceQuantizedModule): """A reference quantized Embedding module that fits into the FX Graph Mode Quantization workflow, activation will be floating point Tensor, we will store floating point weight as well in the module, but in forward we'll quantize and dequantize the weight before running the floating point functional embedding operator. """ def __init__( self, num_embeddings: int, embedding_dim: int, padding_idx: int | None = None, max_norm: float | None = None, norm_type: float = 2.0, scale_grad_by_freq: bool = False, sparse: bool = False, _weight: Tensor | None = None, device=None, dtype=None, weight_qparams: dict[str, Any] | None = None, ) -> None: super().__init__( num_embeddings, embedding_dim, padding_idx, max_norm, norm_type, scale_grad_by_freq, sparse, _weight, # pyrefly: ignore [bad-argument-type] device, dtype, ) self._init_weight_qparams(weight_qparams, device) def _get_name(self): return "QuantizedEmbedding(Reference)" def forward(self, input: Tensor) -> Tensor: weight_quant_dequant = self.get_weight() return F.embedding( input, weight_quant_dequant, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse, ) @classmethod def from_float(cls, mod, weight_qparams): return cls( mod.num_embeddings, mod.embedding_dim, mod.padding_idx, mod.max_norm, mod.norm_type, mod.scale_grad_by_freq, mod.sparse, mod.weight, mod.weight.device, mod.weight.dtype, weight_qparams, )
Embedding
python
spack__spack
lib/spack/spack/vendor/jinja2/runtime.py
{ "start": 33180, "end": 33997 }
class ____(Undefined): """An undefined that returns the debug info when printed. >>> foo = DebugUndefined(name='foo') >>> str(foo) '{{ foo }}' >>> not foo True >>> foo + 42 Traceback (most recent call last): ... spack.vendor.jinja2.exceptions.UndefinedError: 'foo' is undefined """ __slots__ = () def __str__(self) -> str: if self._undefined_hint: message = f"undefined value printed: {self._undefined_hint}" elif self._undefined_obj is missing: message = self._undefined_name # type: ignore else: message = ( f"no such element: {object_type_repr(self._undefined_obj)}" f"[{self._undefined_name!r}]" ) return f"{{{{ {message} }}}}"
DebugUndefined
python
huggingface__transformers
src/transformers/models/blip/modeling_blip.py
{ "start": 18931, "end": 19895 }
class ____(nn.Module): """ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`BlipEncoderLayer`]. Args: config (`BlipConfig`): The corresponding vision configuration for the `BlipEncoder`. """ def __init__(self, config: BlipConfig): super().__init__() self.config = config self.layers = nn.ModuleList([BlipEncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False @auto_docstring def forward( self, inputs_embeds, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, BaseModelOutput]: hidden_states = inputs_embeds for encoder_layer in self.layers: hidden_states = encoder_layer( hidden_states, **kwargs, ) return BaseModelOutput(last_hidden_state=hidden_states)
BlipEncoder
python
doocs__leetcode
solution/0800-0899/0837.New 21 Game/Solution.py
{ "start": 0, "end": 367 }
class ____: def new21Game(self, n: int, k: int, maxPts: int) -> float: @cache def dfs(i: int) -> float: if i >= k: return int(i <= n) if i == k - 1: return min(n - k + 1, maxPts) / maxPts return dfs(i + 1) + (dfs(i + 1) - dfs(i + maxPts + 1)) / maxPts return dfs(0)
Solution
python
huggingface__transformers
src/transformers/models/clip/image_processing_clip_fast.py
{ "start": 871, "end": 1407 }
class ____(BaseImageProcessorFast): # To be checked against the slow image processor # None values left after checking can be removed resample = PILImageResampling.BICUBIC image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD size = {"shortest_edge": 224} default_to_square = False crop_size = {"height": 224, "width": 224} do_resize = True do_center_crop = True do_rescale = True do_normalize = True do_convert_rgb = True __all__ = ["CLIPImageProcessorFast"]
CLIPImageProcessorFast
python
encode__starlette
starlette/middleware/trustedhost.py
{ "start": 346, "end": 2219 }
class ____: def __init__( self, app: ASGIApp, allowed_hosts: Sequence[str] | None = None, www_redirect: bool = True, ) -> None: if allowed_hosts is None: allowed_hosts = ["*"] for pattern in allowed_hosts: assert "*" not in pattern[1:], ENFORCE_DOMAIN_WILDCARD if pattern.startswith("*") and pattern != "*": assert pattern.startswith("*."), ENFORCE_DOMAIN_WILDCARD self.app = app self.allowed_hosts = list(allowed_hosts) self.allow_any = "*" in allowed_hosts self.www_redirect = www_redirect async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: if self.allow_any or scope["type"] not in ( "http", "websocket", ): # pragma: no cover await self.app(scope, receive, send) return headers = Headers(scope=scope) host = headers.get("host", "").split(":")[0] is_valid_host = False found_www_redirect = False for pattern in self.allowed_hosts: if host == pattern or (pattern.startswith("*") and host.endswith(pattern[1:])): is_valid_host = True break elif "www." + host == pattern: found_www_redirect = True if is_valid_host: await self.app(scope, receive, send) else: response: Response if found_www_redirect and self.www_redirect: url = URL(scope=scope) redirect_url = url.replace(netloc="www." + url.netloc) response = RedirectResponse(url=str(redirect_url)) else: response = PlainTextResponse("Invalid host header", status_code=400) await response(scope, receive, send)
TrustedHostMiddleware
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/blobstore/api/main.py
{ "start": 2310, "end": 2802 }
class ____(blobstore_handlers.BlobstoreDownloadHandler): def get(self, photo_key): if not blobstore.get(photo_key): self.error(404) else: self.send_blob(photo_key) # [END gae_blobstore_download_handler] app = webapp2.WSGIApplication( [ ("/", PhotoUploadFormHandler), ("/upload_photo", PhotoUploadHandler), ("/view_photo/([^/]+)?", ViewPhotoHandler), ], debug=True, ) # [END gae_blobstore_sample]
ViewPhotoHandler
python
huggingface__transformers
src/transformers/models/seamless_m4t/modeling_seamless_m4t.py
{ "start": 99122, "end": 105674 }
class ____(PreTrainedModel): config: SeamlessM4TConfig main_input_name = "input_embeds" input_modalities = "audio" _no_split_modules = [] def __init__(self, config): super().__init__(config) self.pad_token_id = config.t2u_pad_token_id self.dur_predictor = SeamlessM4TVariancePredictor(config) self.unit_embedding = nn.Embedding(config.unit_hifi_gan_vocab_size, config.unit_embed_dim) self.speaker_embedding = nn.Embedding(config.vocoder_num_spkrs, config.spkr_embed_dim) self.language_embedding = nn.Embedding(config.vocoder_num_langs, config.lang_embed_dim) self.hifi_gan = SeamlessM4THifiGan(config) # Initialize weights and apply final processing self.post_init() def _get_dur_output_lengths(self, input_ids, dur_out): """ Computes the output length after the duration layer. """ unit_lengths = (input_ids != self.pad_token_id).sum(1) # take care of edge cases where no padding or too many padding unit_lengths = torch.clamp(unit_lengths, 0, dur_out.shape[1] - 1) cumulative_dur_out = torch.cumsum(dur_out, dim=1) unit_lengths = cumulative_dur_out.gather(dim=1, index=unit_lengths.unsqueeze(1)).squeeze() return unit_lengths def _get_output_hifigan_lengths(self, input_lengths: Union[torch.LongTensor, int]): """ Computes the output length of the hifigan convolutional layers """ def _conv_out_length(input_length, kernel_size, stride, pad, dilation=1): # 1D convolutional layer output length formula taken # from https://pytorch.org/docs/stable/generated/torch.nn.Conv1d.html return ( torch.div(input_length + 2 * pad - dilation * (kernel_size - 1) - 1, stride, rounding_mode="floor") + 1 ) def _transpose_conv_out_length(input_length, kernel_size, stride, pad, dilation=1): return (input_length - 1) * stride - 2 * pad + dilation * (kernel_size - 1) + 1 # conv_pre input_lengths = _conv_out_length(input_lengths, 7, 1, 3) # upsampler for i, (upsample_rate, kernel_size) in enumerate( zip(self.config.upsample_rates, self.config.upsample_kernel_sizes) ): input_lengths = _transpose_conv_out_length( input_lengths, kernel_size, upsample_rate, (kernel_size - upsample_rate) // 2 ) # resblock for i in range(len(self.config.upsample_rates)): for kernel_size, dilation in zip(self.config.resblock_kernel_sizes, self.config.resblock_dilation_sizes): for dil in dilation: input_lengths = _conv_out_length( input_lengths, kernel_size, 1, (kernel_size - 1) * dil // 2, dilation=dil ) for dil in dilation: input_lengths = _conv_out_length(input_lengths, kernel_size, 1, (kernel_size - 1) // 2, dilation=1) # conv_post input_lengths = _conv_out_length(input_lengths, 7, 1, 3) return input_lengths def forward( self, input_ids: torch.LongTensor, spkr_id: torch.Tensor, lang_id: torch.Tensor ) -> tuple[torch.Tensor]: """ Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`SeamlessM4TTextToUnitForConditionalGeneration`]. [What are input IDs?](../glossary#input-ids) spkr_id (`int`, *optional*): The id of the speaker used for speech synthesis. Must be lower than `config.vocoder_num_spkrs`. tgt_lang (`str`, *optional*): The language id to use as target language for translation. """ hidden_states = self.unit_embedding(input_ids).transpose(1, 2) spkr = self.speaker_embedding(spkr_id).transpose(1, 2) lang = self.language_embedding(lang_id).transpose(1, 2) log_dur_pred = self.dur_predictor(hidden_states.transpose(1, 2)) dur_out = torch.clamp(torch.round(torch.expm1(log_dur_pred)).long(), min=1) # B x C x T if hidden_states.size(0) == 1: hidden_states = torch.repeat_interleave(hidden_states, dur_out.view(-1), dim=2) else: # if batched sample, need to interleave per sample, and pad -> loss of parallelism if hidden_states.shape[0] > 1 and self.training: logger.warning( """`self.training=True` and you use batching. You lose parallelism during the hifigan forward pass because the samples are interleaved.""" ) hidden_states = [ torch.repeat_interleave(hidden_state, duration, dim=-1).transpose(0, 1) for (hidden_state, duration) in zip(hidden_states, dur_out) ] hidden_states = nn.utils.rnn.pad_sequence(hidden_states, batch_first=True).transpose(1, 2) spkr = spkr.repeat(1, 1, hidden_states.shape[-1]) lang = lang.repeat(1, 1, hidden_states.shape[-1]) hidden_states = torch.cat([lang, hidden_states, spkr], dim=1) hidden_states = self.hifi_gan(hidden_states) unit_lengths = self._get_dur_output_lengths(input_ids, dur_out) lengths = self._get_output_hifigan_lengths(unit_lengths) return hidden_states, lengths def apply_weight_norm(self): weight_norm = nn.utils.weight_norm if hasattr(nn.utils.parametrizations, "weight_norm"): weight_norm = nn.utils.parametrizations.weight_norm weight_norm(self.hifi_gan.conv_pre) for layer in self.hifi_gan.upsampler: weight_norm(layer) for layer in self.hifi_gan.resblocks: layer.apply_weight_norm() weight_norm(self.hifi_gan.conv_post) def remove_weight_norm(self): nn.utils.remove_weight_norm(self.hifi_gan.conv_pre) for layer in self.hifi_gan.upsampler: nn.utils.remove_weight_norm(layer) for layer in self.hifi_gan.resblocks: layer.remove_weight_norm() nn.utils.remove_weight_norm(self.hifi_gan.conv_post) ############ WHOLE MODEL related code ################ @auto_docstring( custom_intro=""" The text-to-text SeamlessM4T Model transformer which can be used for T2TT. """ )
SeamlessM4TCodeHifiGan
python
readthedocs__readthedocs.org
readthedocs/redirects/migrations/0007_migrate_to_new_syntax.py
{ "start": 1181, "end": 1395 }
class ____(migrations.Migration): safe = Safe.after_deploy() dependencies = [ ("redirects", "0006_add_new_fields"), ] operations = [ migrations.RunPython(forwards_func), ]
Migration
python
getsentry__sentry
src/sentry/web/frontend/release_webhook.py
{ "start": 720, "end": 4391 }
class ____(View): def verify(self, plugin_id, project_id, token, signature): return constant_time_compare( signature, hmac.new( key=token.encode("utf-8"), msg=(f"{plugin_id}-{project_id}").encode(), digestmod=sha256, ).hexdigest(), ) @method_decorator(csrf_exempt) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def _handle_builtin(self, request: HttpRequest, project): endpoint = f"/projects/{project.organization.slug}/{project.slug}/releases/" try: data = json.loads(request.body) except json.JSONDecodeError as exc: return HttpResponse( status=400, content=json.dumps({"error": str(exc)}), content_type="application/json", ) try: # Ideally the API client would support some kind of god-mode here # as we've already confirmed credentials and simply want to execute # the view code. Instead we hack around it with an ApiKey instance god = ApiKey(organization_id=project.organization_id, scope_list=["project:write"]) resp = client.post(endpoint, data=data, auth=god) except client.ApiError as exc: return HttpResponse( status=exc.status_code, content=json.dumps(exc.body), content_type="application/json", ) return HttpResponse( status=resp.status_code, content=json.dumps(resp.data), content_type="application/json" ) def post(self, request: HttpRequest, plugin_id, project_id, signature) -> HttpResponse: try: project = Project.objects.get_from_cache(id=project_id) except ValueError: return HttpResponse(status=404) except Project.DoesNotExist: logger.warning( "release-webhook.invalid-project", extra={"project_id": project_id, "plugin_id": plugin_id}, ) return HttpResponse(status=404) logger.info( "release-webhook.incoming", extra={"project_id": project_id, "plugin_id": plugin_id} ) token = ProjectOption.objects.get_value(project, "sentry:release-token") if token is None: logger.warning( "release-webhook.missing-token", extra={"project_id": project_id, "plugin_id": plugin_id}, ) return HttpResponse(status=403) if not self.verify(plugin_id, project_id, token, signature): logger.warning( "release-webhook.invalid-signature", extra={"project_id": project_id, "plugin_id": plugin_id}, ) return HttpResponse(status=403) if plugin_id == "builtin": return self._handle_builtin(request, project) plugin = plugins.get(plugin_id) if not plugin.is_enabled(project): logger.warning( "release-webhook.plugin-disabled", extra={"project_id": project_id, "plugin_id": plugin_id}, ) return HttpResponse(status=403) cls = plugin.get_release_hook() hook = cls(project) try: hook.handle(request) except HookValidationError as exc: return HttpResponse( status=400, content=json.dumps({"error": str(exc)}), content_type="application/json", ) return HttpResponse(status=204)
ReleaseWebhookView
python
py-pdf__pypdf
pypdf/annotations/_markup_annotations.py
{ "start": 1529, "end": 2371 }
class ____(MarkupAnnotation): """ A text annotation. Args: rect: array of four integers ``[xLL, yLL, xUR, yUR]`` specifying the clickable rectangular area text: The text that is added to the document open: flags: """ def __init__( self, *, rect: Union[RectangleObject, tuple[float, float, float, float]], text: str, open: bool = False, flags: int = NO_FLAGS, **kwargs: Any, ) -> None: super().__init__(**kwargs) self[NameObject("/Subtype")] = NameObject("/Text") self[NameObject("/Rect")] = RectangleObject(rect) self[NameObject("/Contents")] = TextStringObject(text) self[NameObject("/Open")] = BooleanObject(open) self[NameObject("/Flags")] = NumberObject(flags)
Text
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/overload3.py
{ "start": 140, "end": 970 }
class ____: @overload # This should emit an error because @staticmethod is used inconsistently. def method1(self, x: int) -> int: ... @overload @staticmethod def method1(x: str) -> str: ... def method1(*args: Any, **kwargs: Any) -> Any: return @overload @classmethod # This should emit an error because @classmethod is used inconsistently. def method2(cls, x: str) -> str: ... @overload def method2(self, x: int) -> int: ... def method2(*args: Any, **kwargs: Any) -> Any: return @overload # This should emit an error because @staticmethod is used inconsistently. def method3(self, x: str) -> str: ... @overload def method3(self, x: int) -> int: ... @staticmethod def method3(*args: Any, **kwargs: Any) -> Any: return
A
python
pytorch__pytorch
test/distributed/pipelining/model_registry.py
{ "start": 10311, "end": 11258 }
class ____(torch.nn.Module): def __init__(self, d_hid: int, n_layers: int = 2): super().__init__() self.layers = torch.nn.ModuleList( [MLPModuleWithDw(d_hid) for _ in range(n_layers)] ) # For testing purpose only, this should be defined by user self.split_spec = { f"layers.{i}": SplitPoint.BEGINNING for i in range(1, n_layers) } self.use_custom_logic = False def forward(self, x): for layer in self.layers: x = layer(x) return x def toggle(self): self.use_custom_logic = not self.use_custom_logic for layer in self.layers: layer.toggle() def compute_dW(self): if not self.use_custom_logic: raise RuntimeError("Need to call toggle() to enable custom backward and dW") for i in reversed(range(len(self.layers))): self.layers[i].compute_dW()
MultiMLPWithDw
python
doocs__leetcode
lcof2/剑指 Offer II 104. 排列的数目/Solution.py
{ "start": 0, "end": 294 }
class ____: def combinationSum4(self, nums: List[int], target: int) -> int: dp = [0] * (target + 1) dp[0] = 1 for i in range(1, target + 1): for num in nums: if i >= num: dp[i] += dp[i - num] return dp[-1]
Solution
python
python-visualization__folium
folium/plugins/geocoder.py
{ "start": 190, "end": 3349 }
class ____(JSCSSMixin, MacroElement): """A simple geocoder for Leaflet that by default uses OSM/Nominatim. Please respect the Nominatim usage policy: https://operations.osmfoundation.org/policies/nominatim/ Parameters ---------- collapsed: bool, default False If True, collapses the search box unless hovered/clicked. position: str, default 'topright' Choose from 'topleft', 'topright', 'bottomleft' or 'bottomright'. add_marker: bool, default True If True, adds a marker on the found location. zoom: int, default 11, optional Set zoom level used for displaying the geocode result, note that this only has an effect when add_marker is set to False. Set this to None to preserve the current map zoom level. provider: str, default 'nominatim' Defaults to "nominatim", see https://github.com/perliedman/leaflet-control-geocoder/tree/2.4.0/src/geocoders for other built-in providers. provider_options: dict, default {} For use with specific providers that may require api keys or other parameters. For all options see https://github.com/perliedman/leaflet-control-geocoder """ _template = Template( """ {% macro script(this, kwargs) %} var geocoderOpts_{{ this.get_name() }} = {{ this.options|tojavascript }}; // note: geocoder name should start with lowercase var geocoderName_{{ this.get_name() }} = geocoderOpts_{{ this.get_name() }}["provider"]; var customGeocoder_{{ this.get_name() }} = L.Control.Geocoder[ geocoderName_{{ this.get_name() }} ]( geocoderOpts_{{ this.get_name() }}['providerOptions'] ); geocoderOpts_{{ this.get_name() }}["geocoder"] = customGeocoder_{{ this.get_name() }}; L.Control.geocoder( geocoderOpts_{{ this.get_name() }} ).on('markgeocode', function(e) { var zoom = geocoderOpts_{{ this.get_name() }}['zoom'] || {{ this._parent.get_name() }}.getZoom(); {{ this._parent.get_name() }}.setView(e.geocode.center, zoom); }).addTo({{ this._parent.get_name() }}); {% endmacro %} """ ) default_js = [ ( "Control.Geocoder.js", "https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js", ) ] default_css = [ ( "Control.Geocoder.css", "https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css", ) ] def __init__( self, collapsed: bool = False, position: str = "topright", add_marker: bool = True, zoom: Optional[int] = 11, provider: str = "nominatim", provider_options: dict = {}, **kwargs ): super().__init__() self._name = "Geocoder" self.options = remove_empty( collapsed=collapsed, position=position, default_mark_geocode=add_marker, zoom=zoom, provider=provider, provider_options=provider_options, **kwargs )
Geocoder
python
numba__numba
numba/tests/test_struct_ref.py
{ "start": 11316, "end": 12458 }
class ____(MemoryLeakMixin, TestCase): def test_same_type_assignment(self): @njit def check(x): poly = PolygonStruct(None, None) p_poly = PolygonStruct(None, None) poly.value = x poly.parent = p_poly p_poly.value = x return poly.parent.value x = 11 got = check(x) expect = x self.assertPreciseEqual(got, expect) def test_overload_method(self): @njit def check(x): poly = PolygonStruct(None, None) p_poly = PolygonStruct(None, None) poly.value = x poly.parent = p_poly p_poly.value = x poly.flip() poly.parent.flip() return poly.parent.value x = 3 got = check(x) expect = -x self.assertPreciseEqual(got, expect) def test_overload_attribute(self): @njit def check(): obj = PolygonStruct(5, None) return obj.prop[0] got = check() expect = 5 self.assertPreciseEqual(got, expect)
TestStructRefForwardTyping
python
langchain-ai__langchain
libs/standard-tests/langchain_tests/base.py
{ "start": 24, "end": 2366 }
class ____: """Base class for standard tests.""" def test_no_overrides_DO_NOT_OVERRIDE(self) -> None: # noqa: N802 """Test that no standard tests are overridden.""" # Find path to standard test implementations comparison_class = None def explore_bases(cls: type) -> None: nonlocal comparison_class for base in cls.__bases__: if base.__module__.startswith("langchain_tests."): if comparison_class is None: comparison_class = base else: msg = ( "Multiple standard test base classes found: " f"{comparison_class}, {base}" ) raise ValueError(msg) else: explore_bases(base) explore_bases(self.__class__) assert comparison_class is not None, "No standard test base class found." print(f"Comparing {self.__class__} to {comparison_class}") # noqa: T201 running_tests = {method for method in dir(self) if method.startswith("test_")} base_tests = { method for method in dir(comparison_class) if method.startswith("test_") } deleted_tests = base_tests - running_tests assert not deleted_tests, f"Standard tests deleted: {deleted_tests}" overridden_tests = [ method for method in base_tests if getattr(self.__class__, method) is not getattr(comparison_class, method) ] def is_xfail(method: str) -> bool: m = getattr(self.__class__, method) if not hasattr(m, "pytestmark"): return False marks = m.pytestmark return any( mark.name == "xfail" and mark.kwargs.get("reason") for mark in marks ) overridden_not_xfail = [ method for method in overridden_tests if not is_xfail(method) ] assert not overridden_not_xfail, ( "Standard tests overridden without " f'@pytest.mark.xfail(reason="..."): {overridden_not_xfail}\n' "Note: reason is required to explain why the standard test has an expected " "failure." )
BaseStandardTests
python
protocolbuffers__protobuf
python/google/protobuf/message.py
{ "start": 728, "end": 815 }
class ____(Error): """Exception raised when serializing messages.""" pass
EncodeError
python
fabric__fabric
tests/task.py
{ "start": 3072, "end": 4350 }
class ____: class init: "__init__" def inherits_regular_kwargs(self): t = fabric.Task(_dummy) call = ConnectionCall( task=t, called_as="meh", args=["5"], kwargs={"kwarg": "val"}, init_kwargs={}, # whatever ) assert call.task is t assert call.called_as == "meh" assert call.args == ["5"] assert call.kwargs["kwarg"] == "val" def extends_with_init_kwargs_kwarg(self): call = ConnectionCall( task=fabric.Task(_dummy), init_kwargs={"host": "server", "port": 2222}, ) assert call.init_kwargs["port"] == 2222 class str: "___str__" def includes_init_kwargs_host_value(self): call = ConnectionCall( fabric.Task(body=_dummy), init_kwargs=dict(host="host", user="user"), ) # TODO: worth using some subset of real Connection repr() in here? # For now, just stick with hostname. expected = "<ConnectionCall '_dummy', args: (), kwargs: {}, host='host'>" # noqa assert str(call) == expected
ConnectionCall_
python
google__pytype
pytype/tools/xref/callgraph.py
{ "start": 425, "end": 487 }
class ____: name: str type: Any @dataclasses.dataclass
Param
python
pytorch__pytorch
torch/distributions/poisson.py
{ "start": 324, "end": 2521 }
class ____(ExponentialFamily): r""" Creates a Poisson distribution parameterized by :attr:`rate`, the rate parameter. Samples are nonnegative integers, with a pmf given by .. math:: \mathrm{rate}^k \frac{e^{-\mathrm{rate}}}{k!} Example:: >>> # xdoctest: +SKIP("poisson_cpu not implemented for 'Long'") >>> m = Poisson(torch.tensor([4])) >>> m.sample() tensor([ 3.]) Args: rate (Number, Tensor): the rate parameter """ # pyrefly: ignore [bad-override] arg_constraints = {"rate": constraints.nonnegative} support = constraints.nonnegative_integer @property def mean(self) -> Tensor: return self.rate @property def mode(self) -> Tensor: return self.rate.floor() @property def variance(self) -> Tensor: return self.rate def __init__( self, rate: Union[Tensor, Number], validate_args: Optional[bool] = None, ) -> None: (self.rate,) = broadcast_all(rate) if isinstance(rate, _Number): batch_shape = torch.Size() else: batch_shape = self.rate.size() super().__init__(batch_shape, validate_args=validate_args) def expand(self, batch_shape, _instance=None): new = self._get_checked_instance(Poisson, _instance) batch_shape = torch.Size(batch_shape) new.rate = self.rate.expand(batch_shape) super(Poisson, new).__init__(batch_shape, validate_args=False) new._validate_args = self._validate_args return new def sample(self, sample_shape=torch.Size()): shape = self._extended_shape(sample_shape) with torch.no_grad(): return torch.poisson(self.rate.expand(shape)) def log_prob(self, value): if self._validate_args: self._validate_sample(value) rate, value = broadcast_all(self.rate, value) return value.xlogy(rate) - rate - (value + 1).lgamma() @property def _natural_params(self) -> tuple[Tensor]: return (torch.log(self.rate),) # pyrefly: ignore [bad-override] def _log_normalizer(self, x): return torch.exp(x)
Poisson
python
django-extensions__django-extensions
tests/test_management_command.py
{ "start": 2549, "end": 3202 }
class ____(TestCase): def test_command(self): out = StringIO() call_command("describe_form", "django_extensions.Secret", stdout=out) output = out.getvalue() self.assertIn("class SecretForm(forms.Form):", output) self.assertRegex(output, r"name = forms.CharField\(.*max_length=255") self.assertRegex(output, r"name = forms.CharField\(.*required=False") self.assertRegex(output, r"name = forms.CharField\(.*label=u?'Name'") self.assertRegex(output, r"text = forms.CharField\(.*required=False") self.assertRegex(output, r"text = forms.CharField\(.*label=u?'Text'")
DescribeFormTests
python
python-excel__xlwt
xlwt/Workbook.py
{ "start": 774, "end": 23539 }
class ____(object): """ This is a class representing a workbook and all its contents. When creating Excel files with xlwt, you will normally start by instantiating an object of this class. """ ################################################################# ## Constructor ################################################################# def __init__(self, encoding='ascii', style_compression=0): self.encoding = encoding self.__owner = 'None' self.__country_code = None # 0x07 is Russia :-) self.__wnd_protect = 0 self.__obj_protect = 0 self.__protect = 0 self.__backup_on_save = 0 # for WINDOW1 record self.__hpos_twips = 0x01E0 self.__vpos_twips = 0x005A self.__width_twips = 0x3FCF self.__height_twips = 0x2A4E self.__custom_palette_b8 = None self.__active_sheet = 0 self.__first_tab_index = 0 self.__selected_tabs = 0x01 self.__tab_width_twips = 0x0258 self.__wnd_hidden = 0 self.__wnd_mini = 0 self.__hscroll_visible = 1 self.__vscroll_visible = 1 self.__tabs_visible = 1 self.__styles = Style.StyleCollection(style_compression) self.__dates_1904 = 0 self.__use_cell_values = 1 self.__sst = BIFFRecords.SharedStringTable(self.encoding) self.__worksheets = [] self.__worksheet_idx_from_name = {} self.__sheet_refs = {} self._supbook_xref = {} self._xcall_xref = {} self._ownbook_supbookx = None self._ownbook_supbook_ref = None self._xcall_supbookx = None self._xcall_supbook_ref = None ################################################################# ## Properties, "getters", "setters" ################################################################# def get_style_stats(self): return self.__styles.stats[:] def set_owner(self, value): self.__owner = value def get_owner(self): return self.__owner owner = property(get_owner, set_owner) ################################################################# def set_country_code(self, value): self.__country_code = value def get_country_code(self): return self.__country_code country_code = property(get_country_code, set_country_code) ################################################################# def set_wnd_protect(self, value): self.__wnd_protect = int(value) def get_wnd_protect(self): return bool(self.__wnd_protect) wnd_protect = property(get_wnd_protect, set_wnd_protect) ################################################################# def set_obj_protect(self, value): self.__obj_protect = int(value) def get_obj_protect(self): return bool(self.__obj_protect) obj_protect = property(get_obj_protect, set_obj_protect) ################################################################# def set_protect(self, value): self.__protect = int(value) def get_protect(self): return bool(self.__protect) protect = property(get_protect, set_protect) ################################################################# def set_backup_on_save(self, value): self.__backup_on_save = int(value) def get_backup_on_save(self): return bool(self.__backup_on_save) backup_on_save = property(get_backup_on_save, set_backup_on_save) ################################################################# def set_hpos(self, value): self.__hpos_twips = value & 0xFFFF def get_hpos(self): return self.__hpos_twips hpos = property(get_hpos, set_hpos) ################################################################# def set_vpos(self, value): self.__vpos_twips = value & 0xFFFF def get_vpos(self): return self.__vpos_twips vpos = property(get_vpos, set_vpos) ################################################################# def set_width(self, value): self.__width_twips = value & 0xFFFF def get_width(self): return self.__width_twips width = property(get_width, set_width) ################################################################# def set_height(self, value): self.__height_twips = value & 0xFFFF def get_height(self): return self.__height_twips height = property(get_height, set_height) ################################################################# def set_active_sheet(self, value): self.__active_sheet = value & 0xFFFF self.__first_tab_index = self.__active_sheet def get_active_sheet(self): return self.__active_sheet active_sheet = property(get_active_sheet, set_active_sheet) ################################################################# def set_tab_width(self, value): self.__tab_width_twips = value & 0xFFFF def get_tab_width(self): return self.__tab_width_twips tab_width = property(get_tab_width, set_tab_width) ################################################################# def set_wnd_visible(self, value): self.__wnd_hidden = int(not value) def get_wnd_visible(self): return not bool(self.__wnd_hidden) wnd_visible = property(get_wnd_visible, set_wnd_visible) ################################################################# def set_wnd_mini(self, value): self.__wnd_mini = int(value) def get_wnd_mini(self): return bool(self.__wnd_mini) wnd_mini = property(get_wnd_mini, set_wnd_mini) ################################################################# def set_hscroll_visible(self, value): self.__hscroll_visible = int(value) def get_hscroll_visible(self): return bool(self.__hscroll_visible) hscroll_visible = property(get_hscroll_visible, set_hscroll_visible) ################################################################# def set_vscroll_visible(self, value): self.__vscroll_visible = int(value) def get_vscroll_visible(self): return bool(self.__vscroll_visible) vscroll_visible = property(get_vscroll_visible, set_vscroll_visible) ################################################################# def set_tabs_visible(self, value): self.__tabs_visible = int(value) def get_tabs_visible(self): return bool(self.__tabs_visible) tabs_visible = property(get_tabs_visible, set_tabs_visible) ################################################################# def set_dates_1904(self, value): self.__dates_1904 = int(value) def get_dates_1904(self): return bool(self.__dates_1904) dates_1904 = property(get_dates_1904, set_dates_1904) ################################################################# def set_use_cell_values(self, value): self.__use_cell_values = int(value) def get_use_cell_values(self): return bool(self.__use_cell_values) use_cell_values = property(get_use_cell_values, set_use_cell_values) ################################################################# def get_default_style(self): return self.__styles.default_style default_style = property(get_default_style) ################################################################# def set_colour_RGB(self, colour_index, red, green, blue): if not(8 <= colour_index <= 63): raise Exception("set_colour_RGB: colour_index (%d) not in range(8, 64)" % colour_index) if min(red, green, blue) < 0 or max(red, green, blue) > 255: raise Exception("set_colour_RGB: colour values (%d,%d,%d) must be in range(0, 256)" % (red, green, blue)) if self.__custom_palette_b8 is None: self.__custom_palette_b8 = list(Style.excel_default_palette_b8) # User-defined Palette starts at colour index 8, # so subtract 8 from colour_index when placing in palette palette_index = colour_index - 8 self.__custom_palette_b8[palette_index] = red << 24 | green << 16 | blue << 8 ################################################################## ## Methods ################################################################## def add_style(self, style): return self.__styles.add(style) def add_font(self, font): return self.__styles.add_font(font) def add_str(self, s): return self.__sst.add_str(s) def del_str(self, sst_idx): self.__sst.del_str(sst_idx) def str_index(self, s): return self.__sst.str_index(s) def add_rt(self, rt): return self.__sst.add_rt(rt) def rt_index(self, rt): return self.__sst.rt_index(rt) def add_sheet(self, sheetname, cell_overwrite_ok=False): """ This method is used to create Worksheets in a Workbook. :param sheetname: The name to use for this sheet, as it will appear in the tabs at the bottom of the Excel application. :param cell_overwrite_ok: If ``True``, cells in the added worksheet will not raise an exception if written to more than once. :return: The :class:`~xlwt.Worksheet.Worksheet` that was added. """ from . import Utils from .Worksheet import Worksheet if not isinstance(sheetname, six.text_type): sheetname = sheetname.decode(self.encoding) if not Utils.valid_sheet_name(sheetname): raise Exception("invalid worksheet name %r" % sheetname) lower_name = sheetname.lower() if lower_name in self.__worksheet_idx_from_name: raise Exception("duplicate worksheet name %r" % sheetname) self.__worksheet_idx_from_name[lower_name] = len(self.__worksheets) self.__worksheets.append(Worksheet(sheetname, self, cell_overwrite_ok)) return self.__worksheets[-1] def get_sheet(self, sheet): if isinstance(sheet, six.integer_types): return self.__worksheets[sheet] elif isinstance(sheet, six.string_types): sheetnum = self.sheet_index(sheet) return self.__worksheets[sheetnum] else: raise Exception("sheet must be integer or string") def sheet_index(self, sheetname): try: sheetnum = self.__worksheet_idx_from_name[sheetname.lower()] except KeyError: self.raise_bad_sheetname(sheetname) return sheetnum def raise_bad_sheetname(self, sheetname): raise Exception("Formula: unknown sheet name %s" % sheetname) def convert_sheetindex(self, strg_ref, n_sheets): idx = int(strg_ref) if 0 <= idx < n_sheets: return idx msg = "Formula: sheet index (%s) >= number of sheets (%d)" % (strg_ref, n_sheets) raise Exception(msg) def _get_supbook_index(self, tag): if tag in self._supbook_xref: return self._supbook_xref[tag] self._supbook_xref[tag] = idx = len(self._supbook_xref) return idx def setup_ownbook(self): self._ownbook_supbookx = self._get_supbook_index(('ownbook', 0)) self._ownbook_supbook_ref = None reference = (self._ownbook_supbookx, 0xFFFE, 0xFFFE) if reference in self.__sheet_refs: raise Exception("can't happen") self.__sheet_refs[reference] = self._ownbook_supbook_ref = len(self.__sheet_refs) def setup_xcall(self): self._xcall_supbookx = self._get_supbook_index(('xcall', 0)) self._xcall_supbook_ref = None reference = (self._xcall_supbookx, 0xFFFE, 0xFFFE) if reference in self.__sheet_refs: raise Exception("can't happen") self.__sheet_refs[reference] = self._xcall_supbook_ref = len(self.__sheet_refs) def add_sheet_reference(self, formula): patches = [] n_sheets = len(self.__worksheets) sheet_refs, xcall_refs = formula.get_references() for ref0, ref1, offset in sheet_refs: if not ref0.isdigit(): try: ref0n = self.__worksheet_idx_from_name[ref0.lower()] except KeyError: self.raise_bad_sheetname(ref0) else: ref0n = self.convert_sheetindex(ref0, n_sheets) if ref1 == ref0: ref1n = ref0n elif not ref1.isdigit(): try: ref1n = self.__worksheet_idx_from_name[ref1.lower()] except KeyError: self.raise_bad_sheetname(ref1) else: ref1n = self.convert_sheetindex(ref1, n_sheets) if ref1n < ref0n: msg = "Formula: sheets out of order; %r:%r -> (%d, %d)" \ % (ref0, ref1, ref0n, ref1n) raise Exception(msg) if self._ownbook_supbookx is None: self.setup_ownbook() reference = (self._ownbook_supbookx, ref0n, ref1n) if reference in self.__sheet_refs: patches.append((offset, self.__sheet_refs[reference])) else: nrefs = len(self.__sheet_refs) if nrefs > 65535: raise Exception('More than 65536 inter-sheet references') self.__sheet_refs[reference] = nrefs patches.append((offset, nrefs)) for funcname, offset in xcall_refs: if self._ownbook_supbookx is None: self.setup_ownbook() if self._xcall_supbookx is None: self.setup_xcall() # print funcname, self._supbook_xref patches.append((offset, self._xcall_supbook_ref)) if not isinstance(funcname, six.text_type): funcname = funcname.decode(self.encoding) if funcname in self._xcall_xref: idx = self._xcall_xref[funcname] else: self._xcall_xref[funcname] = idx = len(self._xcall_xref) patches.append((offset + 2, idx + 1)) formula.patch_references(patches) ################################################################## ## BIFF records generation ################################################################## def __bof_rec(self): return BIFFRecords.Biff8BOFRecord(BIFFRecords.Biff8BOFRecord.BOOK_GLOBAL).get() def __eof_rec(self): return BIFFRecords.EOFRecord().get() def __intf_hdr_rec(self): return BIFFRecords.InteraceHdrRecord().get() def __intf_end_rec(self): return BIFFRecords.InteraceEndRecord().get() def __intf_mms_rec(self): return BIFFRecords.MMSRecord().get() def __write_access_rec(self): return BIFFRecords.WriteAccessRecord(self.__owner).get() def __wnd_protect_rec(self): return BIFFRecords.WindowProtectRecord(self.__wnd_protect).get() def __obj_protect_rec(self): return BIFFRecords.ObjectProtectRecord(self.__obj_protect).get() def __protect_rec(self): return BIFFRecords.ProtectRecord(self.__protect).get() def __password_rec(self): return BIFFRecords.PasswordRecord().get() def __prot4rev_rec(self): return BIFFRecords.Prot4RevRecord().get() def __prot4rev_pass_rec(self): return BIFFRecords.Prot4RevPassRecord().get() def __backup_rec(self): return BIFFRecords.BackupRecord(self.__backup_on_save).get() def __hide_obj_rec(self): return BIFFRecords.HideObjRecord().get() def __window1_rec(self): flags = 0 flags |= (self.__wnd_hidden) << 0 flags |= (self.__wnd_mini) << 1 flags |= (self.__hscroll_visible) << 3 flags |= (self.__vscroll_visible) << 4 flags |= (self.__tabs_visible) << 5 return BIFFRecords.Window1Record(self.__hpos_twips, self.__vpos_twips, self.__width_twips, self.__height_twips, flags, self.__active_sheet, self.__first_tab_index, self.__selected_tabs, self.__tab_width_twips).get() def __codepage_rec(self): return BIFFRecords.CodepageBiff8Record().get() def __country_rec(self): if not self.__country_code: return b'' return BIFFRecords.CountryRecord(self.__country_code, self.__country_code).get() def __dsf_rec(self): return BIFFRecords.DSFRecord().get() def __tabid_rec(self): return BIFFRecords.TabIDRecord(len(self.__worksheets)).get() def __fngroupcount_rec(self): return BIFFRecords.FnGroupCountRecord().get() def __datemode_rec(self): return BIFFRecords.DateModeRecord(self.__dates_1904).get() def __precision_rec(self): return BIFFRecords.PrecisionRecord(self.__use_cell_values).get() def __refresh_all_rec(self): return BIFFRecords.RefreshAllRecord().get() def __bookbool_rec(self): return BIFFRecords.BookBoolRecord().get() def __all_fonts_num_formats_xf_styles_rec(self): return self.__styles.get_biff_data() def __palette_rec(self): if self.__custom_palette_b8 is None: return b'' info = BIFFRecords.PaletteRecord(self.__custom_palette_b8).get() return info def __useselfs_rec(self): return BIFFRecords.UseSelfsRecord().get() def __boundsheets_rec(self, data_len_before, data_len_after, sheet_biff_lens): # ................................. # BOUNDSEHEET0 # BOUNDSEHEET1 # BOUNDSEHEET2 # .................................. # WORKSHEET0 # WORKSHEET1 # WORKSHEET2 boundsheets_len = 0 for sheet in self.__worksheets: boundsheets_len += len(BIFFRecords.BoundSheetRecord( 0x00, sheet.visibility, sheet.name, self.encoding ).get()) start = data_len_before + boundsheets_len + data_len_after result = b'' for sheet_biff_len, sheet in zip(sheet_biff_lens, self.__worksheets): result += BIFFRecords.BoundSheetRecord( start, sheet.visibility, sheet.name, self.encoding ).get() start += sheet_biff_len return result def __all_links_rec(self): pieces = [] temp = [(idx, tag) for tag, idx in self._supbook_xref.items()] temp.sort() for idx, tag in temp: stype, snum = tag if stype == 'ownbook': rec = BIFFRecords.InternalReferenceSupBookRecord(len(self.__worksheets)).get() pieces.append(rec) elif stype == 'xcall': rec = BIFFRecords.XcallSupBookRecord().get() pieces.append(rec) temp = [(idx, name) for name, idx in self._xcall_xref.items()] temp.sort() for idx, name in temp: rec = BIFFRecords.ExternnameRecord( options=0, index=0, name=name, fmla='\x02\x00\x1c\x17').get() pieces.append(rec) else: raise Exception('unknown supbook stype %r' % stype) if len(self.__sheet_refs) > 0: # get references in index order temp = [(idx, ref) for ref, idx in self.__sheet_refs.items()] temp.sort() temp = [ref for idx, ref in temp] externsheet_record = BIFFRecords.ExternSheetRecord(temp).get() pieces.append(externsheet_record) return b''.join(pieces) def __sst_rec(self): return self.__sst.get_biff_record() def __ext_sst_rec(self, abs_stream_pos): return b'' #return BIFFRecords.ExtSSTRecord(abs_stream_pos, self.sst_record.str_placement, #self.sst_record.portions_len).get() def get_biff_data(self): before = b'' before += self.__bof_rec() before += self.__intf_hdr_rec() before += self.__intf_mms_rec() before += self.__intf_end_rec() before += self.__write_access_rec() before += self.__codepage_rec() before += self.__dsf_rec() before += self.__tabid_rec() before += self.__fngroupcount_rec() before += self.__wnd_protect_rec() before += self.__protect_rec() before += self.__obj_protect_rec() before += self.__password_rec() before += self.__prot4rev_rec() before += self.__prot4rev_pass_rec() before += self.__backup_rec() before += self.__hide_obj_rec() before += self.__window1_rec() before += self.__datemode_rec() before += self.__precision_rec() before += self.__refresh_all_rec() before += self.__bookbool_rec() before += self.__all_fonts_num_formats_xf_styles_rec() before += self.__palette_rec() before += self.__useselfs_rec() country = self.__country_rec() all_links = self.__all_links_rec() shared_str_table = self.__sst_rec() after = country + all_links + shared_str_table ext_sst = self.__ext_sst_rec(0) # need fake cause we need calc stream pos eof = self.__eof_rec() self.__worksheets[self.__active_sheet].selected = True sheets = b'' sheet_biff_lens = [] for sheet in self.__worksheets: data = sheet.get_biff_data() sheets += data sheet_biff_lens.append(len(data)) bundlesheets = self.__boundsheets_rec(len(before), len(after)+len(ext_sst)+len(eof), sheet_biff_lens) sst_stream_pos = len(before) + len(bundlesheets) + len(country) + len(all_links) ext_sst = self.__ext_sst_rec(sst_stream_pos) return before + bundlesheets + after + ext_sst + eof + sheets def save(self, filename_or_stream): """ This method is used to save the Workbook to a file in native Excel format. :param filename_or_stream: This can be a string containing a filename of the file, in which case the excel file is saved to disk using the name provided. It can also be a stream object with a write method, such as a :class:`~io.StringIO`, in which case the data for the excel file is written to the stream. """ from . import CompoundDoc doc = CompoundDoc.XlsDoc() doc.save(filename_or_stream, self.get_biff_data())
Workbook
python
pyparsing__pyparsing
examples/bf.py
{ "start": 3061, "end": 3182 }
class ____(Instruction): def execute(self, bf_engine: BFEngine): bf_engine.output_value_at_ptr()
OutputPtrValue
python
doocs__leetcode
solution/2600-2699/2617.Minimum Number of Visited Cells in a Grid/Solution.py
{ "start": 0, "end": 980 }
class ____: def minimumVisitedCells(self, grid: List[List[int]]) -> int: m, n = len(grid), len(grid[0]) dist = [[-1] * n for _ in range(m)] dist[0][0] = 1 row = [[] for _ in range(m)] col = [[] for _ in range(n)] for i in range(m): for j in range(n): while row[i] and grid[i][row[i][0][1]] + row[i][0][1] < j: heappop(row[i]) if row[i] and (dist[i][j] == -1 or dist[i][j] > row[i][0][0] + 1): dist[i][j] = row[i][0][0] + 1 while col[j] and grid[col[j][0][1]][j] + col[j][0][1] < i: heappop(col[j]) if col[j] and (dist[i][j] == -1 or dist[i][j] > col[j][0][0] + 1): dist[i][j] = col[j][0][0] + 1 if dist[i][j] != -1: heappush(row[i], (dist[i][j], j)) heappush(col[j], (dist[i][j], i)) return dist[-1][-1]
Solution
python
wandb__wandb
wandb/vendor/pygments/scanner.py
{ "start": 693, "end": 3123 }
class ____(object): """ Simple scanner All method patterns are regular expression strings (not compiled expressions!) """ def __init__(self, text, flags=0): """ :param text: The text which should be scanned :param flags: default regular expression flags """ self.data = text self.data_length = len(text) self.start_pos = 0 self.pos = 0 self.flags = flags self.last = None self.match = None self._re_cache = {} def eos(self): """`True` if the scanner reached the end of text.""" return self.pos >= self.data_length eos = property(eos, eos.__doc__) def check(self, pattern): """ Apply `pattern` on the current position and return the match object. (Doesn't touch pos). Use this for lookahead. """ if self.eos: raise EndOfText() if pattern not in self._re_cache: self._re_cache[pattern] = re.compile(pattern, self.flags) return self._re_cache[pattern].match(self.data, self.pos) def test(self, pattern): """Apply a pattern on the current position and check if it patches. Doesn't touch pos. """ return self.check(pattern) is not None def scan(self, pattern): """ Scan the text for the given pattern and update pos/match and related fields. The return value is a boolen that indicates if the pattern matched. The matched value is stored on the instance as ``match``, the last value is stored as ``last``. ``start_pos`` is the position of the pointer before the pattern was matched, ``pos`` is the end position. """ if self.eos: raise EndOfText() if pattern not in self._re_cache: self._re_cache[pattern] = re.compile(pattern, self.flags) self.last = self.match m = self._re_cache[pattern].match(self.data, self.pos) if m is None: return False self.start_pos = m.start() self.pos = m.end() self.match = m.group() return True def get_char(self): """Scan exactly one char.""" self.scan('.') def __repr__(self): return '<%s %d/%d>' % ( self.__class__.__name__, self.pos, self.data_length )
Scanner
python
huggingface__transformers
tests/models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py
{ "start": 14556, "end": 16706 }
class ____(VisionTextDualEncoderMixin, unittest.TestCase): def get_pretrained_model_and_inputs(self): model = VisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-clip", "hf-internal-testing/tiny-bert" ) batch_size = 13 pixel_values = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) input_ids = ids_tensor([batch_size, 4], model.text_model.config.vocab_size) attention_mask = random_attention_mask([batch_size, 4]) inputs = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def get_vision_text_model(self, vision_config, text_config): vision_model = CLIPVisionModel(vision_config).eval() text_model = BertModel(text_config).eval() return vision_model, text_model def prepare_config_and_inputs(self): clip_model_tester = CLIPVisionModelTester(self) bert_model_tester = BertModelTester(self) vision_config_and_inputs = clip_model_tester.prepare_config_and_inputs() text_config_and_inputs = bert_model_tester.prepare_config_and_inputs() vision_config, pixel_values = vision_config_and_inputs ( text_config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, ) = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_torch
CLIPVisionBertModelTest
python
pytorch__pytorch
test/dynamo/test_model_output.py
{ "start": 890, "end": 1871 }
class ____(torch._dynamo.test_case.TestCase): @maybe_skip def test_pretrained(self): def fn(a, tmp): if hasattr(tmp, "somekey"): a = a + 1 if tmp.return_dict: return a + torch.ones(2) * tmp.max_length return a x = torch.randn(2) tmp = PretrainedConfig(return_dict=True, max_length=20) ref = fn(x, tmp) opt_fn = torch.compile(fn, backend="eager", fullgraph=True) res = opt_fn(x, tmp) self.assertTrue(same(ref, res)) @maybe_skip def test_pretrained_non_const_attr(self): def fn(a, tmp): if tmp.pruned_heads: return a + 1 else: return a - 1 x = torch.randn(2) tmp = PretrainedConfig() ref = fn(x, tmp) opt_fn = torch.compile(backend="eager", fullgraph=True)(fn) res = opt_fn(x, tmp) self.assertTrue(same(ref, res))
TestHFPretrained
python
ray-project__ray
doc/source/ray-overview/examples/mcp-ray-serve/mcp-gateway-with-existing-ray-apps/image_classifier.py
{ "start": 671, "end": 1318 }
class ____: def __init__(self, downloader: DeploymentHandle): from transformers import pipeline self.downloader = downloader self.model = pipeline( "image-classification", model="google/vit-base-patch16-224" ) async def classify(self, image_url: str) -> str: image = await self.downloader.remote(image_url) results = self.model(image) return results[0]["label"] async def __call__(self, req: starlette.requests.Request): req = await req.json() return await self.classify(req["image_url"]) app = ImageClassifier.bind(downloader.bind())
ImageClassifier
python
eth-brownie__brownie
brownie/typing.py
{ "start": 4680, "end": 4851 }
class ____(_InputJsonBase, total=False): language: Literal["Vyper"] settings: SettingsVyper InputJson = InputJsonSolc | InputJsonVyper Count = int
InputJsonVyper
python
kubernetes-client__python
kubernetes/client/models/v1_managed_fields_entry.py
{ "start": 383, "end": 10901 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'api_version': 'str', 'fields_type': 'str', 'fields_v1': 'object', 'manager': 'str', 'operation': 'str', 'subresource': 'str', 'time': 'datetime' } attribute_map = { 'api_version': 'apiVersion', 'fields_type': 'fieldsType', 'fields_v1': 'fieldsV1', 'manager': 'manager', 'operation': 'operation', 'subresource': 'subresource', 'time': 'time' } def __init__(self, api_version=None, fields_type=None, fields_v1=None, manager=None, operation=None, subresource=None, time=None, local_vars_configuration=None): # noqa: E501 """V1ManagedFieldsEntry - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._api_version = None self._fields_type = None self._fields_v1 = None self._manager = None self._operation = None self._subresource = None self._time = None self.discriminator = None if api_version is not None: self.api_version = api_version if fields_type is not None: self.fields_type = fields_type if fields_v1 is not None: self.fields_v1 = fields_v1 if manager is not None: self.manager = manager if operation is not None: self.operation = operation if subresource is not None: self.subresource = subresource if time is not None: self.time = time @property def api_version(self): """Gets the api_version of this V1ManagedFieldsEntry. # noqa: E501 APIVersion defines the version of this resource that this field set applies to. The format is \"group/version\" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted. # noqa: E501 :return: The api_version of this V1ManagedFieldsEntry. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1ManagedFieldsEntry. APIVersion defines the version of this resource that this field set applies to. The format is \"group/version\" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted. # noqa: E501 :param api_version: The api_version of this V1ManagedFieldsEntry. # noqa: E501 :type: str """ self._api_version = api_version @property def fields_type(self): """Gets the fields_type of this V1ManagedFieldsEntry. # noqa: E501 FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: \"FieldsV1\" # noqa: E501 :return: The fields_type of this V1ManagedFieldsEntry. # noqa: E501 :rtype: str """ return self._fields_type @fields_type.setter def fields_type(self, fields_type): """Sets the fields_type of this V1ManagedFieldsEntry. FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: \"FieldsV1\" # noqa: E501 :param fields_type: The fields_type of this V1ManagedFieldsEntry. # noqa: E501 :type: str """ self._fields_type = fields_type @property def fields_v1(self): """Gets the fields_v1 of this V1ManagedFieldsEntry. # noqa: E501 FieldsV1 holds the first JSON version format as described in the \"FieldsV1\" type. # noqa: E501 :return: The fields_v1 of this V1ManagedFieldsEntry. # noqa: E501 :rtype: object """ return self._fields_v1 @fields_v1.setter def fields_v1(self, fields_v1): """Sets the fields_v1 of this V1ManagedFieldsEntry. FieldsV1 holds the first JSON version format as described in the \"FieldsV1\" type. # noqa: E501 :param fields_v1: The fields_v1 of this V1ManagedFieldsEntry. # noqa: E501 :type: object """ self._fields_v1 = fields_v1 @property def manager(self): """Gets the manager of this V1ManagedFieldsEntry. # noqa: E501 Manager is an identifier of the workflow managing these fields. # noqa: E501 :return: The manager of this V1ManagedFieldsEntry. # noqa: E501 :rtype: str """ return self._manager @manager.setter def manager(self, manager): """Sets the manager of this V1ManagedFieldsEntry. Manager is an identifier of the workflow managing these fields. # noqa: E501 :param manager: The manager of this V1ManagedFieldsEntry. # noqa: E501 :type: str """ self._manager = manager @property def operation(self): """Gets the operation of this V1ManagedFieldsEntry. # noqa: E501 Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. # noqa: E501 :return: The operation of this V1ManagedFieldsEntry. # noqa: E501 :rtype: str """ return self._operation @operation.setter def operation(self, operation): """Sets the operation of this V1ManagedFieldsEntry. Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'. # noqa: E501 :param operation: The operation of this V1ManagedFieldsEntry. # noqa: E501 :type: str """ self._operation = operation @property def subresource(self): """Gets the subresource of this V1ManagedFieldsEntry. # noqa: E501 Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource. # noqa: E501 :return: The subresource of this V1ManagedFieldsEntry. # noqa: E501 :rtype: str """ return self._subresource @subresource.setter def subresource(self, subresource): """Sets the subresource of this V1ManagedFieldsEntry. Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource. # noqa: E501 :param subresource: The subresource of this V1ManagedFieldsEntry. # noqa: E501 :type: str """ self._subresource = subresource @property def time(self): """Gets the time of this V1ManagedFieldsEntry. # noqa: E501 Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over. # noqa: E501 :return: The time of this V1ManagedFieldsEntry. # noqa: E501 :rtype: datetime """ return self._time @time.setter def time(self, time): """Sets the time of this V1ManagedFieldsEntry. Time is the timestamp of when the ManagedFields entry was added. The timestamp will also be updated if a field is added, the manager changes any of the owned fields value or removes a field. The timestamp does not update when a field is removed from the entry because another manager took it over. # noqa: E501 :param time: The time of this V1ManagedFieldsEntry. # noqa: E501 :type: datetime """ self._time = time def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1ManagedFieldsEntry): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1ManagedFieldsEntry): return True return self.to_dict() != other.to_dict()
V1ManagedFieldsEntry
python
django-compressor__django-compressor
compressor/parser/base.py
{ "start": 0, "end": 1046 }
class ____: """ Base parser to be subclassed when creating an own parser. """ def __init__(self, content): self.content = content def css_elems(self): """ Return an iterable containing the css elements to handle """ raise NotImplementedError def js_elems(self): """ Return an iterable containing the js elements to handle """ raise NotImplementedError def elem_attribs(self, elem): """ Return the dictionary like attribute store of the given element """ raise NotImplementedError def elem_content(self, elem): """ Return the content of the given element """ raise NotImplementedError def elem_name(self, elem): """ Return the name of the given element """ raise NotImplementedError def elem_str(self, elem): """ Return the string representation of the given elem """ raise NotImplementedError
ParserBase
python
ethereum__web3.py
web3/types.py
{ "start": 9882, "end": 10102 }
class ____(TypedDict): address: ChecksumAddress accountProof: Sequence[HexStr] balance: int codeHash: HexBytes nonce: Nonce storageHash: HexBytes storageProof: Sequence[StorageProof]
MerkleProof
python
coleifer__peewee
tests/models.py
{ "start": 170460, "end": 171587 }
class ____(ModelTestCase): requires = [Datum] def test_null_ordering(self): values = [('k1', 1), ('ka', None), ('k2', 2), ('kb', None)] Datum.insert_many(values, fields=[Datum.key, Datum.value]).execute() def assertOrder(ordering, expected): query = Datum.select().order_by(*ordering) self.assertEqual([d.key for d in query], expected) # Ascending order. nulls_last = (Datum.value.asc(nulls='last'), Datum.key) assertOrder(nulls_last, ['k1', 'k2', 'ka', 'kb']) nulls_first = (Datum.value.asc(nulls='first'), Datum.key) assertOrder(nulls_first, ['ka', 'kb', 'k1', 'k2']) # Descending order. nulls_last = (Datum.value.desc(nulls='last'), Datum.key) assertOrder(nulls_last, ['k2', 'k1', 'ka', 'kb']) nulls_first = (Datum.value.desc(nulls='first'), Datum.key) assertOrder(nulls_first, ['ka', 'kb', 'k2', 'k1']) # Invalid values. self.assertRaises(ValueError, Datum.value.desc, nulls='bar') self.assertRaises(ValueError, Datum.value.asc, nulls='foo')
TestNullOrdering
python
Lightning-AI__lightning
src/lightning/fabric/utilities/spike.py
{ "start": 317, "end": 7289 }
class ____: """Spike Detection Callback. Terminates training with a ``TrainingSpikeException`` when a loss-spike was detected and saves the batches to skip when resuming to a file. We skip the current and the previous batch since it is unclear whether the previous batch altered the weights in a way that it causes the spike or just the current batch is corrupted somehow. Args: mode: Whether to minimize or maximize the tracked metric window: A running mean of metrics with ``window`` size. Serves as reference value for spikes. warmup: After how many batches spike-tracking should start atol: An absolute tolerance. Every diff between the running mean and the current value, that's not an improvement and above ``atol`` will be considered a spike rtol: A relative tolerance. Every diff between the running mean and the current value, that's higher than ``rtol * running_mean`` is considered a spike exclude_batches_path: Where to save the file that contains the batches to exclude. Will default to current directory. finite_only: If set to ``False``, consider non-finite values like NaN, inf and -inf a spike as well. """ def __init__( self, mode: Literal["min", "max"] = "min", window: int = 10, warmup: int = 1, atol: Optional[float] = None, rtol: Optional[float] = 2.0, exclude_batches_path: Optional[_PATH] = None, finite_only: bool = True, ): if _TORCHMETRICS_GREATER_EQUAL_1_0_0: from torchmetrics.aggregation import MeanMetric from torchmetrics.wrappers import Running else: raise RuntimeError("SpikeDetection requires `torchmetrics>=1.0.0` Please upgrade your version.") super().__init__() self.last_val: Union[torch.Tensor, float] = 0.0 # spike detection happens individually on each machine self.running_mean = Running(MeanMetric(dist_sync_on_step=False, sync_on_compute=False), window=window) # workaround for https://github.com/Lightning-AI/torchmetrics/issues/1899 self.running_mean.dist_sync_on_step = False self.running_mean.sync_on_compute = False self.mode = mode self.warmup = warmup self.atol = atol self.rtol = rtol self.bad_batches: list[int] = [] self.exclude_batches_path = exclude_batches_path self.finite_only = finite_only @torch.no_grad() def on_train_batch_end(self, fabric: "Fabric", loss: torch.Tensor, batch: Any, batch_idx: int) -> None: """Checks if we currently have a loss-spike.""" if batch_idx == 0: self.running_mean.to(fabric.strategy.root_device) if self.exclude_batches_path is None: self.exclude_batches_path = os.getcwd() if not str(self.exclude_batches_path).endswith(".json"): self.exclude_batches_path = os.path.join(self.exclude_batches_path, "skip_batches.json") is_spike = bool(batch_idx >= self.warmup and self._is_spike(loss)) fabric.strategy.barrier() # While spike-detection happens on a per-rank level, we need to fail all ranks if any rank detected a spike is_spike_global = fabric.strategy.reduce_boolean_decision(is_spike, all=False) if is_spike_global: self._handle_spike(fabric, batch_idx) else: is_finite_all = self.finite_only or fabric.strategy.reduce_boolean_decision( bool(torch.isfinite(loss).all()), all=True ) if is_finite_all: self._update_stats(loss) def _is_spike(self, loss: torch.Tensor) -> bool: # we might call compute more often than update which is fine as long as the # metric has at least one internal value. with warnings.catch_warnings(): warnings.simplefilter("ignore") running_val = self.running_mean.compute() curr_diff = loss - self.last_val if self.finite_only and not torch.isfinite(loss): return True if self._is_better(curr_diff): return False return self._check_atol(loss, running_val) and self._check_rtol(loss, running_val) def _handle_spike(self, fabric: "Fabric", batch_idx: int) -> None: # Exclude current and last batch # Current batch is excluded since it could be that the data of this batch produces a high loss # Last batch is excluded since the previous batch could have "corrupted" the weights self.bad_batches.extend([batch_idx - 1, batch_idx]) if fabric.global_rank == 0: assert self.exclude_batches_path is not None os.makedirs(os.path.dirname(self.exclude_batches_path), exist_ok=True) with open(self.exclude_batches_path, "w") as f: json.dump(self.bad_batches, f, indent=4) raise TrainingSpikeException(batch_idx=batch_idx) def _check_atol(self, val_a: Union[float, torch.Tensor], val_b: Union[float, torch.Tensor]) -> bool: return (self.atol is None) or bool(abs(val_a - val_b) >= abs(self.atol)) def _check_rtol(self, val_a: Union[float, torch.Tensor], val_b: Union[float, torch.Tensor]) -> bool: return (self.rtol is None) or bool(abs(val_a - val_b) >= abs(self.rtol * val_b)) def _is_better(self, diff_val: torch.Tensor) -> bool: if self.mode == "min": return bool((diff_val <= 0.0).all()) if self.mode == "max": return bool((diff_val >= 0).all()) raise ValueError(f"Invalid mode. Has to be min or max, found {self.mode}") def _update_stats(self, val: torch.Tensor) -> None: # only update if finite self.running_mean.update(val) self.last_val = val def state_dict(self) -> dict[str, Any]: return { "last_val": self.last_val.item() if isinstance(self.last_val, torch.Tensor) else self.last_val, "mode": self.mode, "warmup": self.warmup, "atol": self.atol, "rtol": self.rtol, "bad_batches": self.bad_batches, "bad_batches_path": self.exclude_batches_path, "running": self.running_mean.state_dict(), "mean": self.running_mean.base_metric.state_dict(), } def load_state_dict(self, state_dict: dict[str, Any]) -> None: self.last_val = state_dict.pop("last_val") self.mode = state_dict.pop("mode") self.warmup = state_dict.pop("warmup") self.atol = state_dict.pop("atol") self.rtol = state_dict.pop("rtol") self.bad_batches = state_dict.pop("bad_batches") self.exclude_batches_path = state_dict.pop("bad_batches_path") self.running.load_state_dict(state_dict.pop("running")) self.running_mean.base_metric.load_state_dict(state_dict.pop("mean"))
SpikeDetection
python
openai__openai-python
src/openai/resources/beta/realtime/realtime.py
{ "start": 22110, "end": 23137 }
class ____(BaseRealtimeConnectionResource): def update(self, *, session: session_update_event_param.Session, event_id: str | NotGiven = NOT_GIVEN) -> None: """ Send this event to update the session’s default configuration. The client may send this event at any time to update any field, except for `voice`. However, note that once a session has been initialized with a particular `model`, it can’t be changed to another model using `session.update`. When the server receives a `session.update`, it will respond with a `session.updated` event showing the full, effective configuration. Only the fields that are present are updated. To clear a field like `instructions`, pass an empty string. """ self._connection.send( cast( RealtimeClientEventParam, strip_not_given({"type": "session.update", "session": session, "event_id": event_id}), ) )
RealtimeSessionResource
python
django__django
tests/model_fields/test_imagefield.py
{ "start": 13171, "end": 17434 }
class ____(ImageFieldTestMixin, TestCase): """ Tests a model with two ImageFields. """ PersonModel = PersonTwoImages def test_constructor(self): p = self.PersonModel(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") p.save() self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") def test_create(self): p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8) self.check_dimensions(p, 8, 4, "headshot") def test_assignment(self): p = self.PersonModel() self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, None, None, "headshot") p.mugshot = self.file1 self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, None, None, "headshot") p.headshot = self.file2 self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # Clear the ImageFields one at a time. p.mugshot = None self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, 8, 4, "headshot") p.headshot = None self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, None, None, "headshot") def test_field_save_and_delete_methods(self): p = self.PersonModel(name="Joe") p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, None, None, "headshot") p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # We can use save=True when deleting the image field with null=True # dimension fields and the other field has an image. p.headshot.delete(save=True) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, None, None, "headshot") p.mugshot.delete(save=False) self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, None, None, "headshot") def test_dimensions(self): """ Dimensions are updated correctly in various situations. """ p = self.PersonModel(name="Joe") # Dimensions should get set for the saved file. p.mugshot.save("mug", self.file1) p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name="Joe") # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertIs(p.mugshot.was_opened, False) self.assertIs(p.headshot.was_opened, False) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # After checking dimensions on the image fields, the files will # have been opened. self.assertIs(p.mugshot.was_opened, True) self.assertIs(p.headshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False p.headshot.was_opened = False self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") self.assertIs(p.mugshot.was_opened, False) self.assertIs(p.headshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 p.headshot = self.file1 self.check_dimensions(p, 8, 4, "mugshot") self.check_dimensions(p, 4, 8, "headshot") # Dimensions were recalculated, and hence file should have opened. self.assertIs(p.mugshot.was_opened, True) self.assertIs(p.headshot.was_opened, True) @skipIf(Image is None, "Pillow is required to test ImageField")
TwoImageFieldTests
python
TheAlgorithms__Python
data_structures/binary_tree/binary_search_tree.py
{ "start": 2193, "end": 2978 }
class ____: value: int left: Node | None = None right: Node | None = None parent: Node | None = None # Added in order to delete a node easier def __iter__(self) -> Iterator[int]: """ >>> list(Node(0)) [0] >>> list(Node(0, Node(-1), Node(1), None)) [-1, 0, 1] """ yield from self.left or [] yield self.value yield from self.right or [] def __repr__(self) -> str: from pprint import pformat if self.left is None and self.right is None: return str(self.value) return pformat({f"{self.value}": (self.left, self.right)}, indent=1) @property def is_right(self) -> bool: return bool(self.parent and self is self.parent.right) @dataclass
Node
python
PyCQA__pyflakes
pyflakes/test/test_type_annotations.py
{ "start": 176, "end": 21034 }
class ____(TestCase): def test_typingOverload(self): """Allow intentional redefinitions via @typing.overload""" self.flakes(""" import typing from typing import overload @overload def f(s: None) -> None: pass @overload def f(s: int) -> int: pass def f(s): return s @typing.overload def g(s: None) -> None: pass @typing.overload def g(s: int) -> int: pass def g(s): return s """) def test_typingExtensionsOverload(self): """Allow intentional redefinitions via @typing_extensions.overload""" self.flakes(""" import typing_extensions from typing_extensions import overload @overload def f(s: None) -> None: pass @overload def f(s: int) -> int: pass def f(s): return s @typing_extensions.overload def g(s: None) -> None: pass @typing_extensions.overload def g(s: int) -> int: pass def g(s): return s """) def test_typingOverloadAsync(self): """Allow intentional redefinitions via @typing.overload (async)""" self.flakes(""" from typing import overload @overload async def f(s: None) -> None: pass @overload async def f(s: int) -> int: pass async def f(s): return s """) def test_overload_with_multiple_decorators(self): self.flakes(""" from typing import overload dec = lambda f: f @dec @overload def f(x: int) -> int: pass @dec @overload def f(x: str) -> str: pass @dec def f(x): return x """) def test_overload_in_class(self): self.flakes(""" from typing import overload class C: @overload def f(self, x: int) -> int: pass @overload def f(self, x: str) -> str: pass def f(self, x): return x """) def test_aliased_import(self): """Detect when typing is imported as another name""" self.flakes(""" import typing as t @t.overload def f(s: None) -> None: pass @t.overload def f(s: int) -> int: pass def f(s): return s """) def test_not_a_typing_overload(self): """regression test for @typing.overload detection bug in 2.1.0""" self.flakes(""" def foo(x): return x @foo def bar(): pass def bar(): pass """, m.RedefinedWhileUnused) def test_variable_annotations(self): def undefined_names_before_py314(*, n: int): return (m.UndefinedName,) * n if version_info < (3, 14) else () self.flakes(''' name: str age: int ''') self.flakes(''' name: str = 'Bob' age: int = 18 ''') self.flakes(''' class C: name: str age: int ''') self.flakes(''' class C: name: str = 'Bob' age: int = 18 ''') self.flakes(''' def f(): name: str age: int ''', m.UnusedAnnotation, m.UnusedAnnotation) self.flakes(''' def f(): name: str = 'Bob' age: int = 18 foo: not_a_real_type = None ''', m.UnusedVariable, m.UnusedVariable, m.UnusedVariable, m.UndefinedName) self.flakes(''' def f(): name: str print(name) ''', m.UndefinedName) self.flakes(''' from typing import Any def f(): a: Any ''', m.UnusedAnnotation) self.flakes(''' foo: not_a_real_type ''', m.UndefinedName) self.flakes(''' foo: not_a_real_type = None ''', m.UndefinedName) self.flakes(''' class C: foo: not_a_real_type ''', m.UndefinedName) self.flakes(''' class C: foo: not_a_real_type = None ''', m.UndefinedName) self.flakes(''' def f(): class C: foo: not_a_real_type ''', m.UndefinedName) self.flakes(''' def f(): class C: foo: not_a_real_type = None ''', m.UndefinedName) self.flakes(''' from foo import Bar bar: Bar ''') self.flakes(''' from foo import Bar bar: 'Bar' ''') self.flakes(''' import foo bar: foo.Bar ''') self.flakes(''' import foo bar: 'foo.Bar' ''') self.flakes(''' from foo import Bar def f(bar: Bar): pass ''') self.flakes(''' from foo import Bar def f(bar: 'Bar'): pass ''') self.flakes(''' from foo import Bar def f(bar) -> Bar: return bar ''') self.flakes(''' from foo import Bar def f(bar) -> 'Bar': return bar ''') self.flakes(''' bar: 'Bar' ''', m.UndefinedName) self.flakes(''' bar: 'foo.Bar' ''', m.UndefinedName) self.flakes(''' from foo import Bar bar: str ''', m.UnusedImport) self.flakes(''' from foo import Bar def f(bar: str): pass ''', m.UnusedImport) self.flakes(''' def f(a: A) -> A: pass class A: pass ''', *undefined_names_before_py314(n=2)) self.flakes(''' def f(a: 'A') -> 'A': return a class A: pass ''') self.flakes(''' a: A class A: pass ''', *undefined_names_before_py314(n=1)) self.flakes(''' a: 'A' class A: pass ''') self.flakes(''' T: object def f(t: T): pass ''', *undefined_names_before_py314(n=1)) self.flakes(''' T: object def g(t: 'T'): pass ''') self.flakes(''' a: 'A B' ''', m.ForwardAnnotationSyntaxError) self.flakes(''' a: 'A; B' ''', m.ForwardAnnotationSyntaxError) self.flakes(''' a: '1 + 2' ''') self.flakes(''' a: 'a: "A"' ''', m.ForwardAnnotationSyntaxError) def test_variable_annotation_references_self_name_undefined(self): self.flakes(""" x: int = x """, m.UndefinedName) def test_TypeAlias_annotations(self): self.flakes(""" from typing_extensions import TypeAlias from foo import Bar bar: TypeAlias = Bar """) self.flakes(""" from typing_extensions import TypeAlias from foo import Bar bar: TypeAlias = 'Bar' """) self.flakes(""" from typing_extensions import TypeAlias from foo import Bar class A: bar: TypeAlias = Bar """) self.flakes(""" from typing_extensions import TypeAlias from foo import Bar class A: bar: TypeAlias = 'Bar' """) self.flakes(""" from typing_extensions import TypeAlias bar: TypeAlias """) self.flakes(""" from typing_extensions import TypeAlias from foo import Bar bar: TypeAlias """, m.UnusedImport) def test_annotating_an_import(self): self.flakes(''' from a import b, c b: c print(b) ''') def test_unused_annotation(self): # Unused annotations are fine in module and class scope self.flakes(''' x: int class Cls: y: int ''') self.flakes(''' def f(): x: int ''', m.UnusedAnnotation) # This should only print one UnusedVariable message self.flakes(''' def f(): x: int x = 3 ''', m.UnusedVariable) def test_unused_annotation_in_outer_scope_reassigned_in_local_scope(self): self.flakes(''' x: int x.__dict__ def f(): x = 1 ''', m.UndefinedName, m.UnusedVariable) def test_unassigned_annotation_is_undefined(self): self.flakes(''' name: str print(name) ''', m.UndefinedName) def test_annotated_async_def(self): self.flakes(''' class c: pass async def func(c: c) -> None: pass ''') def test_postponed_annotations(self): self.flakes(''' from __future__ import annotations def f(a: A) -> A: pass class A: b: B class B: pass ''') self.flakes(''' from __future__ import annotations def f(a: A) -> A: pass class A: b: Undefined class B: pass ''', m.UndefinedName) self.flakes(''' from __future__ import annotations T: object def f(t: T): pass def g(t: 'T'): pass ''') def test_annotations_do_not_define_names_with_future_annotations(self): self.flakes(''' from __future__ import annotations def f(): x: str print(x) ''', m.UndefinedName) @skipIf(version_info < (3, 14), 'new in Python 3.14') def test_postponed_annotations_py314(self): self.flakes(''' def f(x: C) -> None: pass class C: pass ''') def test_type_annotation_clobbers_all(self): self.flakes('''\ from typing import TYPE_CHECKING, List from y import z if not TYPE_CHECKING: __all__ = ("z",) else: __all__: List[str] ''') def test_return_annotation_is_class_scope_variable(self): self.flakes(""" from typing import TypeVar class Test: Y = TypeVar('Y') def t(self, x: Y) -> Y: return x """) def test_return_annotation_is_function_body_variable(self): self.flakes(""" class Test: def t(self) -> Y: Y = 2 return Y """, m.UndefinedName) def test_positional_only_argument_annotations(self): self.flakes(""" from x import C def f(c: C, /): ... """) def test_partially_quoted_type_annotation(self): self.flakes(""" from queue import Queue from typing import Optional def f() -> Optional['Queue[str]']: return None """) def test_partially_quoted_type_assignment(self): self.flakes(""" from queue import Queue from typing import Optional MaybeQueue = Optional['Queue[str]'] """) def test_nested_partially_quoted_type_assignment(self): self.flakes(""" from queue import Queue from typing import Callable Func = Callable[['Queue[str]'], None] """) def test_quoted_type_cast(self): self.flakes(""" from typing import cast, Optional maybe_int = cast('Optional[int]', 42) """) def test_type_cast_literal_str_to_str(self): # Checks that our handling of quoted type annotations in the first # argument to `cast` doesn't cause issues when (only) the _second_ # argument is a literal str which looks a bit like a type annotation. self.flakes(""" from typing import cast a_string = cast(str, 'Optional[int]') """) def test_quoted_type_cast_renamed_import(self): self.flakes(""" from typing import cast as tsac, Optional as Maybe maybe_int = tsac('Maybe[int]', 42) """) def test_quoted_TypeVar_constraints(self): self.flakes(""" from typing import TypeVar, Optional T = TypeVar('T', 'str', 'Optional[int]', bytes) """) def test_quoted_TypeVar_bound(self): self.flakes(""" from typing import TypeVar, Optional, List T = TypeVar('T', bound='Optional[int]') S = TypeVar('S', int, bound='List[int]') """) def test_literal_type_typing(self): self.flakes(""" from typing import Literal def f(x: Literal['some string']) -> None: return None """) def test_literal_type_typing_extensions(self): self.flakes(""" from typing_extensions import Literal def f(x: Literal['some string']) -> None: return None """) def test_annotated_type_typing_missing_forward_type(self): self.flakes(""" from typing import Annotated def f(x: Annotated['integer']) -> None: return None """, m.UndefinedName) def test_annotated_type_typing_missing_forward_type_multiple_args(self): self.flakes(""" from typing import Annotated def f(x: Annotated['integer', 1]) -> None: return None """, m.UndefinedName) def test_annotated_type_typing_with_string_args(self): self.flakes(""" from typing import Annotated def f(x: Annotated[int, '> 0']) -> None: return None """) def test_annotated_type_typing_with_string_args_in_union(self): self.flakes(""" from typing import Annotated, Union def f(x: Union[Annotated['int', '>0'], 'integer']) -> None: return None """, m.UndefinedName) def test_literal_type_some_other_module(self): """err on the side of false-negatives for types named Literal""" self.flakes(""" from my_module import compat from my_module.compat import Literal def f(x: compat.Literal['some string']) -> None: return None def g(x: Literal['some string']) -> None: return None """) def test_literal_union_type_typing(self): self.flakes(""" from typing import Literal def f(x: Literal['some string', 'foo bar']) -> None: return None """) def test_deferred_twice_annotation(self): self.flakes(""" from queue import Queue from typing import Optional def f() -> "Optional['Queue[str]']": return None """) def test_partial_string_annotations_with_future_annotations(self): self.flakes(""" from __future__ import annotations from queue import Queue from typing import Optional def f() -> Optional['Queue[str]']: return None """) def test_forward_annotations_for_classes_in_scope(self): # see #749 self.flakes(""" from typing import Optional def f(): class C: a: "D" b: Optional["D"] c: "Optional[D]" class D: pass """) def test_idomiatic_typing_guards(self): # typing.TYPE_CHECKING: python3.5.3+ self.flakes(""" from typing import TYPE_CHECKING if TYPE_CHECKING: from t import T def f() -> T: pass """) # False: the old, more-compatible approach self.flakes(""" if False: from t import T def f() -> T: pass """) # some choose to assign a constant and do it that way self.flakes(""" MYPY = False if MYPY: from t import T def f() -> T: pass """) def test_typing_guard_for_protocol(self): self.flakes(""" from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Protocol else: Protocol = object class C(Protocol): def f() -> int: pass """) def test_typednames_correct_forward_ref(self): self.flakes(""" from typing import TypedDict, List, NamedTuple List[TypedDict("x", {})] List[TypedDict("x", x=int)] List[NamedTuple("a", a=int)] List[NamedTuple("a", [("a", int)])] """) self.flakes(""" from typing import TypedDict, List, NamedTuple, TypeVar List[TypedDict("x", {"x": "Y"})] List[TypedDict("x", x="Y")] List[NamedTuple("a", [("a", "Y")])] List[NamedTuple("a", a="Y")] List[TypedDict("x", {"x": List["a"]})] List[TypeVar("A", bound="C")] List[TypeVar("A", List["C"])] """, *[m.UndefinedName]*7) self.flakes(""" from typing import NamedTuple, TypeVar, cast from t import A, B, C, D, E NamedTuple("A", [("a", A["C"])]) TypeVar("A", bound=A["B"]) TypeVar("A", A["D"]) cast(A["E"], []) """) def test_namedtypes_classes(self): self.flakes(""" from typing import TypedDict, NamedTuple class X(TypedDict): y: TypedDict("z", {"zz":int}) class Y(NamedTuple): y: NamedTuple("v", [("vv", int)]) """) @skipIf(version_info < (3, 11), 'new in Python 3.11') def test_variadic_generics(self): self.flakes(""" from typing import Generic from typing import TypeVarTuple Ts = TypeVarTuple('Ts') class Shape(Generic[*Ts]): pass def f(*args: *Ts) -> None: ... def g(x: Shape[*Ts]) -> Shape[*Ts]: ... """) @skipIf(version_info < (3, 12), 'new in Python 3.12') def test_type_statements(self): self.flakes(""" type ListOrSet[T] = list[T] | set[T] def f(x: ListOrSet[str]) -> None: ... type RecursiveType = int | list[RecursiveType] type ForwardRef = int | C type ForwardRefInBounds[T: C] = T class C: pass """) @skipIf(version_info < (3, 12), 'new in Python 3.12') def test_type_parameters_functions(self): self.flakes(""" def f[T](t: T) -> T: return t async def g[T](t: T) -> T: return t def with_forward_ref[T: C](t: T) -> T: return t def can_access_inside[T](t: T) -> T: print(T) return t class C: pass """) @skipIf(version_info < (3, 12), 'new in Python 3.12') def test_type_parameters_do_not_escape_function_scopes(self): self.flakes(""" from x import g @g(T) # not accessible in decorators def f[T](t: T) -> T: return t T # not accessible afterwards """, m.UndefinedName, m.UndefinedName) @skipIf(version_info < (3, 12), 'new in Python 3.12') def test_type_parameters_classes(self): self.flakes(""" class C[T](list[T]): pass class UsesForward[T: Forward](list[T]): pass class Forward: pass class WithinBody[T](list[T]): t = T """) @skipIf(version_info < (3, 12), 'new in Python 3.12') def test_type_parameters_do_not_escape_class_scopes(self): self.flakes(""" from x import g @g(T) # not accessible in decorators class C[T](list[T]): pass T # not accessible afterwards """, m.UndefinedName, m.UndefinedName) @skipIf(version_info < (3, 12), 'new in Python 3.12') def test_type_parameters_TypeVarTuple(self): self.flakes(""" def f[*T](*args: *T) -> None: ... """) @skipIf(version_info < (3, 12), 'new in Python 3.12') def test_type_parameters_ParamSpec(self): self.flakes(""" from typing import Callable def f[R, **P](f: Callable[P, R]) -> Callable[P, R]: def g(*args: P.args, **kwargs: P.kwargs) -> R: return f(*args, **kwargs) return g """) @skipIf(version_info < (3, 13), 'new in Python 3.13') def test_type_parameter_defaults(self): self.flakes(""" def f[T = int](u: T) -> T: return u """)
TestTypeAnnotations
python
marshmallow-code__marshmallow
tests/test_serialization.py
{ "start": 518, "end": 594 }
class ____: def __init__(self, ints): self.ints = ints
IntegerList
python
pytorch__pytorch
torch/_inductor/ir.py
{ "start": 244724, "end": 245197 }
class ____(TMADescriptor): """ the new host-side TMA descriptor API (the ones obtained via TensorDescriptor.from_tensor). See also TMADescriptorExperimental for the old API. """ def __init__(self, tensor: IRNode, block_shape: list[Union[int, torch.SymInt]]): self.block_shape = block_shape super().__init__( tensor=tensor, inputs=[tensor], constant_args=block_shape, )
TMADescriptorStable
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 31541, "end": 31833 }
class ____(StringEnum): created = "created" queued = "queued" in_progress = "in_progress" stopped = "stopped" published = "published" publishing = "publishing" closed = "closed" failed = "failed" completed = "completed" unknown = "unknown"
TaskStatusEnum
python
ray-project__ray
rllib/examples/envs/classes/action_mask_env.py
{ "start": 136, "end": 1490 }
class ____(RandomEnv): """A randomly acting environment that publishes an action-mask each step.""" def __init__(self, config): super().__init__(config) # Masking only works for Discrete actions. assert isinstance(self.action_space, Discrete) # Add action_mask to observations. self.observation_space = Dict( { "action_mask": Box(0.0, 1.0, shape=(self.action_space.n,)), "observations": self.observation_space, } ) self.valid_actions = None def reset(self, *, seed=None, options=None): obs, info = super().reset() self._fix_action_mask(obs) return obs, info def step(self, action): # Check whether action is valid. if not self.valid_actions[action]: raise ValueError( f"Invalid action ({action}) sent to env! " f"valid_actions={self.valid_actions}" ) obs, rew, done, truncated, info = super().step(action) self._fix_action_mask(obs) return obs, rew, done, truncated, info def _fix_action_mask(self, obs): # Fix action-mask: Everything larger 0.5 is 1.0, everything else 0.0. self.valid_actions = np.round(obs["action_mask"]) obs["action_mask"] = self.valid_actions
ActionMaskEnv
python
pytest-dev__pytest-xdist
src/xdist/dsession.py
{ "start": 17108, "end": 17462 }
class ____(Enum): """Status of each worker during creation/collection.""" # Worker spec has just been created. Created = auto() # Worker has been initialized. Initialized = auto() # Worker is now ready for collection. ReadyForCollection = auto() # Worker has finished collection. CollectionDone = auto()
WorkerStatus
python
pypa__pipenv
pipenv/vendor/plette/pipfiles.py
{ "start": 558, "end": 4817 }
class ____(DataModel): """Representation of a Pipfile. """ __SCHEMA__ = {} @classmethod def validate(cls, data): # HACK: DO NOT CALL `super().validate()` here!! # Cerberus seems to break TOML Kit's inline table preservation if it # is not at the top-level. Fortunately the spec doesn't have nested # non-inlined tables, so we're OK as long as validation is only # performed at section-level. validation is performed. for key, klass in PIPFILE_SECTIONS.items(): if key not in data: continue klass.validate(data[key]) package_categories = set(data.keys()) - set(PIPFILE_SECTIONS.keys()) for category in package_categories: PackageCollection.validate(data[category]) @classmethod def load(cls, f, encoding=None): content = f.read() if encoding is not None: content = content.decode(encoding) data = tomlkit.loads(content) if "source" not in data: # HACK: There is no good way to prepend a section to an existing # TOML document, but there's no good way to copy non-structural # content from one TOML document to another either. Modify the # TOML content directly, and load the new in-memory document. sep = "" if content.startswith("\n") else "\n" content = DEFAULT_SOURCE_TOML + sep + content data = tomlkit.loads(content) return cls(data) def __getitem__(self, key): value = self._data[key] try: return PIPFILE_SECTIONS[key](value) except KeyError: return value def __setitem__(self, key, value): if isinstance(value, DataModel): self._data[key] = value._data else: self._data[key] = value def get_hash(self): data = { "_meta": { "sources": self._data["source"], "requires": self._data.get("requires", {}), }, "default": self._data.get("packages", {}), "develop": self._data.get("dev-packages", {}), } for category, values in self._data.items(): if category in PIPFILE_SECTIONS or category in ("default", "develop", "pipenv"): continue data[category] = values content = json.dumps(data, sort_keys=True, separators=(",", ":")) if isinstance(content, str): content = content.encode("utf-8") return Hash.from_hash(hashlib.sha256(content)) def dump(self, f, encoding=None): content = tomlkit.dumps(self._data) if encoding is not None: content = content.encode(encoding) f.write(content) @property def sources(self): try: return self["source"] except KeyError: raise AttributeError("sources") @sources.setter def sources(self, value): self["source"] = value @property def source(self): try: return self["source"] except KeyError: raise AttributeError("source") @source.setter def source(self, value): self["source"] = value @property def packages(self): try: return self["packages"] except KeyError: raise AttributeError("packages") @packages.setter def packages(self, value): self["packages"] = value @property def dev_packages(self): try: return self["dev-packages"] except KeyError: raise AttributeError("dev-packages") @dev_packages.setter def dev_packages(self, value): self["dev-packages"] = value @property def requires(self): try: return self["requires"] except KeyError: raise AttributeError("requires") @requires.setter def requires(self, value): self["requires"] = value @property def scripts(self): try: return self["scripts"] except KeyError: raise AttributeError("scripts") @scripts.setter def scripts(self, value): self["scripts"] = value
Pipfile
python
getsentry__sentry
src/sentry/workflow_engine/typings/notification_action.py
{ "start": 14186, "end": 15353 }
class ____(BaseActionTranslator, TicketingActionDataBlobHelper, ABC): @property def required_fields(self) -> list[str]: return [ ACTION_FIELD_MAPPINGS[self.action_type][ActionFieldMappingKeys.INTEGRATION_ID_KEY.value] ] @property def integration_id(self) -> Any | None: return self.action.get("integration") @property def target_type(self) -> int: return ActionTarget.SPECIFIC.value @property def blob_type(self) -> type[DataBlob]: return TicketDataBlob def get_sanitized_data(self) -> dict[str, Any]: """ Override to handle custom fields and additional fields that aren't part of the standard fields. """ # Use helper to separate fields, excluding required fields dynamic_form_fields, additional_fields = self.separate_fields( self.action, excluded_keys=self.required_fields ) data = { TicketFieldMappingKeys.DYNAMIC_FORM_FIELDS_KEY.value: dynamic_form_fields, TicketFieldMappingKeys.ADDITIONAL_FIELDS_KEY.value: additional_fields, } return data
TicketActionTranslator