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
donnemartin__interactive-coding-challenges
graphs_trees/graph_bfs/test_bfs.py
{ "start": 18, "end": 820 }
class ____(unittest.TestCase): def __init__(self, *args, **kwargs): super(TestBfs, self).__init__() self.results = Results() def test_bfs(self): nodes = [] graph = GraphBfs() for id in range(0, 6): nodes.append(graph.add_node(id)) graph.add_edge(0, 1, 5) graph.add_edge(0, 4, 3) graph.add_edge(0, 5, 2) graph.add_edge(1, 3, 5) graph.add_edge(1, 4, 4) graph.add_edge(2, 1, 6) graph.add_edge(3, 2, 7) graph.add_edge(3, 4, 8) graph.bfs(nodes[0], self.results.add_result) self.assertEqual(str(self.results), "[0, 1, 4, 5, 3, 2]") print('Success: test_bfs') def main(): test = TestBfs() test.test_bfs() if __name__ == '__main__': main()
TestBfs
python
getsentry__sentry
src/sentry/issues/grouptype.py
{ "start": 4969, "end": 5189 }
class ____: ignore_limit: int = DEFAULT_IGNORE_LIMIT expiry_time: timedelta = DEFAULT_EXPIRY_TIME @property def expiry_seconds(self) -> int: return int(self.expiry_time.total_seconds())
NoiseConfig
python
numba__numba
numba/core/typing/mathdecl.py
{ "start": 2592, "end": 2834 }
class ____(ConcreteTemplate): cases = [ signature(types.float64, types.float64, types.float64), signature(types.float32, types.float32, types.float32), ] @infer_global(math.isinf) @infer_global(math.isnan)
Math_nextafter
python
huggingface__transformers
tests/models/convnext/test_image_processing_convnext.py
{ "start": 1016, "end": 2818 }
class ____: def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, crop_pct=0.875, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5], ): size = size if size is not None else {"shortest_edge": 20} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.crop_pct = crop_pct self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std def prepare_image_processor_dict(self): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "crop_pct": self.crop_pct, } def expected_output_image_shape(self, images): return self.num_channels, self.size["shortest_edge"], self.size["shortest_edge"] def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision
ConvNextImageProcessingTester
python
redis__redis-py
redis/cluster.py
{ "start": 59909, "end": 60066 }
class ____(Enum): ROUND_ROBIN = "round_robin" ROUND_ROBIN_REPLICAS = "round_robin_replicas" RANDOM_REPLICA = "random_replica"
LoadBalancingStrategy
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 13101, "end": 15190 }
class ____(NonStrictDataModel): """ :param version: Version id of a version belonging to the dataset :type version: str :param dataset: Existing Dataset id :type dataset: str :param merge_with: Version ID to merge with :type merge_with: str """ _schema = { "properties": { "dataset": { "description": "Existing Dataset id", "type": ["string", "null"], }, "merge_with": { "description": "Version ID to merge with", "type": ["string", "null"], }, "version": { "description": "Version id of a version belonging to the dataset", "type": ["string", "null"], }, }, "type": "object", } def __init__(self, version=None, dataset=None, merge_with=None, **kwargs): super(ViewEntry, self).__init__(**kwargs) self.version = version self.dataset = dataset self.merge_with = merge_with @schema_property("version") def version(self): return self._property_version @version.setter def version(self, value): if value is None: self._property_version = None return self.assert_isinstance(value, "version", six.string_types) self._property_version = value @schema_property("dataset") def dataset(self): return self._property_dataset @dataset.setter def dataset(self, value): if value is None: self._property_dataset = None return self.assert_isinstance(value, "dataset", six.string_types) self._property_dataset = value @schema_property("merge_with") def merge_with(self): return self._property_merge_with @merge_with.setter def merge_with(self, value): if value is None: self._property_merge_with = None return self.assert_isinstance(value, "merge_with", six.string_types) self._property_merge_with = value
ViewEntry
python
ansible__ansible
test/units/module_utils/facts/test_facts.py
{ "start": 2809, "end": 2991 }
class ____(BaseTestFactsPlatform): platform_id = 'SunOS' fact_class = hardware.sunos.SunOSHardware collector_class = hardware.sunos.SunOSHardwareCollector
TestSunOSHardware
python
getsentry__sentry
src/sentry/replays/lib/storage.py
{ "start": 5109, "end": 6219 }
class ____(Blob): """Storage service driver blob manager. This driver does not have managed TTLs. To enable TTLs you will need to enable it on your bucket. Keys are prefixed by their TTL. Those TTLs are 30, 60, 90. Measured in days. """ def delete(self, segment: RecordingSegmentStorageMeta) -> None: return storage_kv.delete(self.make_key(segment)) @metrics.wraps("replays.lib.storage.StorageBlob.get") def get(self, segment: RecordingSegmentStorageMeta) -> bytes | None: return storage_kv.get(self.make_key(segment)) @metrics.wraps("replays.lib.storage.StorageBlob.set") def set(self, segment: RecordingSegmentStorageMeta, value: bytes) -> None: return storage_kv.set(self.make_key(segment), value) def initialize_client(self): return storage_kv.initialize_client() def make_key(self, segment: RecordingSegmentStorageMeta) -> str: return _make_recording_filename( segment.retention_days, segment.project_id, segment.replay_id, segment.segment_id, )
StorageBlob
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/postgresql/pg8000.py
{ "start": 4965, "end": 5089 }
class ____(JSONB): render_bind_cast = True def result_processor(self, dialect, coltype): return None
_PGJSONB
python
mozilla__bleach
bleach/_vendor/html5lib/_inputstream.py
{ "start": 2472, "end": 5705 }
class ____(object): """Buffering for streams that do not have buffering of their own The buffer is implemented as a list of chunks on the assumption that joining many strings will be slow since it is O(n**2) """ def __init__(self, stream): self.stream = stream self.buffer = [] self.position = [-1, 0] # chunk number, offset def tell(self): pos = 0 for chunk in self.buffer[:self.position[0]]: pos += len(chunk) pos += self.position[1] return pos def seek(self, pos): assert pos <= self._bufferedBytes() offset = pos i = 0 while len(self.buffer[i]) < offset: offset -= len(self.buffer[i]) i += 1 self.position = [i, offset] def read(self, bytes): if not self.buffer: return self._readStream(bytes) elif (self.position[0] == len(self.buffer) and self.position[1] == len(self.buffer[-1])): return self._readStream(bytes) else: return self._readFromBuffer(bytes) def _bufferedBytes(self): return sum([len(item) for item in self.buffer]) def _readStream(self, bytes): data = self.stream.read(bytes) self.buffer.append(data) self.position[0] += 1 self.position[1] = len(data) return data def _readFromBuffer(self, bytes): remainingBytes = bytes rv = [] bufferIndex = self.position[0] bufferOffset = self.position[1] while bufferIndex < len(self.buffer) and remainingBytes != 0: assert remainingBytes > 0 bufferedData = self.buffer[bufferIndex] if remainingBytes <= len(bufferedData) - bufferOffset: bytesToRead = remainingBytes self.position = [bufferIndex, bufferOffset + bytesToRead] else: bytesToRead = len(bufferedData) - bufferOffset self.position = [bufferIndex, len(bufferedData)] bufferIndex += 1 rv.append(bufferedData[bufferOffset:bufferOffset + bytesToRead]) remainingBytes -= bytesToRead bufferOffset = 0 if remainingBytes: rv.append(self._readStream(remainingBytes)) return b"".join(rv) def HTMLInputStream(source, **kwargs): # Work around Python bug #20007: read(0) closes the connection. # http://bugs.python.org/issue20007 if (isinstance(source, http_client.HTTPResponse) or # Also check for addinfourl wrapping HTTPResponse (isinstance(source, urllib.response.addbase) and isinstance(source.fp, http_client.HTTPResponse))): isUnicode = False elif hasattr(source, "read"): isUnicode = isinstance(source.read(0), text_type) else: isUnicode = isinstance(source, text_type) if isUnicode: encodings = [x for x in kwargs if x.endswith("_encoding")] if encodings: raise TypeError("Cannot set an encoding with a unicode input, set %r" % encodings) return HTMLUnicodeInputStream(source, **kwargs) else: return HTMLBinaryInputStream(source, **kwargs)
BufferedStream
python
django__django
tests/validation/models.py
{ "start": 1619, "end": 1725 }
class ____(models.Model): my_pk_field = models.CharField(max_length=100, primary_key=True)
CustomPKModel
python
tensorflow__tensorflow
tensorflow/python/ops/parallel_for/control_flow_ops_test.py
{ "start": 71739, "end": 73267 }
class ____(PForTestCase): def setUp(self): self._enabled = control_flow_v2_toggles.control_flow_v2_enabled() control_flow_v2_toggles.enable_control_flow_v2() super(NestedControlFlowTest, self).setUp() def tearDown(self): if not self._enabled: control_flow_v2_toggles.disable_control_flow_v2() super(NestedControlFlowTest, self).tearDown() def _cond(self, f=None, split=0): if f is None: f = lambda x, y: (x, y) def _f(x, y): return cond.cond(y > split, lambda: f(x, y), lambda: (x + 1., y)) return _f def _while(self, f=None): if f is None: f = lambda x, y: (x, y) def _f(x, y): return while_loop.while_loop( lambda j, _: j < y, lambda j, t: (j + 1, t + array_ops.gather(f(x, y)[0], j)), [0, x])[1], y return _f def _test_helper(self, f): x = random_ops.random_uniform([5, 5]) y = constant_op.constant([4, -1, 2, -2, 2]) def loop_fn(i): x_i = array_ops.gather(x, i) y_i = array_ops.gather(y, i) return f(x_i, y_i) self._test_loop_fn(loop_fn, 5) def test_cond_while(self): self._test_helper(self._cond(self._while())) def test_while_cond(self): self._test_helper(self._while(self._cond())) def test_while_while(self): self._test_helper(self._while(self._while())) def test_cond_cond(self): self._test_helper(self._cond(self._cond())) @test_util.run_all_in_graph_and_eager_modes @test_util.with_control_flow_v2
NestedControlFlowTest
python
kamyu104__LeetCode-Solutions
Python/difference-between-maximum-and-minimum-price-sum.py
{ "start": 2421, "end": 4239 }
class ____(object): def maxOutput(self, n, edges, price): """ :type n: int :type edges: List[List[int]] :type price: List[int] :rtype: int """ def iter_dfs(): dp = [0]*n # max_sum stk = [(1, 0, -1)] while stk: step, u, p = stk.pop() if step == 1: stk.append((2, u, p)) for v in adj[u]: if v == p: continue stk.append((1, v, u)) elif step == 2: dp[u] = price[u] for v in adj[u]: if v == p: continue dp[u] = max(dp[u], dp[v]+price[u]) return dp def iter_dfs2(): result = 0 stk = [(0, -1, 0)] while stk: u, p, curr = stk.pop() result = max(result, curr, dp[u]-price[u]) top2 = [[curr, p], [0, -1]] for v in adj[u]: if v == p: continue curr = [dp[v], v] for i in xrange(len(top2)): if curr > top2[i]: top2[i], curr = curr, top2[i] for v in adj[u]: if v == p: continue stk.append((v, u, (top2[0][0] if top2[0][1] != v else top2[1][0])+price[u])) return result adj = [[] for _ in xrange(n)] for u, v in edges: adj[u].append(v) adj[v].append(u) dp = iter_dfs() return iter_dfs2() # Time: O(n) # Space: O(n) # dfs, tree dp
Solution3
python
getsentry__sentry
src/sentry/releases/endpoints/organization_release_details.py
{ "start": 2022, "end": 3690 }
class ____(ReleaseSerializer): headCommits = ListField( child=ReleaseHeadCommitSerializerDeprecated(), required=False, allow_null=False, ) refs = ListField( child=ReleaseHeadCommitSerializer(), required=False, allow_null=False, help_text="""An optional way to indicate the start and end commits for each repository included in a release. Head commits must include parameters ``repository`` and ``commit`` (the HEAD SHA). For GitLab repositories, please use the Group name instead of the slug. They can optionally include ``previousCommit`` (the SHA of the HEAD of the previous release), which should be specified if this is the first time you've sent commit data.""", ) def add_status_filter_to_queryset(queryset, status_filter): """ Function that adds status filter on a queryset """ try: status_int = ReleaseStatus.from_string(status_filter) except ValueError: raise ParseError(detail="invalid value for status") if status_int == ReleaseStatus.OPEN: queryset = queryset.filter(Q(status=status_int) | Q(status=None)) else: queryset = queryset.filter(status=status_int) return queryset def add_query_filter_to_queryset(queryset, query): """ Function that adds a query filtering to a queryset """ if query: query_q = Q(version__icontains=query) suffix_match = _release_suffix.match(query) if suffix_match is not None: query_q |= Q(version__icontains="%s+%s" % suffix_match.groups()) queryset = queryset.filter(query_q) return queryset
OrganizationReleaseSerializer
python
apache__avro
lang/py/avro/errors.py
{ "start": 1493, "end": 1607 }
class ____(SchemaParseException): """User attempted to parse a schema with an invalid default."""
InvalidDefault
python
gevent__gevent
src/gevent/_fileobjectcommon.py
{ "start": 2935, "end": 3045 }
class ____(WriteallMixin): def write(self, value): return self.writeall(value)
WriteIsWriteallMixin
python
ray-project__ray
rllib/algorithms/dreamerv3/torch/models/components/vector_decoder.py
{ "start": 339, "end": 2245 }
class ____(nn.Module): """A simple vector decoder to reproduce non-image (1D vector) observations. Wraps an MLP for mean parameter computations and a Gaussian distribution, from which we then sample using these mean values and a fixed stddev of 1.0. """ def __init__( self, *, input_size: int, model_size: str = "XS", observation_space: gym.Space, ): """Initializes a VectorDecoder instance. Args: input_size: The input size of the vector decoder. model_size: The "Model Size" used according to [1] Appendinx B. Determines the exact size of the underlying MLP. observation_space: The observation space to decode back into. This must be a Box of shape (d,), where d >= 1. """ super().__init__() assert ( isinstance(observation_space, gym.spaces.Box) and len(observation_space.shape) == 1 ) self.mlp = MLP( input_size=input_size, model_size=model_size, output_layer_size=observation_space.shape[0], ) def forward(self, h, z): """Performs a forward pass through the vector encoder. Args: h: The deterministic hidden state of the sequence model. [B, dim(h)]. z: The stochastic discrete representations of the original observation input. [B, num_categoricals, num_classes]. """ # Flatten last two dims of z. assert len(z.shape) == 3 z_shape = z.shape z = z.view(z_shape[0], -1) assert len(z.shape) == 2 out = torch.cat([h, z], dim=-1) # Send h-cat-z through MLP to get mean values of diag gaussian. loc = self.mlp(out) # Return only the predicted observations (mean, no sample). return loc
VectorDecoder
python
huggingface__transformers
src/transformers/models/mgp_str/modeling_mgp_str.py
{ "start": 5832, "end": 6613 }
class ____(nn.Module): """MLP as used in Vision Transformer, MLP-Mixer and related networks""" def __init__(self, config: MgpstrConfig, hidden_features): super().__init__() hidden_features = hidden_features or config.hidden_size self.fc1 = nn.Linear(config.hidden_size, hidden_features) self.act = nn.GELU() self.fc2 = nn.Linear(hidden_features, config.hidden_size) self.drop = nn.Dropout(config.drop_rate) def forward(self, hidden_states): hidden_states = self.fc1(hidden_states) hidden_states = self.act(hidden_states) hidden_states = self.drop(hidden_states) hidden_states = self.fc2(hidden_states) hidden_states = self.drop(hidden_states) return hidden_states
MgpstrMlp
python
pola-rs__polars
py-polars/tests/unit/io/database/test_async.py
{ "start": 1814, "end": 7052 }
class ____(ModuleType): """Mock SurrealDB module; enables internal `isinstance` check for AsyncSurrealDB.""" AsyncSurrealDB = MockSurrealConnection @pytest.mark.skipif( parse_version(sqlalchemy.__version__) < (2, 0), reason="SQLAlchemy 2.0+ required for async tests", ) def test_read_async(tmp_sqlite_db: Path) -> None: # confirm that we can load frame data from the core sqlalchemy async # primitives: AsyncConnection, AsyncEngine, and async_sessionmaker from sqlalchemy.ext.asyncio import async_sessionmaker async_engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_sqlite_db}") async_connection = async_engine.connect() async_session = async_sessionmaker(async_engine) async_session_inst = async_session() expected_frame = pl.DataFrame( {"id": [2, 1], "name": ["other", "misc"], "value": [-99.5, 100.0]} ) async_conn: Any for async_conn in ( async_engine, async_connection, async_session, async_session_inst, ): if async_conn in (async_session, async_session_inst): constraint, execute_opts = "", {} else: constraint = "WHERE value > :n" execute_opts = {"parameters": {"n": -1000}} df = pl.read_database( query=f""" SELECT id, name, value FROM test_data {constraint} ORDER BY id DESC """, connection=async_conn, execute_options=execute_opts, ) assert_frame_equal(expected_frame, df) async def _nested_async_test(tmp_sqlite_db: Path) -> pl.DataFrame: async_engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_sqlite_db}") return pl.read_database( query="SELECT id, name FROM test_data ORDER BY id", connection=async_engine.connect(), ) @pytest.mark.skipif( parse_version(sqlalchemy.__version__) < (2, 0), reason="SQLAlchemy 2.0+ required for async tests", ) def test_read_async_nested(tmp_sqlite_db: Path) -> None: # This tests validates that we can handle nested async calls expected_frame = pl.DataFrame({"id": [1, 2], "name": ["misc", "other"]}) df = asyncio.run(_nested_async_test(tmp_sqlite_db)) assert_frame_equal(expected_frame, df) @overload async def _surreal_query_as_frame( url: str, query: str, batch_size: None ) -> pl.DataFrame: ... @overload async def _surreal_query_as_frame( url: str, query: str, batch_size: int ) -> Iterable[pl.DataFrame]: ... async def _surreal_query_as_frame( url: str, query: str, batch_size: int | None ) -> pl.DataFrame | Iterable[pl.DataFrame]: batch_params = ( {"iter_batches": True, "batch_size": batch_size} if batch_size else {} ) async with MockSurrealConnection(url=url, mock_data=SURREAL_MOCK_DATA) as client: await client.use(namespace="test", database="test") return pl.read_database( # type: ignore[no-any-return,call-overload] query=query, connection=client, **batch_params, ) @pytest.mark.parametrize("batch_size", [None, 1, 2, 3, 4]) def test_surrealdb_fetchall(batch_size: int | None) -> None: with mock_module_import("surrealdb", MockedSurrealModule("surrealdb")): df_expected = pl.DataFrame(SURREAL_MOCK_DATA) res = asyncio.run( _surreal_query_as_frame( url="ws://localhost:8000/rpc", query="SELECT * FROM item", batch_size=batch_size, ) ) if batch_size: frames = list(res) # type: ignore[call-overload] n_mock_rows = len(SURREAL_MOCK_DATA) assert len(frames) == ceil(n_mock_rows / batch_size) assert_frame_equal(df_expected[:batch_size], frames[0]) else: assert_frame_equal(df_expected, res) # type: ignore[arg-type] def test_async_nested_captured_loop_21263() -> None: # Tests awaiting a future that has "captured" the original event loop from # within a `_run_async` context. async def test_impl() -> None: loop = asyncio.get_running_loop() task = loop.create_task(asyncio.sleep(0)) _run_async(await_task(task)) async def await_task(task: Any) -> None: await task asyncio.run(test_impl()) def test_async_index_error_25209(tmp_sqlite_db: Path) -> None: base_uri = f"sqlite:///{tmp_sqlite_db}" table_name = "test_25209" pl.select(x=1, y=2, z=3).write_database( table_name, connection=base_uri, engine="sqlalchemy", if_table_exists="replace", ) async def run_async_query() -> Any: async_engine = create_async_engine(f"sqlite+aio{base_uri}") try: return pl.read_database( query=f"SELECT * FROM {table_name}", connection=async_engine, ) finally: await async_engine.dispose() async def testing() -> Any: # return/await multiple queries return await asyncio.gather(*(run_async_query(), run_async_query())) df1, df2 = asyncio.run(testing()) assert_frame_equal(df1, df2) assert df1.rows() == [(1, 2, 3)]
MockedSurrealModule
python
wandb__wandb
wandb/automations/_generated/input_types.py
{ "start": 819, "end": 921 }
class ____(GQLInput): queue_id: GQLId = Field(alias="queueID") template: str
QueueJobActionInput
python
realpython__materials
python-sockets-tutorial/libserver.py
{ "start": 268, "end": 7215 }
class ____: def __init__(self, selector, sock, addr): self.selector = selector self.sock = sock self.addr = addr self._recv_buffer = b"" self._send_buffer = b"" self._jsonheader_len = None self.jsonheader = None self.request = None self.response_created = False def _set_selector_events_mask(self, mode): """Set selector to listen for events: mode is 'r', 'w', or 'rw'.""" if mode == "r": events = selectors.EVENT_READ elif mode == "w": events = selectors.EVENT_WRITE elif mode == "rw": events = selectors.EVENT_READ | selectors.EVENT_WRITE else: raise ValueError(f"Invalid events mask mode {mode!r}.") self.selector.modify(self.sock, events, data=self) def _read(self): try: # Should be ready to read data = self.sock.recv(4096) except BlockingIOError: # Resource temporarily unavailable (errno EWOULDBLOCK) pass else: if data: self._recv_buffer += data else: raise RuntimeError("Peer closed.") def _write(self): if self._send_buffer: print(f"Sending {self._send_buffer!r} to {self.addr}") try: # Should be ready to write sent = self.sock.send(self._send_buffer) except BlockingIOError: # Resource temporarily unavailable (errno EWOULDBLOCK) pass else: self._send_buffer = self._send_buffer[sent:] # Close when the buffer is drained. The response has been sent. if sent and not self._send_buffer: self.close() def _json_encode(self, obj, encoding): return json.dumps(obj, ensure_ascii=False).encode(encoding) def _json_decode(self, json_bytes, encoding): tiow = io.TextIOWrapper( io.BytesIO(json_bytes), encoding=encoding, newline="" ) obj = json.load(tiow) tiow.close() return obj def _create_message( self, *, content_bytes, content_type, content_encoding ): jsonheader = { "byteorder": sys.byteorder, "content-type": content_type, "content-encoding": content_encoding, "content-length": len(content_bytes), } jsonheader_bytes = self._json_encode(jsonheader, "utf-8") message_hdr = struct.pack(">H", len(jsonheader_bytes)) message = message_hdr + jsonheader_bytes + content_bytes return message def _create_response_json_content(self): action = self.request.get("action") if action == "search": query = self.request.get("value") answer = request_search.get(query) or f"No match for '{query}'." content = {"result": answer} else: content = {"result": f"Error: invalid action '{action}'."} content_encoding = "utf-8" response = { "content_bytes": self._json_encode(content, content_encoding), "content_type": "text/json", "content_encoding": content_encoding, } return response def _create_response_binary_content(self): response = { "content_bytes": b"First 10 bytes of request: " + self.request[:10], "content_type": "binary/custom-server-binary-type", "content_encoding": "binary", } return response def process_events(self, mask): if mask & selectors.EVENT_READ: self.read() if mask & selectors.EVENT_WRITE: self.write() def read(self): self._read() if self._jsonheader_len is None: self.process_protoheader() if self._jsonheader_len is not None: if self.jsonheader is None: self.process_jsonheader() if self.jsonheader: if self.request is None: self.process_request() def write(self): if self.request: if not self.response_created: self.create_response() self._write() def close(self): print(f"Closing connection to {self.addr}") try: self.selector.unregister(self.sock) except Exception as e: print( f"Error: selector.unregister() exception for {self.addr}: {e!r}" ) try: self.sock.close() except OSError as e: print(f"Error: socket.close() exception for {self.addr}: {e!r}") finally: # Delete reference to socket object for garbage collection self.sock = None def process_protoheader(self): hdrlen = 2 if len(self._recv_buffer) >= hdrlen: self._jsonheader_len = struct.unpack( ">H", self._recv_buffer[:hdrlen] )[0] self._recv_buffer = self._recv_buffer[hdrlen:] def process_jsonheader(self): hdrlen = self._jsonheader_len if len(self._recv_buffer) >= hdrlen: self.jsonheader = self._json_decode( self._recv_buffer[:hdrlen], "utf-8" ) self._recv_buffer = self._recv_buffer[hdrlen:] for reqhdr in ( "byteorder", "content-length", "content-type", "content-encoding", ): if reqhdr not in self.jsonheader: raise ValueError(f"Missing required header '{reqhdr}'.") def process_request(self): content_len = self.jsonheader["content-length"] if not len(self._recv_buffer) >= content_len: return data = self._recv_buffer[:content_len] self._recv_buffer = self._recv_buffer[content_len:] if self.jsonheader["content-type"] == "text/json": encoding = self.jsonheader["content-encoding"] self.request = self._json_decode(data, encoding) print(f"Received request {self.request!r} from {self.addr}") else: # Binary or unknown content-type self.request = data print( f"Received {self.jsonheader['content-type']} request from {self.addr}" ) # Set selector to listen for write events, we're done reading. self._set_selector_events_mask("w") def create_response(self): if self.jsonheader["content-type"] == "text/json": response = self._create_response_json_content() else: # Binary or unknown content-type response = self._create_response_binary_content() message = self._create_message(**response) self.response_created = True self._send_buffer += message
Message
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/tasks.py
{ "start": 41210, "end": 44418 }
class ____(GoogleCloudBaseOperator): """ Deletes a task from Cloud Tasks. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudTasksTaskDeleteOperator` :param location: The location name in which the task will be deleted. :param queue_name: The queue's name. :param task_name: The task's name. :param project_id: (Optional) The ID of the Google Cloud project that owns the Cloud Tasks. If set to None or missing, the default project_id from the Google Cloud connection is used. :param retry: (Optional) A retry object used to retry requests. If None is specified, requests will not be retried. :param timeout: (Optional) The amount of time, in seconds, to wait for the request to complete. Note that if retry is specified, the timeout applies to each individual attempt. :param metadata: (Optional) Additional metadata that is provided to the method. :param gcp_conn_id: (Optional) The connection ID used to connect 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). """ template_fields: Sequence[str] = ( "location", "queue_name", "task_name", "project_id", "gcp_conn_id", "impersonation_chain", ) def __init__( self, *, location: str, queue_name: str, task_name: str, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: MetaData = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.location = location self.queue_name = queue_name self.task_name = task_name self.project_id = project_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = CloudTasksHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) hook.delete_task( location=self.location, queue_name=self.queue_name, task_name=self.task_name, project_id=self.project_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, )
CloudTasksTaskDeleteOperator
python
sanic-org__sanic
sanic/response/types.py
{ "start": 16230, "end": 18421 }
class ____: """A compat layer to bridge the gap after the deprecation of StreamingHTTPResponse. It will be removed when: - file_stream is moved to new style streaming - file and file_stream are combined into a single API """ # noqa: E501 __slots__ = ( "_cookies", "content_type", "headers", "request", "response", "status", "streaming_fn", ) def __init__( self, streaming_fn: Callable[ [Union[BaseHTTPResponse, ResponseStream]], Coroutine[Any, Any, None], ], status: int = 200, headers: Optional[Union[Header, dict[str, str]]] = None, content_type: Optional[str] = None, ): if headers is None: headers = Header() elif not isinstance(headers, Header): headers = Header(headers) self.streaming_fn = streaming_fn self.status = status self.headers = headers or Header() self.content_type = content_type self.request: Optional[Request] = None self._cookies: Optional[CookieJar] = None async def write(self, message: str): await self.response.send(message) async def stream(self) -> HTTPResponse: if not self.request: raise ServerError("Attempted response to unknown request") self.response = await self.request.respond( headers=self.headers, status=self.status, content_type=self.content_type, ) await self.streaming_fn(self) return self.response async def eof(self) -> None: await self.response.eof() @property def cookies(self) -> CookieJar: if self._cookies is None: self._cookies = CookieJar(self.headers) return self._cookies @property def processed_headers(self): return self.response.processed_headers @property def body(self): return self.response.body def __call__(self, request: Request) -> ResponseStream: self.request = request return self def __await__(self): return self.stream().__await__()
ResponseStream
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 346711, "end": 347295 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("GistEdge"), graphql_name="edges") nodes = sgqlc.types.Field(sgqlc.types.list_of("Gist"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
GistConnection
python
ansible__ansible
test/lib/ansible_test/_internal/cli/argparsing/parsers.py
{ "start": 10157, "end": 10766 }
class ____(ChoicesParser): """Composite argument parser which relies on a static list of choices derived from the values of an enum.""" def __init__(self, enum_type: t.Type[enum.Enum], conditions: MatchConditions = MatchConditions.CHOICE) -> None: self.enum_type = enum_type super().__init__(choices=[str(item.value) for item in enum_type], conditions=conditions) def parse(self, state: ParserState) -> t.Any: """Parse the input from the given state and return the result.""" value = super().parse(state) return self.enum_type(value)
EnumValueChoicesParser
python
kamyu104__LeetCode-Solutions
Python/shortest-subarray-with-or-at-least-k-i.py
{ "start": 1136, "end": 1670 }
class ____(object): def minimumSubarrayLength(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ result = float("inf") for left in xrange(len(nums)): curr = 0 for right in xrange(left, len(nums)): curr |= nums[right] if curr < k: continue result = min(result, right-left+1) break return result if result != float("inf") else -1
Solution2
python
PyCQA__pylint
tests/checkers/unittest_variables.py
{ "start": 621, "end": 1042 }
class ____(CheckerTestCase): CHECKER_CLASS = variables.VariablesChecker def test_all_elements_without_parent(self) -> None: node = astroid.extract_node("__all__ = []") node.value.elts.append(nodes.Const("test", parent=None)) root = node.root() with self.assertNoMessages(): self.checker.visit_module(root) self.checker.leave_module(root)
TestVariablesChecker
python
django__django
tests/auth_tests/test_remote_user.py
{ "start": 541, "end": 15051 }
class ____(TestCase): middleware = "django.contrib.auth.middleware.RemoteUserMiddleware" backend = "django.contrib.auth.backends.RemoteUserBackend" header = "REMOTE_USER" email_header = "REMOTE_EMAIL" # Usernames to be passed in REMOTE_USER for the test_known_user test case. known_user = "knownuser" known_user2 = "knownuser2" @classmethod def setUpClass(cls): cls.enterClassContext( modify_settings( AUTHENTICATION_BACKENDS={"append": cls.backend}, MIDDLEWARE={"append": cls.middleware}, ) ) super().setUpClass() def test_passing_explicit_none(self): msg = "get_response must be provided." with self.assertRaisesMessage(ValueError, msg): RemoteUserMiddleware(None) def test_no_remote_user(self): """Users are not created when remote user is not specified.""" num_users = User.objects.count() response = self.client.get("/remote_user/") self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(User.objects.count(), num_users) response = self.client.get("/remote_user/", **{self.header: None}) self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(User.objects.count(), num_users) response = self.client.get("/remote_user/", **{self.header: ""}) self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(User.objects.count(), num_users) async def test_no_remote_user_async(self): """See test_no_remote_user.""" num_users = await User.objects.acount() response = await self.async_client.get("/remote_user/") self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(await User.objects.acount(), num_users) response = await self.async_client.get("/remote_user/", **{self.header: ""}) self.assertTrue(response.context["user"].is_anonymous) self.assertEqual(await User.objects.acount(), num_users) def test_csrf_validation_passes_after_process_request_login(self): """ CSRF check must access the CSRF token from the session or cookie, rather than the request, as rotate_token() may have been called by an authentication middleware during the process_request() phase. """ csrf_client = Client(enforce_csrf_checks=True) csrf_secret = _get_new_csrf_string() csrf_token = _mask_cipher_secret(csrf_secret) csrf_token_form = _mask_cipher_secret(csrf_secret) headers = {self.header: "fakeuser"} data = {"csrfmiddlewaretoken": csrf_token_form} # Verify that CSRF is configured for the view csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token}) response = csrf_client.post("/remote_user/", **headers) self.assertEqual(response.status_code, 403) self.assertIn(b"CSRF verification failed.", response.content) # This request will call django.contrib.auth.login() which will call # django.middleware.csrf.rotate_token() thus changing the value of # request.META['CSRF_COOKIE'] from the user submitted value set by # CsrfViewMiddleware.process_request() to the new csrftoken value set # by rotate_token(). Csrf validation should still pass when the view is # later processed by CsrfViewMiddleware.process_view() csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token}) response = csrf_client.post("/remote_user/", data, **headers) self.assertEqual(response.status_code, 200) async def test_csrf_validation_passes_after_process_request_login_async(self): """See test_csrf_validation_passes_after_process_request_login.""" csrf_client = AsyncClient(enforce_csrf_checks=True) csrf_secret = _get_new_csrf_string() csrf_token = _mask_cipher_secret(csrf_secret) csrf_token_form = _mask_cipher_secret(csrf_secret) headers = {self.header: "fakeuser"} data = {"csrfmiddlewaretoken": csrf_token_form} # Verify that CSRF is configured for the view csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token}) response = await csrf_client.post("/remote_user/", **headers) self.assertEqual(response.status_code, 403) self.assertIn(b"CSRF verification failed.", response.content) # This request will call django.contrib.auth.alogin() which will call # django.middleware.csrf.rotate_token() thus changing the value of # request.META['CSRF_COOKIE'] from the user submitted value set by # CsrfViewMiddleware.process_request() to the new csrftoken value set # by rotate_token(). Csrf validation should still pass when the view is # later processed by CsrfViewMiddleware.process_view() csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token}) response = await csrf_client.post("/remote_user/", data, **headers) self.assertEqual(response.status_code, 200) def test_unknown_user(self): """ Tests the case where the username passed in the header does not exist as a User. """ num_users = User.objects.count() response = self.client.get("/remote_user/", **{self.header: "newuser"}) self.assertEqual(response.context["user"].username, "newuser") self.assertEqual(User.objects.count(), num_users + 1) User.objects.get(username="newuser") # Another request with same user should not create any new users. response = self.client.get("/remote_user/", **{self.header: "newuser"}) self.assertEqual(User.objects.count(), num_users + 1) async def test_unknown_user_async(self): """See test_unknown_user.""" num_users = await User.objects.acount() response = await self.async_client.get( "/remote_user/", **{self.header: "newuser"} ) self.assertEqual(response.context["user"].username, "newuser") self.assertEqual(await User.objects.acount(), num_users + 1) await User.objects.aget(username="newuser") # Another request with same user should not create any new users. response = await self.async_client.get( "/remote_user/", **{self.header: "newuser"} ) self.assertEqual(await User.objects.acount(), num_users + 1) def test_known_user(self): """ Tests the case where the username passed in the header is a valid User. """ User.objects.create(username="knownuser") User.objects.create(username="knownuser2") num_users = User.objects.count() response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, "knownuser") self.assertEqual(User.objects.count(), num_users) # A different user passed in the headers causes the new user # to be logged in. response = self.client.get("/remote_user/", **{self.header: self.known_user2}) self.assertEqual(response.context["user"].username, "knownuser2") self.assertEqual(User.objects.count(), num_users) async def test_known_user_async(self): """See test_known_user.""" await User.objects.acreate(username="knownuser") await User.objects.acreate(username="knownuser2") num_users = await User.objects.acount() response = await self.async_client.get( "/remote_user/", **{self.header: self.known_user} ) self.assertEqual(response.context["user"].username, "knownuser") self.assertEqual(await User.objects.acount(), num_users) # A different user passed in the headers causes the new user # to be logged in. response = await self.async_client.get( "/remote_user/", **{self.header: self.known_user2} ) self.assertEqual(response.context["user"].username, "knownuser2") self.assertEqual(await User.objects.acount(), num_users) def test_last_login(self): """ A user's last_login is set the first time they make a request but not updated in subsequent requests with the same session. """ user = User.objects.create(username="knownuser") # Set last_login to something so we can determine if it changes. default_login = datetime(2000, 1, 1) if settings.USE_TZ: default_login = default_login.replace(tzinfo=UTC) user.last_login = default_login user.save() response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertNotEqual(default_login, response.context["user"].last_login) user = User.objects.get(username="knownuser") user.last_login = default_login user.save() response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(default_login, response.context["user"].last_login) async def test_last_login_async(self): """See test_last_login.""" user = await User.objects.acreate(username="knownuser") # Set last_login to something so we can determine if it changes. default_login = datetime(2000, 1, 1) if settings.USE_TZ: default_login = default_login.replace(tzinfo=UTC) user.last_login = default_login await user.asave() response = await self.async_client.get( "/remote_user/", **{self.header: self.known_user} ) self.assertNotEqual(default_login, response.context["user"].last_login) user = await User.objects.aget(username="knownuser") user.last_login = default_login await user.asave() response = await self.async_client.get( "/remote_user/", **{self.header: self.known_user} ) self.assertEqual(default_login, response.context["user"].last_login) def test_header_disappears(self): """ A logged in user is logged out automatically when the REMOTE_USER header disappears during the same browser session. """ User.objects.create(username="knownuser") # Known user authenticates response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, "knownuser") # During the session, the REMOTE_USER header disappears. Should trigger # logout. response = self.client.get("/remote_user/") self.assertTrue(response.context["user"].is_anonymous) # verify the remoteuser middleware will not remove a user # authenticated via another backend User.objects.create_user(username="modeluser", password="foo") self.client.login(username="modeluser", password="foo") authenticate(username="modeluser", password="foo") response = self.client.get("/remote_user/") self.assertEqual(response.context["user"].username, "modeluser") async def test_header_disappears_async(self): """See test_header_disappears.""" await User.objects.acreate(username="knownuser") # Known user authenticates response = await self.async_client.get( "/remote_user/", **{self.header: self.known_user} ) self.assertEqual(response.context["user"].username, "knownuser") # During the session, the REMOTE_USER header disappears. Should trigger # logout. response = await self.async_client.get("/remote_user/") self.assertTrue(response.context["user"].is_anonymous) # verify the remoteuser middleware will not remove a user # authenticated via another backend await User.objects.acreate_user(username="modeluser", password="foo") await self.async_client.alogin(username="modeluser", password="foo") await aauthenticate(username="modeluser", password="foo") response = await self.async_client.get("/remote_user/") self.assertEqual(response.context["user"].username, "modeluser") def test_user_switch_forces_new_login(self): """ If the username in the header changes between requests that the original user is logged out """ User.objects.create(username="knownuser") # Known user authenticates response = self.client.get("/remote_user/", **{self.header: self.known_user}) self.assertEqual(response.context["user"].username, "knownuser") # During the session, the REMOTE_USER changes to a different user. response = self.client.get("/remote_user/", **{self.header: "newnewuser"}) # The current user is not the prior remote_user. # In backends that create a new user, username is "newnewuser" # In backends that do not create new users, it is '' (anonymous user) self.assertNotEqual(response.context["user"].username, "knownuser") async def test_user_switch_forces_new_login_async(self): """See test_user_switch_forces_new_login.""" await User.objects.acreate(username="knownuser") # Known user authenticates response = await self.async_client.get( "/remote_user/", **{self.header: self.known_user} ) self.assertEqual(response.context["user"].username, "knownuser") # During the session, the REMOTE_USER changes to a different user. response = await self.async_client.get( "/remote_user/", **{self.header: "newnewuser"} ) # The current user is not the prior remote_user. # In backends that create a new user, username is "newnewuser" # In backends that do not create new users, it is '' (anonymous user) self.assertNotEqual(response.context["user"].username, "knownuser") def test_inactive_user(self): User.objects.create(username="knownuser", is_active=False) response = self.client.get("/remote_user/", **{self.header: "knownuser"}) self.assertTrue(response.context["user"].is_anonymous) async def test_inactive_user_async(self): await User.objects.acreate(username="knownuser", is_active=False) response = await self.async_client.get( "/remote_user/", **{self.header: "knownuser"} ) self.assertTrue(response.context["user"].is_anonymous)
RemoteUserTest
python
getsentry__sentry
src/sentry/discover/endpoints/discover_key_transactions.py
{ "start": 6534, "end": 6715 }
class ____(Serializer): def serialize(self, obj, attrs, user, **kwargs): return { "team": str(obj.project_team.team_id), }
TeamKeyTransactionSerializer
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/ext/associationproxy.py
{ "start": 9790, "end": 10089 }
class ____(InspectionAttrExtensionType): ASSOCIATION_PROXY = "ASSOCIATION_PROXY" """Symbol indicating an :class:`.InspectionAttr` that's of type :class:`.AssociationProxy`. Is assigned to the :attr:`.InspectionAttr.extension_type` attribute. """
AssociationProxyExtensionType
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/optional_dep_test_3/package.py
{ "start": 217, "end": 578 }
class ____(Package): """Depends on the optional-dep-test package""" homepage = "http://www.example.com" url = "http://www.example.com/optional-dep-test-3-1.0.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") variant("var", default=False) depends_on("pkg-a", when="~var") depends_on("pkg-b", when="+var")
OptionalDepTest3
python
kamyu104__LeetCode-Solutions
Python/climbing-stairs.py
{ "start": 51, "end": 827 }
class ____(object): def climbStairs(self, n): """ :type n: int :rtype: int """ def matrix_expo(A, K): result = [[int(i==j) for j in xrange(len(A))] \ for i in xrange(len(A))] while K: if K % 2: result = matrix_mult(result, A) A = matrix_mult(A, A) K /= 2 return result def matrix_mult(A, B): ZB = zip(*B) return [[sum(a*b for a, b in itertools.izip(row, col)) \ for col in ZB] for row in A] T = [[1, 1], [1, 0]] return matrix_mult([[1, 0]], matrix_expo(T, n))[0][0] # [a0, a(-1)] * T^n # Time: O(n) # Space: O(1)
Solution
python
pennersr__django-allauth
allauth/account/internal/flows/password_reset_by_code.py
{ "start": 598, "end": 2774 }
class ____(AbstractCodeVerificationProcess): def __init__(self, request, state, user=None): self.request = request super().__init__( state=state, timeout=app_settings.PASSWORD_RESET_BY_CODE_TIMEOUT, max_attempts=app_settings.PASSWORD_RESET_BY_CODE_MAX_ATTEMPTS, user=user, ) def abort(self): self.request.session.pop(PASSWORD_RESET_VERIFICATION_SESSION_KEY, None) def confirm_code(self): if self.state.get("code_confirmed"): return self.state["code_confirmed"] = True self.persist() verify_email_indirectly(self.request, self.user, self.state["email"]) def finish(self) -> Optional[HttpResponse]: self.request.session.pop(PASSWORD_RESET_VERIFICATION_SESSION_KEY, None) return password_reset.finalize_password_reset( self.request, self.user, email=self.state["email"] ) def persist(self): self.request.session[PASSWORD_RESET_VERIFICATION_SESSION_KEY] = self.state def send(self): adapter = get_adapter() email = self.state["email"] if not self.user: send_unknown_account_mail(self.request, email) return code = adapter.generate_password_reset_code() self.state["code"] = code context = { "request": self.request, "code": self.code, } adapter.send_mail("account/email/password_reset_code", email, context) @classmethod def initiate(cls, *, request, user, email: str): state = cls.initial_state(user, email) process = PasswordResetVerificationProcess(request, state=state, user=user) process.send() process.persist() return process @classmethod def resume( cls, request: HttpRequest ) -> Optional["PasswordResetVerificationProcess"]: state = request.session.get(PASSWORD_RESET_VERIFICATION_SESSION_KEY) if not state: return None process = PasswordResetVerificationProcess(request, state=state) return process.abort_if_invalid()
PasswordResetVerificationProcess
python
django__django
django/db/backends/sqlite3/schema.py
{ "start": 362, "end": 20627 }
class ____(BaseDatabaseSchemaEditor): sql_delete_table = "DROP TABLE %(table)s" sql_create_fk = None sql_create_inline_fk = ( "REFERENCES %(to_table)s (%(to_column)s)%(on_delete_db)s DEFERRABLE INITIALLY " "DEFERRED" ) sql_create_column_inline_fk = sql_create_inline_fk sql_create_unique = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)" sql_delete_unique = "DROP INDEX %(name)s" sql_alter_table_comment = None sql_alter_column_comment = None def __enter__(self): # Some SQLite schema alterations need foreign key constraints to be # disabled. Enforce it here for the duration of the schema edition. if not self.connection.disable_constraint_checking(): raise NotSupportedError( "SQLite schema editor cannot be used while foreign key " "constraint checks are enabled. Make sure to disable them " "before entering a transaction.atomic() context because " "SQLite does not support disabling them in the middle of " "a multi-statement transaction." ) return super().__enter__() def __exit__(self, exc_type, exc_value, traceback): self.connection.check_constraints() super().__exit__(exc_type, exc_value, traceback) self.connection.enable_constraint_checking() def quote_value(self, value): # The backend "mostly works" without this function and there are use # cases for compiling Python without the sqlite3 libraries (e.g. # security hardening). try: import sqlite3 value = sqlite3.adapt(value) except ImportError: pass except sqlite3.ProgrammingError: pass # Manual emulation of SQLite parameter quoting if isinstance(value, bool): return str(int(value)) elif isinstance(value, (Decimal, float, int)): return str(value) elif isinstance(value, str): return "'%s'" % value.replace("'", "''") elif value is None: return "NULL" elif isinstance(value, (bytes, bytearray, memoryview)): # Bytes are only allowed for BLOB fields, encoded as string # literals containing hexadecimal data and preceded by a single "X" # character. return "X'%s'" % value.hex() else: raise ValueError( "Cannot quote parameter value %r of type %s" % (value, type(value)) ) def prepare_default(self, value): return self.quote_value(value) def _remake_table( self, model, create_field=None, delete_field=None, alter_fields=None ): """ Shortcut to transform a model from old_model into new_model This follows the correct procedure to perform non-rename or column addition operations based on SQLite's documentation https://www.sqlite.org/lang_altertable.html#caution The essential steps are: 1. Create a table with the updated definition called "new__app_model" 2. Copy the data from the existing "app_model" table to the new table 3. Drop the "app_model" table 4. Rename the "new__app_model" table to "app_model" 5. Restore any index of the previous "app_model" table. """ # Self-referential fields must be recreated rather than copied from # the old model to ensure their remote_field.field_name doesn't refer # to an altered field. def is_self_referential(f): return f.is_relation and f.remote_field.model is model # Work out the new fields dict / mapping body = { f.name: f.clone() if is_self_referential(f) else f for f in model._meta.local_concrete_fields } # Since CompositePrimaryKey is not a concrete field (column is None), # it's not copied by default. pk = model._meta.pk if isinstance(pk, CompositePrimaryKey): body[pk.name] = pk.clone() # Since mapping might mix column names and default values, # its values must be already quoted. mapping = { f.column: self.quote_name(f.column) for f in model._meta.local_concrete_fields if f.generated is False } # This maps field names (not columns) for things like unique_together rename_mapping = {} # If any of the new or altered fields is introducing a new PK, # remove the old one restore_pk_field = None alter_fields = alter_fields or [] if getattr(create_field, "primary_key", False) or any( getattr(new_field, "primary_key", False) for _, new_field in alter_fields ): for name, field in list(body.items()): if field.primary_key and not any( # Do not remove the old primary key when an altered field # that introduces a primary key is the same field. name == new_field.name for _, new_field in alter_fields ): field.primary_key = False restore_pk_field = field if field.auto_created: del body[name] del mapping[field.column] # Add in any created fields if create_field: body[create_field.name] = create_field # Choose a default and insert it into the copy map if ( not create_field.has_db_default() and not create_field.generated and create_field.concrete ): mapping[create_field.column] = self.prepare_default( self.effective_default(create_field) ) # Add in any altered fields for alter_field in alter_fields: old_field, new_field = alter_field body.pop(old_field.name, None) mapping.pop(old_field.column, None) body[new_field.name] = new_field rename_mapping[old_field.name] = new_field.name if new_field.generated: continue if old_field.null and not new_field.null: if not new_field.has_db_default(): default = self.prepare_default(self.effective_default(new_field)) else: default, _ = self.db_default_sql(new_field) case_sql = "coalesce(%(col)s, %(default)s)" % { "col": self.quote_name(old_field.column), "default": default, } mapping[new_field.column] = case_sql else: mapping[new_field.column] = self.quote_name(old_field.column) # Remove any deleted fields if delete_field: del body[delete_field.name] mapping.pop(delete_field.column, None) # Remove any implicit M2M tables if ( delete_field.many_to_many and delete_field.remote_field.through._meta.auto_created ): return self.delete_model(delete_field.remote_field.through) # Work inside a new app registry apps = Apps() # Work out the new value of unique_together, taking renames into # account unique_together = [ [rename_mapping.get(n, n) for n in unique] for unique in model._meta.unique_together ] indexes = model._meta.indexes if delete_field: indexes = [ index for index in indexes if delete_field.name not in index.fields ] constraints = list(model._meta.constraints) # Provide isolated instances of the fields to the new model body so # that the existing model's internals aren't interfered with when # the dummy model is constructed. body_copy = copy.deepcopy(body) # Construct a new model with the new fields to allow self referential # primary key to resolve to. This model won't ever be materialized as a # table and solely exists for foreign key reference resolution # purposes. This wouldn't be required if the schema editor was # operating on model states instead of rendered models. meta_contents = { "app_label": model._meta.app_label, "db_table": model._meta.db_table, "unique_together": unique_together, "indexes": indexes, "constraints": constraints, "apps": apps, } meta = type("Meta", (), meta_contents) body_copy["Meta"] = meta body_copy["__module__"] = model.__module__ type(model._meta.object_name, model.__bases__, body_copy) # Construct a model with a renamed table name. body_copy = copy.deepcopy(body) meta_contents = { "app_label": model._meta.app_label, "db_table": "new__%s" % strip_quotes(model._meta.db_table), "unique_together": unique_together, "indexes": indexes, "constraints": constraints, "apps": apps, } meta = type("Meta", (), meta_contents) body_copy["Meta"] = meta body_copy["__module__"] = model.__module__ new_model = type("New%s" % model._meta.object_name, model.__bases__, body_copy) # Remove the automatically recreated default primary key, if it has # been deleted. if delete_field and delete_field.attname == new_model._meta.pk.attname: auto_pk = new_model._meta.pk delattr(new_model, auto_pk.attname) new_model._meta.local_fields.remove(auto_pk) new_model.pk = None # Create a new table with the updated schema. self.create_model(new_model) # Copy data from the old table into the new table self.execute( "INSERT INTO %s (%s) SELECT %s FROM %s" % ( self.quote_name(new_model._meta.db_table), ", ".join(self.quote_name(x) for x in mapping), ", ".join(mapping.values()), self.quote_name(model._meta.db_table), ) ) # Delete the old table to make way for the new self.delete_model(model, handle_autom2m=False) # Rename the new table to take way for the old self.alter_db_table( new_model, new_model._meta.db_table, model._meta.db_table, ) # Run deferred SQL on correct table for sql in self.deferred_sql: self.execute(sql) self.deferred_sql = [] # Fix any PK-removed field if restore_pk_field: restore_pk_field.primary_key = True def delete_model(self, model, handle_autom2m=True): if handle_autom2m: super().delete_model(model) else: # Delete the table (and only that) self.execute( self.sql_delete_table % { "table": self.quote_name(model._meta.db_table), } ) # Remove all deferred statements referencing the deleted table. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_table( model._meta.db_table ): self.deferred_sql.remove(sql) def add_field(self, model, field): """Create a field on a model.""" from django.db.models.expressions import Value # Special-case implicit M2M tables. if field.many_to_many and field.remote_field.through._meta.auto_created: self.create_model(field.remote_field.through) elif isinstance(field, CompositePrimaryKey): # If a CompositePrimaryKey field was added, the existing primary # key field had to be altered too, resulting in an AddField, # AlterField migration. The table cannot be re-created on AddField, # it would result in a duplicate primary key error. return elif ( # Primary keys and unique fields are not supported in ALTER TABLE # ADD COLUMN. field.primary_key or field.unique or not field.null # Fields with default values cannot by handled by ALTER TABLE ADD # COLUMN statement because DROP DEFAULT is not supported in # ALTER TABLE. or self.effective_default(field) is not None # Fields with non-constant defaults cannot by handled by ALTER # TABLE ADD COLUMN statement. or (field.has_db_default() and not isinstance(field.db_default, Value)) ): self._remake_table(model, create_field=field) else: super().add_field(model, field) def remove_field(self, model, field): """ Remove a field from a model. Usually involves deleting a column, but for M2Ms may involve deleting a table. """ # M2M fields are a special case if field.many_to_many: # For implicit M2M tables, delete the auto-created table if field.remote_field.through._meta.auto_created: self.delete_model(field.remote_field.through) # For explicit "through" M2M fields, do nothing elif ( # Primary keys, unique fields, indexed fields, and foreign keys are # not supported in ALTER TABLE DROP COLUMN. not field.primary_key and not field.unique and not field.db_index and not (field.remote_field and field.db_constraint) ): super().remove_field(model, field) # For everything else, remake. else: # It might not actually have a column behind it if field.db_parameters(connection=self.connection)["type"] is None: return self._remake_table(model, delete_field=field) def _alter_field( self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False, ): """Perform a "physical" (non-ManyToMany) field update.""" # Use "ALTER TABLE ... RENAME COLUMN" if only the column name # changed and there aren't any constraints. if ( old_field.column != new_field.column and self.column_sql(model, old_field) == self.column_sql(model, new_field) and not ( old_field.remote_field and old_field.db_constraint or new_field.remote_field and new_field.db_constraint ) ): return self.execute( self._rename_field_sql( model._meta.db_table, old_field, new_field, new_type ) ) # Alter by remaking table self._remake_table(model, alter_fields=[(old_field, new_field)]) # Rebuild tables with FKs pointing to this field. old_collation = old_db_params.get("collation") new_collation = new_db_params.get("collation") if new_field.unique and ( old_type != new_type or old_collation != new_collation ): related_models = set() opts = new_field.model._meta for remote_field in opts.related_objects: # Ignore self-relationship since the table was already rebuilt. if remote_field.related_model == model: continue if not remote_field.many_to_many: if remote_field.field_name == new_field.name: related_models.add(remote_field.related_model) elif new_field.primary_key and remote_field.through._meta.auto_created: related_models.add(remote_field.through) if new_field.primary_key: for many_to_many in opts.many_to_many: # Ignore self-relationship since the table was already # rebuilt. if many_to_many.related_model == model: continue if many_to_many.remote_field.through._meta.auto_created: related_models.add(many_to_many.remote_field.through) for related_model in related_models: self._remake_table(related_model) def _alter_many_to_many(self, model, old_field, new_field, strict): """Alter M2Ms to repoint their to= endpoints.""" if ( old_field.remote_field.through._meta.db_table == new_field.remote_field.through._meta.db_table ): # The field name didn't change, but some options did, so we have to # propagate this altering. self._remake_table( old_field.remote_field.through, alter_fields=[ ( # The field that points to the target model is needed, # so that table can be remade with the new m2m field - # this is m2m_reverse_field_name(). old_field.remote_field.through._meta.get_field( old_field.m2m_reverse_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_reverse_field_name() ), ), ( # The field that points to the model itself is needed, # so that table can be remade with the new self field - # this is m2m_field_name(). old_field.remote_field.through._meta.get_field( old_field.m2m_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_field_name() ), ), ], ) return # Make a new through table self.create_model(new_field.remote_field.through) # Copy the data across self.execute( "INSERT INTO %s (%s) SELECT %s FROM %s" % ( self.quote_name(new_field.remote_field.through._meta.db_table), ", ".join( [ "id", new_field.m2m_column_name(), new_field.m2m_reverse_name(), ] ), ", ".join( [ "id", old_field.m2m_column_name(), old_field.m2m_reverse_name(), ] ), self.quote_name(old_field.remote_field.through._meta.db_table), ) ) # Delete the old through table self.delete_model(old_field.remote_field.through) def add_constraint(self, model, constraint): if isinstance(constraint, UniqueConstraint) and ( constraint.condition or constraint.contains_expressions or constraint.include or constraint.deferrable ): super().add_constraint(model, constraint) else: self._remake_table(model) def remove_constraint(self, model, constraint): if isinstance(constraint, UniqueConstraint) and ( constraint.condition or constraint.contains_expressions or constraint.include or constraint.deferrable ): super().remove_constraint(model, constraint) else: self._remake_table(model) def _collate_sql(self, collation): return "COLLATE " + collation
DatabaseSchemaEditor
python
ray-project__ray
python/ray/data/tests/unit/test_datatype.py
{ "start": 3607, "end": 4474 }
class ____: """Test type checking methods.""" @pytest.mark.parametrize( "datatype,is_arrow,is_numpy,is_python", [ (DataType.from_arrow(pa.int64()), True, False, False), (DataType.from_arrow(pa.string()), True, False, False), (DataType.from_numpy(np.dtype("int32")), False, True, False), (DataType.from_numpy(np.dtype("float64")), False, True, False), (DataType(int), False, False, True), (DataType(str), False, False, True), ], ) def test_type_checkers(self, datatype, is_arrow, is_numpy, is_python): """Test is_arrow_type, is_numpy_type, and is_python_type methods.""" assert datatype.is_arrow_type() == is_arrow assert datatype.is_numpy_type() == is_numpy assert datatype.is_python_type() == is_python
TestDataTypeCheckers
python
zarr-developers__zarr-python
src/zarr/core/dtype/npy/bytes.py
{ "start": 998, "end": 1645 }
class ____(DTypeConfig_V2[str, None]): """ A wrapper around the JSON representation of the ``NullTerminatedBytes`` data type in Zarr V2. The ``name`` field of this class contains the value that would appear under the ``dtype`` field in Zarr V2 array metadata. References ---------- The structure of the ``name`` field is defined in the Zarr V2 [specification document](https://github.com/zarr-developers/zarr-specs/blob/main/docs/v2/v2.0.rst#data-type-encoding). Examples -------- ```python { "name": "|S10", "object_codec_id": None } ``` """
NullterminatedBytesJSON_V2
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_django/DJ008.py
{ "start": 392, "end": 686 }
class ____(Model): new_field = models.CharField(max_length=10) class Meta: verbose_name = "test model" verbose_name_plural = "test models" @property def my_brand_new_property(self): return 1 def my_beautiful_method(self): return 2
TestModel2
python
bokeh__bokeh
src/bokeh/util/compiler.py
{ "start": 4519, "end": 4843 }
class ____(Inline): ''' An implementation for a Bokeh custom model in JavaScript Example: .. code-block:: python class MyExt(Model): __implementation__ = JavaScript(""" <JavaScript code> """) ''' @property def lang(self) -> str: return "javascript"
JavaScript
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py
{ "start": 7563, "end": 10681 }
class ____(StateMigration): """ Migrates legacy per-partition Google Ads state to low code format that includes parent_slice for each customer_id partition. Example input state: { "1234567890": {"segments.date": "2120-10-10"}, "0987654321": {"segments.date": "2120-10-11"} } Example output state: { "states": [ { "partition": { "customer_id": "1234567890", "parent_slice": {"customer_id": "1234567890_parent", "parent_slice": {}}}, "cursor": {"segments.date": "2120-10-10"} }, { "partition": { "customer_id": "0987654321", "parent_slice": {"customer_id": "0987654321_parent", "parent_slice": {}}}, "cursor": {"segments.date": "2120-10-11"} } ], "state": {"segments.date": "2120-10-10"} } """ config: Config customer_client_stream: DefaultStream cursor_field: str = "segments.date" def __init__(self, config: Config, customer_client_stream: DefaultStream, cursor_field: str = "segments.date"): self._config = config self._parent_stream = customer_client_stream self._cursor_field = cursor_field def should_migrate(self, stream_state: Mapping[str, Any]) -> bool: return stream_state and "state" not in stream_state def _read_parent_stream(self) -> Iterable[Record]: for partition in self._parent_stream.generate_partitions(): for record in partition.read(): yield record def migrate(self, stream_state: Mapping[str, Any]) -> Mapping[str, Any]: if not self.should_migrate(stream_state): return stream_state stream_state_values = [ stream_state for stream_state in stream_state.values() if isinstance(stream_state, dict) and self._cursor_field in stream_state ] if not stream_state_values: logger.warning("No valid cursor field found in the stream state. Returning empty state.") return {} min_state = min(stream_state_values, key=lambda state: state[self._cursor_field]) customer_ids_in_state = list(stream_state.keys()) partitions_state = [] for record in self._read_parent_stream(): customer_id = record.data.get("id") if customer_id in customer_ids_in_state: legacy_partition_state = stream_state[customer_id] partitions_state.append( { "partition": { "customer_id": record["clientCustomer"], "parent_slice": {"customer_id": record.associated_slice.get("customer_id"), "parent_slice": {}}, }, "cursor": legacy_partition_state, } ) if not partitions_state: logger.warning("No matching customer clients found during state migration.") return {} state = {"states": partitions_state, "state": min_state} return state @dataclass
GoogleAdsPerPartitionStateMigration
python
pytorch__pytorch
torch/_dynamo/variables/higher_order_ops.py
{ "start": 79184, "end": 81233 }
class ____(TorchHigherOrderOperatorVariable): def __init__(self, hop, source, script_obj_var, method_name) -> None: super().__init__(hop, source) self.script_obj_var = script_obj_var self.method_name = method_name def _call_function( self, tx: "InstructionTranslator", args: list[VariableTracker], kwargs: dict[str, VariableTracker], ) -> VariableTracker: from .builder import wrap_fx_proxy args, kwargs = LazyVariableTracker.realize_all((args, kwargs)) args_proxy = [arg.as_proxy() for arg in args] kwargs_proxy = {k: v.as_proxy() for k, v in kwargs.items()} return wrap_fx_proxy( tx=tx, proxy=tx.output.create_proxy( "call_function", self.value, args=tuple( [self.script_obj_var.as_proxy(), self.method_name] + args_proxy ), kwargs=kwargs_proxy, ), ) def validate_subgraph_output_types(output: VariableTracker): """Verify that that the output of the subgraph is a tensor, int, bool, SymBool, or SymInt. """ from . import TensorVariable if non_tensor_output := find_mismatched_vars( output, TensorVariable, allow_none=True ): for out in non_tensor_output: if ( isinstance(out, SymNodeVariable) and out.python_type() in (int, bool) ) or ( isinstance(out, ConstantVariable) and out.python_type() in (int, bool) ): continue unimplemented( gb_type="HOP body output unsupported", context=f"non-tensor outputs: {non_tensor_output}", explanation="HigherOrderOperator body's output must consist of tensors or ints/bools only " f"but got {out.python_type()}.", hints=[ *graph_break_hints.USER_ERROR, ], )
CallTorchbindHigherOrderVariable
python
google__pytype
pytype/rewrite/abstract/classes_test.py
{ "start": 2849, "end": 3223 }
class ____(test_utils.ContextfulTestBase): def test_get_attribute(self): cls = classes.SimpleClass(self.ctx, 'X', {}) mutable_instance = classes.MutableInstance(self.ctx, cls) mutable_instance.set_attribute('x', self.ctx.consts[3]) instance = mutable_instance.freeze() self.assertEqual(instance.get_attribute('x'), self.ctx.consts[3])
FrozenInstanceTest
python
openai__openai-python
src/openai/types/chat/chat_completion_content_part_input_audio_param.py
{ "start": 254, "end": 488 }
class ____(TypedDict, total=False): data: Required[str] """Base64 encoded audio data.""" format: Required[Literal["wav", "mp3"]] """The format of the encoded audio data. Currently supports "wav" and "mp3"."""
InputAudio
python
langchain-ai__langchain
libs/core/tests/unit_tests/load/test_serializable.py
{ "start": 5145, "end": 10631 }
class ____(Serializable): model_config = ConfigDict(arbitrary_types_allowed=True) content: str non_bool: NonBoolObj @classmethod def is_lc_serializable(cls) -> bool: return True def test_repr() -> None: foo = Foo3( content="repr", non_bool=NonBoolObj(), ) assert repr(foo) == "Foo3(content='repr', non_bool=NonBoolObj)" def test_str() -> None: foo = Foo3( content="str", non_bool=NonBoolObj(), ) assert str(foo) == "content='str' non_bool=NonBoolObj" def test_serialization_with_pydantic() -> None: class MyModel(BaseModel): x: int y: str my_model = MyModel(x=1, y="hello") llm_response = ChatGeneration( message=AIMessage( content='{"x": 1, "y": "hello"}', additional_kwargs={"parsed": my_model} ) ) ser = dumpd(llm_response) deser = load(ser) assert isinstance(deser, ChatGeneration) assert deser.message.content assert deser.message.additional_kwargs["parsed"] == my_model.model_dump() def test_serialization_with_generation() -> None: generation = Generation(text="hello-world") assert dumpd(generation)["kwargs"] == {"text": "hello-world", "type": "Generation"} def test_serialization_with_ignore_unserializable_fields() -> None: data = { "messages": [ [ { "lc": 1, "type": "constructor", "id": ["langchain", "schema", "messages", "AIMessage"], "kwargs": { "content": "Call tools to get entity details", "response_metadata": { "other_field": "foo", "create_date": { "lc": 1, "type": "not_implemented", "id": ["datetime", "datetime"], "repr": "datetime.datetime(2025, 7, 15, 13, 14, 0, 000000, tzinfo=datetime.timezone.utc)", # noqa: E501 }, }, "type": "ai", "id": "00000000-0000-0000-0000-000000000000", }, }, ] ] } ser = dumpd(data) deser = load(ser, ignore_unserializable_fields=True) assert deser == { "messages": [ [ AIMessage( id="00000000-0000-0000-0000-000000000000", content="Call tools to get entity details", response_metadata={ "other_field": "foo", "create_date": None, }, ) ] ] } # Tests for dumps() function def test_dumps_basic_serialization() -> None: """Test basic string serialization with `dumps()`.""" foo = Foo(bar=42, baz="test") json_str = dumps(foo) # Should be valid JSON parsed = json.loads(json_str) assert parsed == { "id": ["tests", "unit_tests", "load", "test_serializable", "Foo"], "kwargs": {"bar": 42, "baz": "test"}, "lc": 1, "type": "constructor", } def test_dumps_pretty_formatting() -> None: """Test pretty printing functionality.""" foo = Foo(bar=1, baz="hello") # Test pretty=True with default indent pretty_json = dumps(foo, pretty=True) assert " " in pretty_json # Test custom indent (4-space) custom_indent = dumps(foo, pretty=True, indent=4) assert " " in custom_indent # Verify it's still valid JSON parsed = json.loads(pretty_json) assert parsed["kwargs"]["bar"] == 1 def test_dumps_invalid_default_kwarg() -> None: """Test that passing `'default'` as kwarg raises ValueError.""" foo = Foo(bar=1, baz="test") with pytest.raises(ValueError, match="`default` should not be passed to dumps"): dumps(foo, default=lambda x: x) def test_dumps_additional_json_kwargs() -> None: """Test that additional JSON kwargs are passed through.""" foo = Foo(bar=1, baz="test") compact_json = dumps(foo, separators=(",", ":")) assert ", " not in compact_json # Should be compact # Test sort_keys sorted_json = dumps(foo, sort_keys=True) parsed = json.loads(sorted_json) assert parsed == dumpd(foo) def test_dumps_non_serializable_object() -> None: """Test `dumps()` behavior with non-serializable objects.""" class NonSerializable: def __init__(self, value: int) -> None: self.value = value obj = NonSerializable(42) json_str = dumps(obj) # Should create a "not_implemented" representation parsed = json.loads(json_str) assert parsed["lc"] == 1 assert parsed["type"] == "not_implemented" assert "NonSerializable" in parsed["repr"] def test_dumps_mixed_data_structure() -> None: """Test `dumps()` with complex nested data structures.""" data = { "serializable": Foo(bar=1, baz="test"), "list": [1, 2, {"nested": "value"}], "primitive": "string", } json_str = dumps(data) parsed = json.loads(json_str) # Serializable object should be properly serialized assert parsed["serializable"]["type"] == "constructor" # Primitives should remain unchanged assert parsed["list"] == [1, 2, {"nested": "value"}] assert parsed["primitive"] == "string"
Foo3
python
huggingface__transformers
src/transformers/models/focalnet/modeling_focalnet.py
{ "start": 17550, "end": 20010 }
class ____(GradientCheckpointingLayer): def __init__(self, config, index, input_resolution): super().__init__() self.config = config self.num_stages = len(config.depths) embed_dim = [config.embed_dim * (2**i) for i in range(self.num_stages)] dim = embed_dim[index] out_dim = embed_dim[index + 1] if (index < self.num_stages - 1) else None downsample = FocalNetPatchEmbeddings if (index < self.num_stages - 1) else None # stochastic depth decay rule dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")] drop_path = dpr[sum(config.depths[:index]) : sum(config.depths[: index + 1])] self.layers = nn.ModuleList( [ FocalNetLayer( config=config, index=index, dim=dim, input_resolution=input_resolution, drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, ) for i in range(config.depths[index]) ] ) if downsample is not None: self.downsample = downsample( config=config, image_size=input_resolution, patch_size=2, num_channels=dim, embed_dim=out_dim, add_norm=True, use_conv_embed=config.use_conv_embed, is_stem=False, ) else: self.downsample = None self.pointing = False def forward(self, hidden_states: torch.Tensor, input_dimensions: tuple[int, int]) -> tuple[torch.Tensor]: height, width = input_dimensions for layer_module in self.layers: hidden_states = layer_module(hidden_states, input_dimensions) hidden_states_before_downsampling = hidden_states if self.downsample is not None: height, width = input_dimensions hidden_states = hidden_states.transpose(1, 2).reshape( hidden_states_before_downsampling.shape[0], -1, height, width ) hidden_states, output_dimensions = self.downsample(hidden_states) else: output_dimensions = (height, width, height, width) stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions) return stage_outputs
FocalNetStage
python
viewflow__viewflow
viewflow/workflow/flow/mixins.py
{ "start": 2747, "end": 3506 }
class ____(metaclass=ViewsetMeta): """Cancel a task action.""" cancel_view_class: Optional[Type[View]] = None @viewprop def cancel_view(self): """View for the admin to cancel a task.""" if self.cancel_view_class: return self.cancel_view_class.as_view() @property def cancel_path(self): if self.cancel_view: return path( f"<int:process_pk>/{self.name}/<int:task_pk>/cancel/", utils.wrap_task_view( self, self.cancel_view, permission=self.can_cancel ), name="cancel", ) def can_cancel(self, user, task): return self.flow_class.instance.has_manage_permission(user)
NodeCancelMixin
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/random/random_binomial_test.py
{ "start": 1381, "end": 8610 }
class ____(test.TestCase): """This is a large test due to the moments computation taking some time.""" def _Sampler( self, num, counts, probs, dtype, gen=None, sample_shape=None, seed=None): def func(): shape = [10 * num] if sample_shape is None else sample_shape generator = gen if gen is not None else ( stateful_random_ops.Generator.from_seed(seed)) return generator.binomial( shape=shape, counts=counts, probs=probs, dtype=dtype) return func @test_util.run_v2_only def testMoments(self): try: from scipy import stats # pylint: disable=g-import-not-at-top except ImportError as e: tf_logging.warn("Cannot test moments: %s", e) return # The moments test is a z-value test. This is the largest z-value # we want to tolerate. Since the z-test approximates a unit normal # distribution, it should almost definitely never exceed 6. z_limit = 6.0 gen = stateful_random_ops.Generator.from_seed(seed=12345) for dt in _SUPPORTED_DTYPES: # Test when n * p > 10, and n * p < 10 for stride in 0, 4, 10: for counts in (1., 10., 22., 50.): for prob in (0.1, 0.5, 0.8): sampler = self._Sampler(int(5e4), counts, prob, dt, gen=gen) z_scores = util.test_moment_matching( # Use float64 samples. self.evaluate(sampler()).astype(np.float64), number_moments=6, dist=stats.binom(counts, prob), stride=stride, ) self.assertAllLess(z_scores, z_limit) @test_util.run_v2_only def testSeed(self): for dt in dtypes.float16, dtypes.float32, dtypes.float64: sx = self._Sampler(1000, counts=10., probs=0.4, dtype=dt, seed=345) sy = self._Sampler(1000, counts=10., probs=0.4, dtype=dt, seed=345) self.assertAllEqual(self.evaluate(sx()), self.evaluate(sy())) def testStateless(self): for dt in dtypes.float16, dtypes.float32, dtypes.float64: sx = stateless_random_ops.stateless_random_binomial( shape=[1000], seed=[12, 34], counts=10., probs=0.4, output_dtype=dt) sy = stateless_random_ops.stateless_random_binomial( shape=[1000], seed=[12, 34], counts=10., probs=0.4, output_dtype=dt) sx0, sx1 = self.evaluate(sx), self.evaluate(sx) sy0, sy1 = self.evaluate(sy), self.evaluate(sy) self.assertAllEqual(sx0, sx1) self.assertAllEqual(sx0, sy0) self.assertAllEqual(sy0, sy1) def testZeroShape(self): rnd = stateful_random_ops.Generator.from_seed(12345).binomial([0], [], []) self.assertEqual([0], rnd.shape.as_list()) def testShape(self): rng = stateful_random_ops.Generator.from_seed(12345) # Scalar parameters. rnd = rng.binomial(shape=[10], counts=np.float32(2.), probs=np.float32(0.5)) self.assertEqual([10], rnd.shape.as_list()) rnd = rng.binomial(shape=[], counts=np.float32(2.), probs=np.float32(0.5)) self.assertEqual([], rnd.shape.as_list()) # Vector parameters. rnd = rng.binomial( shape=[10], counts=array_ops.ones([10], dtype=np.float32), probs=0.3 * array_ops.ones([10], dtype=np.float32)) self.assertEqual([10], rnd.shape.as_list()) rnd = rng.binomial( shape=[5, 2], counts=array_ops.ones([2], dtype=np.float32), probs=0.4 * array_ops.ones([2], dtype=np.float32)) self.assertEqual([5, 2], rnd.shape.as_list()) # Scalar counts, vector probs. rnd = rng.binomial( shape=[10], counts=np.float32(5.), probs=0.8 * array_ops.ones([10], dtype=np.float32)) self.assertEqual([10], rnd.shape.as_list()) # Vector counts, scalar probs. rnd = rng.binomial( shape=[10], counts=array_ops.ones([10], dtype=np.float32), probs=np.float32(0.9)) self.assertEqual([10], rnd.shape.as_list()) # Tensor parameters rnd = rng.binomial( shape=[10, 2, 3], counts=array_ops.ones([2, 1], dtype=np.float32), probs=0.9 * array_ops.ones([1, 3], dtype=np.float32)) self.assertEqual([10, 2, 3], rnd.shape.as_list()) # Tensor parameters rnd = rng.binomial( shape=[10, 2, 3, 5], counts=array_ops.ones([2, 1, 5], dtype=np.float32), probs=0.9 * array_ops.ones([1, 3, 1], dtype=np.float32)) self.assertEqual([10, 2, 3, 5], rnd.shape.as_list()) @test_util.run_v2_only def testCornerCases(self): rng = stateful_random_ops.Generator.from_seed(12345) counts = np.array([5, 5, 5, 0, 0, 0], dtype=np.float32) probs = np.array([0, 1, float("nan"), -10, 10, float("nan")], dtype=np.float32) expected = np.array([0, 5, float("nan"), 0, 0, 0], dtype=np.float32) result = rng.binomial( shape=[6], counts=counts, probs=probs, dtype=np.float32) self.assertAllEqual(expected, self.evaluate(result)) @test_util.run_v2_only def testMomentsForTensorInputs(self): try: from scipy import stats # pylint: disable=g-import-not-at-top except ImportError as e: tf_logging.warn("Cannot test moments: %s", e) return # The moments test is a z-value test. This is the largest z-value # we want to tolerate. Since the z-test approximates a unit normal # distribution, it should almost definitely never exceed 6. z_limit = 6.0 class ScipyBinomialWrapper(object): """Wrapper for stats.binom to support broadcasting.""" def __init__(self, counts, probs): self.counts = counts self.probs = probs def moment(self, i): counts, probs = np.broadcast_arrays(self.counts, self.probs) broadcast_shape = counts.shape counts = np.reshape(counts, (-1,)) probs = np.reshape(probs, (-1,)) counts_and_probs = np.stack([counts, probs], axis=-1) moments = np.fromiter( (stats.binom(cp[0], cp[1]).moment(i) for cp in counts_and_probs), dtype=np.float64) return np.reshape(moments, broadcast_shape) gen = stateful_random_ops.Generator.from_seed(seed=23455) for dt in _SUPPORTED_DTYPES: # Test when n * p > 10, and n * p < 10 for stride in 0, 4, 10: counts = np.float64(np.random.randint(low=1, high=20, size=(2, 1, 4))) probs = np.random.uniform(size=(1, 3, 4)) sampler = self._Sampler( int(5e4), counts, probs, dt, gen=gen, sample_shape=[10 * int(5e4), 2, 3, 4]) # Use float64 samples. samples = self.evaluate(sampler()).astype(np.float64) z_scores = util.test_moment_matching( samples, number_moments=6, dist=ScipyBinomialWrapper(counts, probs), stride=stride, ) self.assertAllLess(z_scores, z_limit) def testStatelessDtypeInt64(self): srb = stateless_random_ops.stateless_random_binomial( shape=[constant_op.constant(1, dtype=dtypes.int64)], seed=[12, 34], counts=10.0, probs=0.4, output_dtype=dtypes.float16) out = self.evaluate(srb) self.assertEqual(out, [5.0]) if __name__ == "__main__": test.main()
RandomBinomialTest
python
pandas-dev__pandas
pandas/tests/series/test_cumulative.py
{ "start": 333, "end": 9954 }
class ____: @pytest.mark.parametrize("func", [np.cumsum, np.cumprod]) def test_datetime_series(self, datetime_series, func): tm.assert_numpy_array_equal( func(datetime_series).values, func(np.array(datetime_series)), check_dtype=True, ) # with missing values ts = datetime_series.copy() ts[::2] = np.nan result = func(ts)[1::2] expected = func(np.array(ts.dropna())) tm.assert_numpy_array_equal(result.values, expected, check_dtype=False) @pytest.mark.parametrize("method", ["cummin", "cummax"]) def test_cummin_cummax(self, datetime_series, method): ufunc = methods[method] result = getattr(datetime_series, method)().values expected = ufunc(np.array(datetime_series)) tm.assert_numpy_array_equal(result, expected) ts = datetime_series.copy() ts[::2] = np.nan result = getattr(ts, method)()[1::2] expected = ufunc(ts.dropna()) result.index = result.index._with_freq(None) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "ts", [ pd.Timedelta(0), pd.Timestamp("1999-12-31"), pd.Timestamp("1999-12-31").tz_localize("US/Pacific"), ], ) @pytest.mark.parametrize( "method, skipna, exp_tdi", [ ["cummax", True, ["NaT", "2 days", "NaT", "2 days", "NaT", "3 days"]], ["cummin", True, ["NaT", "2 days", "NaT", "1 days", "NaT", "1 days"]], [ "cummax", False, ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT"], ], [ "cummin", False, ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT"], ], ], ) def test_cummin_cummax_datetimelike(self, ts, method, skipna, exp_tdi): # with ts==pd.Timedelta(0), we are testing td64; with naive Timestamp # we are testing datetime64[ns]; with Timestamp[US/Pacific] # we are testing dt64tz tdi = pd.to_timedelta(["NaT", "2 days", "NaT", "1 days", "NaT", "3 days"]) ser = pd.Series(tdi + ts) exp_tdi = pd.to_timedelta(exp_tdi) expected = pd.Series(exp_tdi + ts) result = getattr(ser, method)(skipna=skipna) tm.assert_series_equal(expected, result) def test_cumsum_datetimelike(self): # GH#57956 df = pd.DataFrame( [ [pd.Timedelta(0), pd.Timedelta(days=1)], [pd.Timedelta(days=2), pd.NaT], [pd.Timedelta(hours=-6), pd.Timedelta(hours=12)], ] ) result = df.cumsum() expected = pd.DataFrame( [ [pd.Timedelta(0), pd.Timedelta(days=1)], [pd.Timedelta(days=2), pd.NaT], [pd.Timedelta(days=1, hours=18), pd.Timedelta(days=1, hours=12)], ] ) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "func, exp", [ ("cummin", "2012-1-1"), ("cummax", "2012-1-2"), ], ) def test_cummin_cummax_period(self, func, exp): # GH#28385 ser = pd.Series( [pd.Period("2012-1-1", freq="D"), pd.NaT, pd.Period("2012-1-2", freq="D")] ) result = getattr(ser, func)(skipna=False) expected = pd.Series([pd.Period("2012-1-1", freq="D"), pd.NaT, pd.NaT]) tm.assert_series_equal(result, expected) result = getattr(ser, func)(skipna=True) exp = pd.Period(exp, freq="D") expected = pd.Series([pd.Period("2012-1-1", freq="D"), pd.NaT, exp]) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "arg", [ [False, False, False, True, True, False, False], [False, False, False, False, False, False, False], ], ) @pytest.mark.parametrize( "func", [lambda x: x, lambda x: ~x], ids=["identity", "inverse"] ) @pytest.mark.parametrize("method", methods.keys()) def test_cummethods_bool(self, arg, func, method): # GH#6270 # checking Series method vs the ufunc applied to the values ser = func(pd.Series(arg)) ufunc = methods[method] exp_vals = ufunc(ser.values) expected = pd.Series(exp_vals) result = getattr(ser, method)() tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "method, expected", [ ["cumsum", pd.Series([0, 1, np.nan, 1], dtype=object)], ["cumprod", pd.Series([False, 0, np.nan, 0])], ["cummin", pd.Series([False, False, np.nan, False])], ["cummax", pd.Series([False, True, np.nan, True])], ], ) def test_cummethods_bool_in_object_dtype(self, method, expected): ser = pd.Series([False, True, np.nan, False]) result = getattr(ser, method)() tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "method, order", [ ["cummax", "abc"], ["cummin", "cba"], ], ) def test_cummax_cummin_on_ordered_categorical(self, method, order): # GH#52335 cat = pd.CategoricalDtype(list(order), ordered=True) ser = pd.Series( list("ababcab"), dtype=cat, ) result = getattr(ser, method)() expected = pd.Series( list("abbbccc"), dtype=cat, ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "skip, exp", [ [True, ["a", np.nan, "b", "b", "c"]], [False, ["a", np.nan, np.nan, np.nan, np.nan]], ], ) @pytest.mark.parametrize( "method, order", [ ["cummax", "abc"], ["cummin", "cba"], ], ) def test_cummax_cummin_ordered_categorical_nan(self, skip, exp, method, order): # GH#52335 cat = pd.CategoricalDtype(list(order), ordered=True) ser = pd.Series( ["a", np.nan, "b", "a", "c"], dtype=cat, ) result = getattr(ser, method)(skipna=skip) expected = pd.Series( exp, dtype=cat, ) tm.assert_series_equal( result, expected, ) def test_cumprod_timedelta(self): # GH#48111 ser = pd.Series([pd.Timedelta(days=1), pd.Timedelta(days=3)]) with pytest.raises(TypeError, match="cumprod not supported for Timedelta"): ser.cumprod() @pytest.mark.parametrize( "data, op, skipna, expected_data", [ ([], "cumsum", True, []), ([], "cumsum", False, []), (["x", "z", "y"], "cumsum", True, ["x", "xz", "xzy"]), (["x", "z", "y"], "cumsum", False, ["x", "xz", "xzy"]), (["x", pd.NA, "y"], "cumsum", True, ["x", pd.NA, "xy"]), (["x", pd.NA, "y"], "cumsum", False, ["x", pd.NA, pd.NA]), ([pd.NA, "x", "y"], "cumsum", True, [pd.NA, "x", "xy"]), ([pd.NA, "x", "y"], "cumsum", False, [pd.NA, pd.NA, pd.NA]), ([pd.NA, pd.NA, pd.NA], "cumsum", True, [pd.NA, pd.NA, pd.NA]), ([pd.NA, pd.NA, pd.NA], "cumsum", False, [pd.NA, pd.NA, pd.NA]), ([], "cummin", True, []), ([], "cummin", False, []), (["y", "z", "x"], "cummin", True, ["y", "y", "x"]), (["y", "z", "x"], "cummin", False, ["y", "y", "x"]), (["y", pd.NA, "x"], "cummin", True, ["y", pd.NA, "x"]), (["y", pd.NA, "x"], "cummin", False, ["y", pd.NA, pd.NA]), ([pd.NA, "y", "x"], "cummin", True, [pd.NA, "y", "x"]), ([pd.NA, "y", "x"], "cummin", False, [pd.NA, pd.NA, pd.NA]), ([pd.NA, pd.NA, pd.NA], "cummin", True, [pd.NA, pd.NA, pd.NA]), ([pd.NA, pd.NA, pd.NA], "cummin", False, [pd.NA, pd.NA, pd.NA]), ([], "cummax", True, []), ([], "cummax", False, []), (["x", "z", "y"], "cummax", True, ["x", "z", "z"]), (["x", "z", "y"], "cummax", False, ["x", "z", "z"]), (["x", pd.NA, "y"], "cummax", True, ["x", pd.NA, "y"]), (["x", pd.NA, "y"], "cummax", False, ["x", pd.NA, pd.NA]), ([pd.NA, "x", "y"], "cummax", True, [pd.NA, "x", "y"]), ([pd.NA, "x", "y"], "cummax", False, [pd.NA, pd.NA, pd.NA]), ([pd.NA, pd.NA, pd.NA], "cummax", True, [pd.NA, pd.NA, pd.NA]), ([pd.NA, pd.NA, pd.NA], "cummax", False, [pd.NA, pd.NA, pd.NA]), ], ) def test_cum_methods_ea_strings( self, string_dtype_no_object, data, op, skipna, expected_data ): # https://github.com/pandas-dev/pandas/pull/60633 - pyarrow # https://github.com/pandas-dev/pandas/pull/60938 - Python ser = pd.Series(data, dtype=string_dtype_no_object) method = getattr(ser, op) expected = pd.Series(expected_data, dtype=string_dtype_no_object) result = method(skipna=skipna) tm.assert_series_equal(result, expected) def test_cumprod_pyarrow_strings(self, pyarrow_string_dtype, skipna): # https://github.com/pandas-dev/pandas/pull/60633 ser = pd.Series(list("xyz"), dtype=pyarrow_string_dtype) msg = re.escape(f"operation 'cumprod' not supported for dtype '{ser.dtype}'") with pytest.raises(TypeError, match=msg): ser.cumprod(skipna=skipna)
TestSeriesCumulativeOps
python
sympy__sympy
sympy/polys/polyclasses.py
{ "start": 91123, "end": 102749 }
class ____(PicklableWithSlots, CantSympify): """Dense Multivariate Fractions over `K`. """ __slots__ = ('num', 'den', 'lev', 'dom') def __init__(self, rep, dom, lev=None): num, den, lev = self._parse(rep, dom, lev) num, den = dmp_cancel(num, den, lev, dom) self.num = num self.den = den self.lev = lev self.dom = dom @classmethod def new(cls, rep, dom, lev=None): num, den, lev = cls._parse(rep, dom, lev) obj = object.__new__(cls) obj.num = num obj.den = den obj.lev = lev obj.dom = dom return obj def ground_new(self, rep): return self.new(rep, self.dom, self.lev) @classmethod def _parse(cls, rep, dom, lev=None): if isinstance(rep, tuple): num, den = rep if lev is not None: if isinstance(num, dict): num = dmp_from_dict(num, lev, dom) if isinstance(den, dict): den = dmp_from_dict(den, lev, dom) else: num, num_lev = dmp_validate(num, dom) den, den_lev = dmp_validate(den, dom) if num_lev == den_lev: lev = num_lev else: raise ValueError('inconsistent number of levels') if dmp_zero_p(den, lev): raise ZeroDivisionError('fraction denominator') if dmp_zero_p(num, lev): den = dmp_one(lev, dom) else: if dmp_negative_p(den, lev, dom): num = dmp_neg(num, lev, dom) den = dmp_neg(den, lev, dom) else: num = rep if lev is not None: if isinstance(num, dict): num = dmp_from_dict(num, lev, dom) elif not isinstance(num, list): num = dmp_ground(dom.convert(num), lev, dom) else: num, lev = dmp_validate(num, dom) den = dmp_one(lev, dom) return num, den, lev def __repr__(f): return "%s((%s, %s), %s)" % (f.__class__.__name__, f.num, f.den, f.dom) def __hash__(f): return hash((f.__class__.__name__, dmp_to_tuple(f.num, f.lev), dmp_to_tuple(f.den, f.lev), f.lev, f.dom)) def poly_unify(f, g): """Unify a multivariate fraction and a polynomial. """ if not isinstance(g, DMP) or f.lev != g.lev: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if f.dom == g.dom: return (f.lev, f.dom, f.per, (f.num, f.den), g._rep) else: lev, dom = f.lev, f.dom.unify(g.dom) F = (dmp_convert(f.num, lev, f.dom, dom), dmp_convert(f.den, lev, f.dom, dom)) G = dmp_convert(g._rep, lev, g.dom, dom) def per(num, den, cancel=True, kill=False, lev=lev): if kill: if not lev: return num/den else: lev = lev - 1 if cancel: num, den = dmp_cancel(num, den, lev, dom) return f.__class__.new((num, den), dom, lev) return lev, dom, per, F, G def frac_unify(f, g): """Unify representations of two multivariate fractions. """ if not isinstance(g, DMF) or f.lev != g.lev: raise UnificationFailed("Cannot unify %s with %s" % (f, g)) if f.dom == g.dom: return (f.lev, f.dom, f.per, (f.num, f.den), (g.num, g.den)) else: lev, dom = f.lev, f.dom.unify(g.dom) F = (dmp_convert(f.num, lev, f.dom, dom), dmp_convert(f.den, lev, f.dom, dom)) G = (dmp_convert(g.num, lev, g.dom, dom), dmp_convert(g.den, lev, g.dom, dom)) def per(num, den, cancel=True, kill=False, lev=lev): if kill: if not lev: return num/den else: lev = lev - 1 if cancel: num, den = dmp_cancel(num, den, lev, dom) return f.__class__.new((num, den), dom, lev) return lev, dom, per, F, G def per(f, num, den, cancel=True, kill=False): """Create a DMF out of the given representation. """ lev, dom = f.lev, f.dom if kill: if not lev: return num/den else: lev -= 1 if cancel: num, den = dmp_cancel(num, den, lev, dom) return f.__class__.new((num, den), dom, lev) def half_per(f, rep, kill=False): """Create a DMP out of the given representation. """ lev = f.lev if kill: if not lev: return rep else: lev -= 1 return DMP(rep, f.dom, lev) @classmethod def zero(cls, lev, dom): return cls.new(0, dom, lev) @classmethod def one(cls, lev, dom): return cls.new(1, dom, lev) def numer(f): """Returns the numerator of ``f``. """ return f.half_per(f.num) def denom(f): """Returns the denominator of ``f``. """ return f.half_per(f.den) def cancel(f): """Remove common factors from ``f.num`` and ``f.den``. """ return f.per(f.num, f.den) def neg(f): """Negate all coefficients in ``f``. """ return f.per(dmp_neg(f.num, f.lev, f.dom), f.den, cancel=False) def add_ground(f, c): """Add an element of the ground domain to ``f``. """ return f + f.ground_new(c) def add(f, g): """Add two multivariate fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = dmp_add_mul(F_num, F_den, G, lev, dom), F_den else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_add(dmp_mul(F_num, G_den, lev, dom), dmp_mul(F_den, G_num, lev, dom), lev, dom) den = dmp_mul(F_den, G_den, lev, dom) return per(num, den) def sub(f, g): """Subtract two multivariate fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = dmp_sub_mul(F_num, F_den, G, lev, dom), F_den else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_sub(dmp_mul(F_num, G_den, lev, dom), dmp_mul(F_den, G_num, lev, dom), lev, dom) den = dmp_mul(F_den, G_den, lev, dom) return per(num, den) def mul(f, g): """Multiply two multivariate fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = dmp_mul(F_num, G, lev, dom), F_den else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_mul(F_num, G_num, lev, dom) den = dmp_mul(F_den, G_den, lev, dom) return per(num, den) def pow(f, n): """Raise ``f`` to a non-negative power ``n``. """ if isinstance(n, int): num, den = f.num, f.den if n < 0: num, den, n = den, num, -n return f.per(dmp_pow(num, n, f.lev, f.dom), dmp_pow(den, n, f.lev, f.dom), cancel=False) else: raise TypeError("``int`` expected, got %s" % type(n)) def quo(f, g): """Computes quotient of fractions ``f`` and ``g``. """ if isinstance(g, DMP): lev, dom, per, (F_num, F_den), G = f.poly_unify(g) num, den = F_num, dmp_mul(F_den, G, lev, dom) else: lev, dom, per, F, G = f.frac_unify(g) (F_num, F_den), (G_num, G_den) = F, G num = dmp_mul(F_num, G_den, lev, dom) den = dmp_mul(F_den, G_num, lev, dom) return per(num, den) exquo = quo def invert(f, check=True): """Computes inverse of a fraction ``f``. """ return f.per(f.den, f.num, cancel=False) @property def is_zero(f): """Returns ``True`` if ``f`` is a zero fraction. """ return dmp_zero_p(f.num, f.lev) @property def is_one(f): """Returns ``True`` if ``f`` is a unit fraction. """ return dmp_one_p(f.num, f.lev, f.dom) and \ dmp_one_p(f.den, f.lev, f.dom) def __pos__(f): return f def __neg__(f): return f.neg() def __add__(f, g): if isinstance(g, (DMP, DMF)): return f.add(g) elif g in f.dom: return f.add_ground(f.dom.convert(g)) try: return f.add(f.half_per(g)) except (TypeError, CoercionFailed, NotImplementedError): return NotImplemented def __radd__(f, g): return f.__add__(g) def __sub__(f, g): if isinstance(g, (DMP, DMF)): return f.sub(g) try: return f.sub(f.half_per(g)) except (TypeError, CoercionFailed, NotImplementedError): return NotImplemented def __rsub__(f, g): return (-f).__add__(g) def __mul__(f, g): if isinstance(g, (DMP, DMF)): return f.mul(g) try: return f.mul(f.half_per(g)) except (TypeError, CoercionFailed, NotImplementedError): return NotImplemented def __rmul__(f, g): return f.__mul__(g) def __pow__(f, n): return f.pow(n) def __truediv__(f, g): if isinstance(g, (DMP, DMF)): return f.quo(g) try: return f.quo(f.half_per(g)) except (TypeError, CoercionFailed, NotImplementedError): return NotImplemented def __rtruediv__(self, g): return self.invert(check=False)*g def __eq__(f, g): try: if isinstance(g, DMP): _, _, _, (F_num, F_den), G = f.poly_unify(g) if f.lev == g.lev: return dmp_one_p(F_den, f.lev, f.dom) and F_num == G else: _, _, _, F, G = f.frac_unify(g) if f.lev == g.lev: return F == G except UnificationFailed: pass return False def __ne__(f, g): try: if isinstance(g, DMP): _, _, _, (F_num, F_den), G = f.poly_unify(g) if f.lev == g.lev: return not (dmp_one_p(F_den, f.lev, f.dom) and F_num == G) else: _, _, _, F, G = f.frac_unify(g) if f.lev == g.lev: return F != G except UnificationFailed: pass return True def __lt__(f, g): _, _, _, F, G = f.frac_unify(g) return F < G def __le__(f, g): _, _, _, F, G = f.frac_unify(g) return F <= G def __gt__(f, g): _, _, _, F, G = f.frac_unify(g) return F > G def __ge__(f, g): _, _, _, F, G = f.frac_unify(g) return F >= G def __bool__(f): return not dmp_zero_p(f.num, f.lev) def init_normal_ANP(rep, mod, dom): return ANP(dup_normal(rep, dom), dup_normal(mod, dom), dom)
DMF
python
scrapy__scrapy
tests/AsyncCrawlerProcess/multi.py
{ "start": 63, "end": 309 }
class ____(scrapy.Spider): name = "no_request" async def start(self): return yield process = AsyncCrawlerProcess(settings={}) process.crawl(NoRequestsSpider) process.crawl(NoRequestsSpider) process.start()
NoRequestsSpider
python
Unity-Technologies__ml-agents
ml-agents-envs/mlagents_envs/side_channel/default_training_analytics_side_channel.py
{ "start": 346, "end": 1835 }
class ____(SideChannel): """ Side channel that sends information about the training to the Unity environment so it can be logged. """ CHANNEL_ID = uuid.UUID("b664a4a9-d86f-5a5f-95cb-e8353a7e8356") def __init__(self) -> None: # >>> uuid.uuid5(uuid.NAMESPACE_URL, "com.unity.ml-agents/TrainingAnalyticsSideChannel") # UUID('b664a4a9-d86f-5a5f-95cb-e8353a7e8356') # We purposefully use the SAME side channel as the TrainingAnalyticsSideChannel super().__init__(DefaultTrainingAnalyticsSideChannel.CHANNEL_ID) def on_message_received(self, msg: IncomingMessage) -> None: raise UnityCommunicationException( "The DefaultTrainingAnalyticsSideChannel received a message from Unity, " + "this should not have happened." ) def environment_initialized(self) -> None: # Tuple of (major, minor, patch) vi = sys.version_info msg = TrainingEnvironmentInitialized( python_version=f"{vi[0]}.{vi[1]}.{vi[2]}", mlagents_version="Custom", mlagents_envs_version=mlagents_envs.__version__, torch_version="Unknown", torch_device_type="Unknown", ) any_message = Any() any_message.Pack(msg) env_init_msg = OutgoingMessage() env_init_msg.set_raw_bytes(any_message.SerializeToString()) # type: ignore super().queue_message_to_send(env_init_msg)
DefaultTrainingAnalyticsSideChannel
python
pypa__pipenv
pipenv/patched/pip/_internal/index/package_finder.py
{ "start": 3987, "end": 12922 }
class ____: """ Responsible for evaluating links for a particular project. """ _py_version_re = re.compile(r"-py([123]\.?[0-9]?)$") # Don't include an allow_yanked default value to make sure each call # site considers whether yanked releases are allowed. This also causes # that decision to be made explicit in the calling code, which helps # people when reading the code. def __init__( self, project_name: str, canonical_name: str, formats: FrozenSet[str], target_python: TargetPython, allow_yanked: bool, ignore_requires_python: Optional[bool] = None, ignore_compatibility: Optional[bool] = None, ) -> None: """ :param project_name: The user supplied package name. :param canonical_name: The canonical package name. :param formats: The formats allowed for this package. Should be a set with 'binary' or 'source' or both in it. :param target_python: The target Python interpreter to use when evaluating link compatibility. This is used, for example, to check wheel compatibility, as well as when checking the Python version, e.g. the Python version embedded in a link filename (or egg fragment) and against an HTML link's optional PEP 503 "data-requires-python" attribute. :param allow_yanked: Whether files marked as yanked (in the sense of PEP 592) are permitted to be candidates for install. :param ignore_requires_python: Whether to ignore incompatible PEP 503 "data-requires-python" values in HTML links. Defaults to False. :param ignore_compatibility: Whether to ignore compatibility of python versions and allow all versions of packages. """ if ignore_requires_python is None: ignore_requires_python = False self._allow_yanked = allow_yanked self._canonical_name = canonical_name self._ignore_requires_python = ignore_requires_python self._formats = formats self._target_python = target_python self._ignore_compatibility = ignore_compatibility self.project_name = project_name def evaluate_link(self, link: Link) -> Tuple[LinkType, str]: """ Determine whether a link is a candidate for installation. :return: A tuple (result, detail), where *result* is an enum representing whether the evaluation found a candidate, or the reason why one is not found. If a candidate is found, *detail* will be the candidate's version string; if one is not found, it contains the reason the link fails to qualify. """ version = None if link.is_yanked and not self._allow_yanked: reason = link.yanked_reason or "<none given>" return (LinkType.yanked, f"yanked for reason: {reason}") if link.egg_fragment: egg_info = link.egg_fragment ext = link.ext else: egg_info, ext = link.splitext() if not ext: return (LinkType.format_unsupported, "not a file") if ext not in SUPPORTED_EXTENSIONS: return ( LinkType.format_unsupported, f"unsupported archive format: {ext}", ) if "binary" not in self._formats and ext == WHEEL_EXTENSION and not self._ignore_compatibility: reason = f"No binaries permitted for {self.project_name}" return (LinkType.format_unsupported, reason) if "macosx10" in link.path and ext == ".zip" and not self._ignore_compatibility: return (LinkType.format_unsupported, "macosx10 one") if ext == WHEEL_EXTENSION: try: wheel = Wheel(link.filename) except InvalidWheelFilename: return ( LinkType.format_invalid, "invalid wheel filename", ) if canonicalize_name(wheel.name) != self._canonical_name: reason = f"wrong project name (not {self.project_name})" return (LinkType.different_project, reason) supported_tags = self._target_python.get_unsorted_tags() if not wheel.supported(supported_tags) and not self._ignore_compatibility: # Include the wheel's tags in the reason string to # simplify troubleshooting compatibility issues. file_tags = ", ".join(wheel.get_formatted_file_tags()) reason = ( f"none of the wheel's tags ({file_tags}) are compatible " f"(run pip debug --verbose to show compatible tags)" ) return (LinkType.platform_mismatch, reason) version = wheel.version # This should be up by the self.ok_binary check, but see issue 2700. if "source" not in self._formats and ext != WHEEL_EXTENSION: reason = f"No sources permitted for {self.project_name}" return (LinkType.format_unsupported, reason) if not version: version = _extract_version_from_fragment( egg_info, self._canonical_name, ) if not version: reason = f"Missing project version for {self.project_name}" return (LinkType.format_invalid, reason) match = self._py_version_re.search(version) if match: version = version[: match.start()] py_version = match.group(1) if py_version != self._target_python.py_version: return ( LinkType.platform_mismatch, "Python version is incorrect", ) supports_python = _check_link_requires_python( link, version_info=self._target_python.py_version_info, ignore_requires_python=self._ignore_requires_python, ) if not supports_python and not self._ignore_compatibility: reason = f"{version} Requires-Python {link.requires_python}" return (LinkType.requires_python_mismatch, reason) logger.debug("Found link %s, version: %s", link, version) return (LinkType.candidate, version) def filter_unallowed_hashes( candidates: List[InstallationCandidate], hashes: Optional[Hashes], project_name: str, ) -> List[InstallationCandidate]: """ Filter out candidates whose hashes aren't allowed, and return a new list of candidates. If at least one candidate has an allowed hash, then all candidates with either an allowed hash or no hash specified are returned. Otherwise, the given candidates are returned. Including the candidates with no hash specified when there is a match allows a warning to be logged if there is a more preferred candidate with no hash specified. Returning all candidates in the case of no matches lets pip report the hash of the candidate that would otherwise have been installed (e.g. permitting the user to more easily update their requirements file with the desired hash). """ if not hashes: logger.debug( "Given no hashes to check %s links for project %r: " "discarding no candidates", len(candidates), project_name, ) # Make sure we're not returning back the given value. return list(candidates) matches_or_no_digest = [] # Collect the non-matches for logging purposes. non_matches = [] match_count = 0 for candidate in candidates: link = candidate.link if not link.has_hash: pass elif link.is_hash_allowed(hashes=hashes): match_count += 1 else: non_matches.append(candidate) continue matches_or_no_digest.append(candidate) if match_count: filtered = matches_or_no_digest else: # Make sure we're not returning back the given value. filtered = list(candidates) if len(filtered) == len(candidates): discard_message = "discarding no candidates" else: discard_message = "discarding {} non-matches:\n {}".format( len(non_matches), "\n ".join(str(candidate.link) for candidate in non_matches), ) logger.debug( "Checked %s links for project %r against %s hashes " "(%s matches, %s no digest): %s", len(candidates), project_name, hashes.digest_count, match_count, len(matches_or_no_digest) - match_count, discard_message, ) return filtered @dataclass
LinkEvaluator
python
PyCQA__pylint
tests/test_check_parallel.py
{ "start": 2700, "end": 4673 }
class ____(BaseRawFileChecker): """A checker that does need to consolidate data. To simulate the need to consolidate data, this checker only reports a message for pairs of files. On non-parallel builds: it works on all the files in a single run. On parallel builds: ``lint.parallel`` calls ``open`` once per file. So if files are treated by separate processes, no messages will be raised from the individual process, all messages will be raised from reduce_map_data. """ name = "parallel-checker" test_data = "parallel" msgs = { "R9999": ( "Test %s", "parallel-test-check", "Some helpful text.", ) } def __init__(self, linter: PyLinter) -> None: super().__init__(linter) self.data: list[str] = [] self.linter = linter def open(self) -> None: """Init the checkers: reset statistics information.""" self.linter.stats.reset_node_count() self.data = [] def close(self) -> None: for _ in self.data[1::2]: # Work on pairs of files, see class docstring. self.add_message("R9999", args=("From process_module, two files seen.",)) def get_map_data(self) -> list[str]: return self.data def reduce_map_data(self, linter: PyLinter, data: list[list[str]]) -> None: recombined = type(self)(linter) recombined.open() aggregated = [] for d in data: aggregated.extend(d) for _ in aggregated[1::2]: # Work on pairs of files, see class docstring. self.add_message("R9999", args=("From reduce_map_data",)) recombined.close() def process_module(self, node: nodes.Module) -> None: """Called once per stream/file/astroid object.""" # record the number of invocations with the data object record = self.test_data + str(len(self.data)) self.data.append(record)
ParallelTestChecker
python
sympy__sympy
sympy/simplify/hyperexpand.py
{ "start": 40651, "end": 40919 }
class ____(Operator): """ Decrement a lower a index. """ def __init__(self, bi): bi = sympify(bi) self._poly = Poly(bi - 1 - _x, _x) def __str__(self): return '<Decrement lower a=%s.>' % (self._poly.all_coeffs()[1] + 1)
MeijerShiftD
python
tensorflow__tensorflow
tensorflow/examples/speech_commands/wav_to_features_test.py
{ "start": 934, "end": 3102 }
class ____(test.TestCase): def _getWavData(self): with self.cached_session(): sample_data = tf.zeros([32000, 2]) wav_encoder = tf.audio.encode_wav(sample_data, 16000) wav_data = self.evaluate(wav_encoder) return wav_data def _saveTestWavFile(self, filename, wav_data): with open(filename, "wb") as f: f.write(wav_data) def _saveWavFolders(self, root_dir, labels, how_many): wav_data = self._getWavData() for label in labels: dir_name = os.path.join(root_dir, label) os.mkdir(dir_name) for i in range(how_many): file_path = os.path.join(dir_name, "some_audio_%d.wav" % i) self._saveTestWavFile(file_path, wav_data) @test_util.run_deprecated_v1 def testWavToFeatures(self): tmp_dir = self.get_temp_dir() wav_dir = os.path.join(tmp_dir, "wavs") os.mkdir(wav_dir) self._saveWavFolders(wav_dir, ["a", "b", "c"], 100) input_file_path = os.path.join(tmp_dir, "input.wav") output_file_path = os.path.join(tmp_dir, "output.c") wav_data = self._getWavData() self._saveTestWavFile(input_file_path, wav_data) wav_to_features.wav_to_features(16000, 1000, 10, 10, 40, True, "average", input_file_path, output_file_path) with open(output_file_path, "rb") as f: content = f.read() self.assertIn(b"const unsigned char g_input_data", content) @test_util.run_deprecated_v1 def testWavToFeaturesMicro(self): tmp_dir = self.get_temp_dir() wav_dir = os.path.join(tmp_dir, "wavs") os.mkdir(wav_dir) self._saveWavFolders(wav_dir, ["a", "b", "c"], 100) input_file_path = os.path.join(tmp_dir, "input.wav") output_file_path = os.path.join(tmp_dir, "output.c") wav_data = self._getWavData() self._saveTestWavFile(input_file_path, wav_data) wav_to_features.wav_to_features(16000, 1000, 10, 10, 40, True, "micro", input_file_path, output_file_path) with open(output_file_path, "rb") as f: content = f.read() self.assertIn(b"const unsigned char g_input_data", content) if __name__ == "__main__": test.main()
WavToFeaturesTest
python
eth-brownie__brownie
brownie/_gui/root.py
{ "start": 412, "end": 2702 }
class ____(tk.Tk): _active = False def __init__(self): projects = get_loaded_projects() if self._active: raise SystemError("GUI is already active") if not projects: raise SystemError("No project loaded") if len(projects) > 1: raise SystemError("More than one active project") Root._active = True self.active_project = projects[0] self.pcMap = {} self.report_key = None self.highlight_key = None self.reports = {} for path in self.active_project._path.glob("reports/*.json"): try: with path.open() as fp: self.reports[path.stem] = ujson_load(fp) except Exception: continue super().__init__(className=f" Brownie GUI - {self.active_project._name}") self.bind("<Escape>", lambda k: self.destroy()) # geometry and styling self.columnconfigure(0, weight=1) self.rowconfigure(0, minsize=30) self.rowconfigure(1, weight=1) set_style(self) # main widgets self.main = MainFrame(self) self.main.grid(row=1, column=0, sticky="nsew") # toolbar widgets self.toolbar = ToolbarFrame(self, self.active_project) self.toolbar.grid(row=0, column=0, sticky="nsew") @property def active_report(self): return self.reports[self.report_key]["highlights"] def set_active_contract(self, contract_name): build_json = self.active_project._build.get(contract_name) self.pathMap = pathMap = build_json["allSourcePaths"] self.main.note.set_visible(sorted(pathMap.values())) self.main.note.set_active(build_json["sourcePath"]) pcMap = build_json["pcMap"] self.main.oplist.set_opcodes(pcMap) self.pcMap = {str(k): pcMap[k] for k in pcMap} for value in (v for v in pcMap.values() if "path" in v): value_path = value["path"] if value_path not in pathMap: value_path = pathMap[value_path] self.toolbar.report.show() self.toolbar.report.set_values(contract_name) def destroy(self): super().destroy() self.quit() Root._active = False
Root
python
facebookresearch__faiss
tests/test_referenced_objects.py
{ "start": 2603, "end": 2994 }
class ____(unittest.TestCase): def test_binary_ivf(self): index = faiss.IndexBinaryIVF(faiss.IndexBinaryFlat(dbin), dbin, 10) gc.collect() index.train(xtbin) def test_wrap(self): index = faiss.IndexBinaryFromFloat(faiss.IndexFlatL2(dbin)) gc.collect() index.add(xbbin) if __name__ == '__main__': unittest.main()
TestReferencedBinary
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/mssql/base.py
{ "start": 79488, "end": 80914 }
class ____(MSSQLCompiler): """A subclass of MSSQLCompiler which disables the usage of bind parameters where not allowed natively by MS-SQL. A dialect may use this compiler on a platform where native binds are used. """ ansi_bind_rules = True def visit_in_op_binary(self, binary, operator, **kw): kw["literal_execute"] = True return "%s IN %s" % ( self.process(binary.left, **kw), self.process(binary.right, **kw), ) def visit_not_in_op_binary(self, binary, operator, **kw): kw["literal_execute"] = True return "%s NOT IN %s" % ( self.process(binary.left, **kw), self.process(binary.right, **kw), ) def render_literal_value(self, value, type_): """ For date and datetime values, convert to a string format acceptable to MSSQL. That seems to be the so-called ODBC canonical date format which looks like this: yyyy-mm-dd hh:mi:ss.mmm(24h) For other data types, call the base class implementation. """ # datetime and date are both subclasses of datetime.date if issubclass(type(value), datetime.date): # SQL Server wants single quotes around the date string. return "'" + str(value) + "'" else: return super().render_literal_value(value, type_)
MSSQLStrictCompiler
python
keras-team__keras
guides/making_new_layers_and_models_via_subclassing.py
{ "start": 7334, "end": 7932 }
class ____(keras.layers.Layer): ... def call(self, inputs): return torch.matmul(inputs, self.w) + self.b ``` Because cross-backend compatibility is a tremendously useful property, we strongly recommend that you seek to always make your layers backend-agnostic by leveraging only Keras APIs. """ """ ## The `add_loss()` method When writing the `call()` method of a layer, you can create loss tensors that you will want to use later, when writing your training loop. This is doable by calling `self.add_loss(value)`: """ # A layer that creates an activity regularization loss
Linear
python
doocs__leetcode
solution/1100-1199/1171.Remove Zero Sum Consecutive Nodes from Linked List/Solution.py
{ "start": 151, "end": 588 }
class ____: def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(next=head) last = {} s, cur = 0, dummy while cur: s += cur.val last[s] = cur cur = cur.next s, cur = 0, dummy while cur: s += cur.val cur.next = last[s].next cur = cur.next return dummy.next
Solution
python
eth-brownie__brownie
tests/network/test_alert.py
{ "start": 76, "end": 3230 }
class ____: def __init__(self, initial_value, args=tuple(), kwargs={}): self.value = [initial_value] self.args = args self.kwargs = kwargs self.raised = False def __call__(self, *args, **kwargs): if args != self.args or kwargs != self.kwargs: self.raised = True raise ValueError return self.value[-1] def set_value(self, value): self.value = [self.value[-1], value] def callback(self, old, new): if self.value != [old, new]: self.raised = True @pytest.fixture(scope="function", autouse=True) def setup(): yield alert.stop_all() def _alert_fn(): return True def test_raises(): with pytest.raises(TypeError): alert.new("foo") assert len(alert.show()) == 0 with pytest.raises(ValueError): alert.new(time.time, repeat=-1) assert len(alert.show()) == 0 with pytest.raises(TypeError): alert.new(time.time, args=("potato",)) assert len(alert.show()) == 0 def test_new(): a = alert.new(_alert_fn, delay=0.1) assert type(a) is alert.Alert assert alert.show() == [a] b = alert.Alert(_alert_fn, delay=0.1) assert a != b assert len(alert.show()) == 2 def test_show(): a = alert.new(_alert_fn, delay=0.1) time.sleep(0.05) b = alert.new(_alert_fn, delay=0.1) time.sleep(0.05) c = alert.new(_alert_fn, delay=0.1) assert alert.show() == [a, b, c] def test_stop(): alert.new(_alert_fn, delay=0.1) a = alert.new(_alert_fn, delay=0.1) assert len(alert.show()) == 2 a.stop(False) a.wait() assert len(alert.show()) == 1 alert.new(_alert_fn, delay=0.1) alert.new(_alert_fn, delay=0.1) assert len(alert.show()) == 3 alert.stop_all() assert len(alert.show()) == 0 def test_fire_msg(capfd): t = AlertTest(False) alert.new(t, delay=0.03, msg="Fired") assert not capfd.readouterr()[0].strip() t.set_value(True) time.sleep(0.08) assert capfd.readouterr()[0].strip()[-5:] == "Fired" assert len(alert.show()) == 0 def test_fire_callback(capfd): t = AlertTest("foo") alert.new(t, delay=0.01, callback=t.callback) time.sleep(0.03) assert not t.raised assert len(alert.show()) == 1 t.set_value("bar") time.sleep(0.03) assert not t.raised assert len(alert.show()) == 0 def test_args_kwargs(): t = AlertTest(False, (1, 2, 3), {"foo": "bar"}) alert.new(t, (1, 2, 3), {"foo": "bar"}, delay=0.01) time.sleep(0.02) assert not t.raised assert len(alert.show()) == 1 def test_repeat(): t = AlertTest("foo") a = alert.new(t, delay=0.01, callback=t.callback, repeat=2) time.sleep(0.05) assert not t.raised assert len(alert.show()) == 1 t.set_value("bar") time.sleep(0.05) assert not t.raised assert len(alert.show()) == 1 t.set_value("foo") time.sleep(0.05) assert not t.raised assert a.is_alive() assert len(alert.show()) == 1 t.set_value("potato") time.sleep(0.05) assert not t.raised assert not a.is_alive() assert len(alert.show()) == 0
AlertTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/links/test_base_aws.py
{ "start": 4116, "end": 8234 }
class ____: """Base class for AWS Provider links tests.""" link_class: type[BaseAwsLink] @pytest.fixture(autouse=True) def setup_base_test_case(self, dag_maker, create_task_instance_of_operator): self.dag_maker = dag_maker self.ti_maker = create_task_instance_of_operator @property def full_qualname(self) -> str: return f"{self.link_class.__module__}.{self.link_class.__qualname__}" @property def task_id(self) -> str: return f"test-{self.link_class.__name__}" def create_op_and_ti( self, extra_link_class: type[BaseAwsLink], *, dag_id, task_id, logical_date=None, session=None, **operator_kwargs, ): """Helper method for generate operator and task instance""" op = link_test_operator(extra_link_class) return OperatorAndTi( task=op(task_id=task_id), task_instance=self.ti_maker( op, dag_id=dag_id, task_id=task_id, logical_date=logical_date, session=session, **operator_kwargs, ), ) def assert_extra_link_url( self, expected_url: str, region_name=TEST_REGION_NAME, aws_partition=TEST_AWS_PARTITION, **extra_link_kwargs, ): """Helper method for create extra link URL from the parameters.""" task, ti = self.create_op_and_ti(self.link_class, dag_id="test_extra_link", task_id=self.task_id) mock_context = mock.MagicMock() mock_context.__getitem__.side_effect = {"ti": ti}.__getitem__ self.link_class.persist( context=mock_context, operator=task, region_name=region_name, aws_partition=aws_partition, **extra_link_kwargs, ) error_msg = f"{self.full_qualname!r} should be preserved after execution" assert task.operator_extra_links[0].get_link(operator=task, ti_key=ti.key) == expected_url, error_msg def test_link_serialize(self): """Test: Operator links should exist for serialized DAG.""" self.create_op_and_ti(self.link_class, dag_id="test_link_serialize", task_id=self.task_id) serialized_dag = self.dag_maker.get_serialized_data() deserialized_dag = SerializedDAG.deserialize_dag(serialized_dag["dag"]) operator_extra_link = deserialized_dag.tasks[0].operator_extra_links[0] error_message = "Operator links should exist for serialized DAG" assert operator_extra_link.name == self.link_class.name, error_message def test_empty_xcom(self): """Test: Operator links should return empty string if no XCom value.""" ti = self.create_op_and_ti( self.link_class, dag_id="test_empty_xcom", task_id=self.task_id ).task_instance serialized_dag = self.dag_maker.get_serialized_data() deserialized_dag = SerializedDAG.from_dict(serialized_dag) deserialized_task = deserialized_dag.task_dict[self.task_id] assert ti.task.operator_extra_links[0].get_link(operator=ti.task, ti_key=ti.key) == "", ( "Operator link should only be added if job id is available in XCom" ) assert deserialized_task.get_extra_links(ti, self.link_class.name) == "", ( "Operator link should be empty for deserialized task with no XCom push" ) def test_suppress_error_on_xcom_pull(self): """Test ignore any error on XCom pull""" with mock.patch.object(XCom, "get_value", side_effect=OSError("FakeError")) as m: op, ti = self.create_op_and_ti( self.link_class, dag_id="test_error_on_xcom_pull", task_id=self.task_id ) self.link_class().get_link(op, ti_key=ti.key) m.assert_called_once() @abstractmethod def test_extra_link(self, **kwargs): """Test: Expected URL Link.""" raise NotImplementedError(f"{type(self).__name__!r} should implement `test_extra_link` test")
BaseAwsLinksTestCase
python
dask__dask
dask/dataframe/dask_expr/_groupby.py
{ "start": 18608, "end": 19387 }
class ____(SingleAggregation): chunk = staticmethod(_cov_chunk) std = False @classmethod def combine(cls, g, levels): return _concat(g) @classmethod def aggregate(cls, inputs, **kwargs): return _cov_agg(_concat(inputs), **kwargs) @property def chunk_kwargs(self) -> dict: # type: ignore[override] return self.operand("chunk_kwargs") @property def aggregate_kwargs(self) -> dict: # type: ignore[override] kwargs = self.operand("aggregate_kwargs").copy() kwargs["sort"] = self.sort kwargs["std"] = self.std kwargs["levels"] = self.levels return kwargs @property def combine_kwargs(self) -> dict: # type: ignore[override] return {"levels": self.levels}
Cov
python
PyCQA__pylint
tests/functional/s/super/super_checks.py
{ "start": 4399, "end": 4523 }
class ____(Child, Niece): def method(self): print("AlabamaCousin") super(Child, self).method()
AlabamaCousin
python
scrapy__scrapy
tests/test_spidermiddleware_referer.py
{ "start": 21197, "end": 21357 }
class ____(MixinNoReferrer, TestRefererMiddleware): settings = {"REFERRER_POLICY": "scrapy.spidermiddlewares.referer.NoReferrerPolicy"}
TestSettingsNoReferrer
python
pexpect__pexpect
pexpect/expect.py
{ "start": 51, "end": 6867 }
class ____(object): def __init__(self, spawn, searcher, searchwindowsize=-1): self.spawn = spawn self.searcher = searcher # A value of -1 means to use the figure from spawn, which should # be None or a positive number. if searchwindowsize == -1: searchwindowsize = spawn.searchwindowsize self.searchwindowsize = searchwindowsize self.lookback = None if hasattr(searcher, 'longest_string'): self.lookback = searcher.longest_string def do_search(self, window, freshlen): spawn = self.spawn searcher = self.searcher if freshlen > len(window): freshlen = len(window) index = searcher.search(window, freshlen, self.searchwindowsize) if index >= 0: spawn._buffer = spawn.buffer_type() spawn._buffer.write(window[searcher.end:]) spawn.before = spawn._before.getvalue()[ 0:-(len(window) - searcher.start)] spawn._before = spawn.buffer_type() spawn._before.write(window[searcher.end:]) spawn.after = window[searcher.start:searcher.end] spawn.match = searcher.match spawn.match_index = index # Found a match return index elif self.searchwindowsize or self.lookback: maintain = self.searchwindowsize or self.lookback if spawn._buffer.tell() > maintain: spawn._buffer = spawn.buffer_type() spawn._buffer.write(window[-maintain:]) def existing_data(self): # First call from a new call to expect_loop or expect_async. # self.searchwindowsize may have changed. # Treat all data as fresh. spawn = self.spawn before_len = spawn._before.tell() buf_len = spawn._buffer.tell() freshlen = before_len if before_len > buf_len: if not self.searchwindowsize: spawn._buffer = spawn.buffer_type() window = spawn._before.getvalue() spawn._buffer.write(window) elif buf_len < self.searchwindowsize: spawn._buffer = spawn.buffer_type() spawn._before.seek( max(0, before_len - self.searchwindowsize)) window = spawn._before.read() spawn._buffer.write(window) else: spawn._buffer.seek(max(0, buf_len - self.searchwindowsize)) window = spawn._buffer.read() else: if self.searchwindowsize: spawn._buffer.seek(max(0, buf_len - self.searchwindowsize)) window = spawn._buffer.read() else: window = spawn._buffer.getvalue() return self.do_search(window, freshlen) def new_data(self, data): # A subsequent call, after a call to existing_data. spawn = self.spawn freshlen = len(data) spawn._before.write(data) if not self.searchwindowsize: if self.lookback: # search lookback + new data. old_len = spawn._buffer.tell() spawn._buffer.write(data) spawn._buffer.seek(max(0, old_len - self.lookback)) window = spawn._buffer.read() else: # copy the whole buffer (really slow for large datasets). spawn._buffer.write(data) window = spawn.buffer else: if len(data) >= self.searchwindowsize or not spawn._buffer.tell(): window = data[-self.searchwindowsize:] spawn._buffer = spawn.buffer_type() spawn._buffer.write(window[-self.searchwindowsize:]) else: spawn._buffer.write(data) new_len = spawn._buffer.tell() spawn._buffer.seek(max(0, new_len - self.searchwindowsize)) window = spawn._buffer.read() return self.do_search(window, freshlen) def eof(self, err=None): spawn = self.spawn spawn.before = spawn._before.getvalue() spawn._buffer = spawn.buffer_type() spawn._before = spawn.buffer_type() spawn.after = EOF index = self.searcher.eof_index if index >= 0: spawn.match = EOF spawn.match_index = index return index else: spawn.match = None spawn.match_index = None msg = str(spawn) msg += '\nsearcher: %s' % self.searcher if err is not None: msg = str(err) + '\n' + msg exc = EOF(msg) exc.__cause__ = None # in Python 3.x we can use "raise exc from None" raise exc def timeout(self, err=None): spawn = self.spawn spawn.before = spawn._before.getvalue() spawn.after = TIMEOUT index = self.searcher.timeout_index if index >= 0: spawn.match = TIMEOUT spawn.match_index = index return index else: spawn.match = None spawn.match_index = None msg = str(spawn) msg += '\nsearcher: %s' % self.searcher if err is not None: msg = str(err) + '\n' + msg exc = TIMEOUT(msg) exc.__cause__ = None # in Python 3.x we can use "raise exc from None" raise exc def errored(self): spawn = self.spawn spawn.before = spawn._before.getvalue() spawn.after = None spawn.match = None spawn.match_index = None def expect_loop(self, timeout=-1): """Blocking expect""" spawn = self.spawn if timeout is not None: end_time = time.time() + timeout try: idx = self.existing_data() if idx is not None: return idx while True: # No match at this point if (timeout is not None) and (timeout < 0): return self.timeout() # Still have time left, so read more data incoming = spawn.read_nonblocking(spawn.maxread, timeout) if self.spawn.delayafterread is not None: time.sleep(self.spawn.delayafterread) idx = self.new_data(incoming) # Keep reading until exception or return. if idx is not None: return idx if timeout is not None: timeout = end_time - time.time() except EOF as e: return self.eof(e) except TIMEOUT as e: return self.timeout(e) except: self.errored() raise
Expecter
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_textbox19.py
{ "start": 315, "end": 948 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("textbox19.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with textbox(s).""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.insert_textbox( "E9", "This is some text", {"gradient": {"colors": ["#DDEBCF", "#9CB86E", "#156B13"]}}, ) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
getsentry__sentry
src/sentry/models/importchunk.py
{ "start": 3569, "end": 3977 }
class ____(BaseImportChunk): """ Records the pk mapping for the successful import of instances of a model that lives in the control silo. """ __relocation_scope__ = RelocationScope.Excluded class Meta: app_label = "sentry" db_table = "sentry_controlimportchunk" unique_together = (("import_uuid", "model", "min_ordinal"),) @region_silo_model
ControlImportChunk
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-moves-in-a-grid.py
{ "start": 38, "end": 865 }
class ____(object): def maxMoves(self, grid): """ :type grid: List[List[int]] :rtype: int """ dp = [True]*len(grid) result = 0 for c in xrange(len(grid[0])-1): new_dp = [False]*len(grid) for r in xrange(len(grid)): if not dp[r]: continue if grid[r][c] < grid[r][c+1]: new_dp[r] = True if r-1 >= 0 and grid[r][c] < grid[r-1][c+1]: new_dp[r-1] = True if r+1 < len(grid) and grid[r][c] < grid[r+1][c+1]: new_dp[r+1] = True dp = new_dp if not sum(dp): break else: c = len(grid[0])-1 return c # Time: O(m * n) # Space: O(m) # dp
Solution
python
scipy__scipy
scipy/special/tests/test_bdtr.py
{ "start": 141, "end": 970 }
class ____: def test(self): val = sc.bdtr(0, 1, 0.5) assert_allclose(val, 0.5) def test_sum_is_one(self): val = sc.bdtr([0, 1, 2], 2, 0.5) assert_array_equal(val, [0.25, 0.75, 1.0]) def test_rounding(self): double_val = sc.bdtr([0.1, 1.1, 2.1], 2, 0.5) int_val = sc.bdtr([0, 1, 2], 2, 0.5) assert_array_equal(double_val, int_val) @pytest.mark.parametrize('k, n, p', [ (np.inf, 2, 0.5), (1.0, np.inf, 0.5), (1.0, 2, np.inf) ]) def test_inf(self, k, n, p): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) val = sc.bdtr(k, n, p) assert np.isnan(val) def test_domain(self): val = sc.bdtr(-1.1, 1, 0.5) assert np.isnan(val)
TestBdtr
python
getsentry__sentry
tests/sentry/replays/endpoints/test_project_replay_summary.py
{ "start": 487, "end": 752 }
class ____: def __init__(self, status: int, json_data: dict[str, str]): self.status = status self.json_data = json_data self.data = json.dumps(json_data) def json(self) -> dict[str, str]: return self.json_data
MockSeerResponse
python
realpython__materials
what-does-arrow-mean-in-python/game_class_example.py
{ "start": 0, "end": 337 }
class ____: def __init__(self, name: str, genre: str, price: float) -> None: self.name = name self.genre = genre self.price = price def get_name(self) -> str: return self.name def get_genre(self) -> str: return self.genre def get_price(self) -> float: return self.price
Game
python
python-attrs__attrs
tests/test_abc.py
{ "start": 232, "end": 1638 }
class ____: def test_abc_implementation(self, slots): """ If an attrs class implements an abstract method, it stops being abstract. """ class Ordered(abc.ABC): @abc.abstractmethod def __lt__(self, other): pass @abc.abstractmethod def __le__(self, other): pass @attrs.define(order=True, slots=slots) class Concrete(Ordered): x: int assert not inspect.isabstract(Concrete) assert Concrete(2) > Concrete(1) def test_remain_abstract(self, slots): """ If an attrs class inherits from an abstract class but doesn't implement abstract methods, it remains abstract. """ class A(abc.ABC): @abc.abstractmethod def foo(self): pass @attrs.define(slots=slots) class StillAbstract(A): pass assert inspect.isabstract(StillAbstract) expected_exception_message = ( "^Can't instantiate abstract class StillAbstract without an " "implementation for abstract method 'foo'$" if PY_3_12_PLUS else "class StillAbstract with abstract method foo" ) with pytest.raises(TypeError, match=expected_exception_message): StillAbstract()
TestUpdateAbstractMethods
python
django__django
django/core/exceptions.py
{ "start": 435, "end": 519 }
class ____(Exception): """The updated object no longer exists."""
ObjectNotUpdated
python
joke2k__faker
tests/providers/test_automotive.py
{ "start": 6840, "end": 7223 }
class ____(_SimpleAutomotiveTestMixin): """Test ja_JP automotive provider methods""" license_plate_pattern: Pattern = re.compile( r"^(?:品川|足立|練馬|横浜|川崎|名古屋|大阪|神戸|福岡|札幌|尾張小牧|伊勢志摩) " r"\d{2,3} " r"(?:あ|い|う|え|か|き|く|け|こ|さ|す|せ|そ|た|ち|つ|て|と|な|に|ぬ|ね|の|は|ひ|ふ|ほ|" r"ま|み|む|め|も|や|ゆ|よ|ら|り|る|れ|ろ|わ|を) " r"(?:\d{2}-\d{2}|・{1,3}\d{1,3})$" )
TestJaJp
python
ApeWorX__ape
src/ape/api/networks.py
{ "start": 29606, "end": 49493 }
class ____(BaseInterfaceModel): """ A wrapper around a provider for a specific ecosystem. """ name: str # Name given when registered in ecosystem """The name of the network.""" ecosystem: EcosystemAPI """The ecosystem of the network.""" # TODO: In 0.9, make @property that returns value from config, # and use REQUEST_HEADER as plugin-defined constants. request_header: dict = {} """A shareable network HTTP header.""" # See ``.default_provider`` which is the proper field. _default_provider: str = "" _is_custom: bool = False def __repr__(self) -> str: try: chain_id = self.chain_id except ProviderNotConnectedError: # Only happens on local networks chain_id = None try: content = ( f"{self.choice} chain_id={self.chain_id}" if chain_id is not None else self.choice ) return f"<{content}>" except Exception: # Don't allow repr to fail. try: name = self.name except Exception: name = None return f"<{name}>" if name else f"{type(self)}" @property def data_folder(self) -> Path: """ The path to the network's data folder, e.g. ``$HOME/.ape/{self.ecosystem_name}/{self.name}`` unless overridden. """ return self.ecosystem.data_folder / self.name @property def ecosystem_config(self) -> PluginConfig: """ The configuration of the network. See :class:`~ape.managers.config.ConfigManager` for more information on plugin configurations. """ return self.ecosystem.config @property def config(self) -> PluginConfig: name_options = {self.name, self.name.replace("-", "_"), self.name.replace("_", "-")} cfg: Any for opt in name_options: if cfg := self.ecosystem_config.get(opt): if isinstance(cfg, dict): return PluginConfig.model_validate(cfg) elif isinstance(cfg, PluginConfig): return cfg else: raise TypeError(f"Network config must be a dictionary. Received '{type(cfg)}'.") return PluginConfig() @cached_property def gas_limit(self) -> GasLimit: return self.config.get("gas_limit", AutoGasLimit()) @cached_property def auto_gas_multiplier(self) -> float: """ The value to multiply estimated gas by for tx-insurance. """ return self.gas_limit.multiplier if isinstance(self.gas_limit, AutoGasLimit) else 1.0 @property def base_fee_multiplier(self) -> float: """ A multiplier to apply to a transaction base fee. """ return self.config.get("base_fee_multiplier", DEFAULT_LIVE_NETWORK_BASE_FEE_MULTIPLIER) @property def chain_id(self) -> int: """ The ID of the blockchain. **NOTE**: Unless overridden, returns same as :py:attr:`ape.api.providers.ProviderAPI.chain_id`. """ if ( self.provider.network.name == self.name and self.provider.network.ecosystem.name == self.ecosystem.name ): # Ensure 'active_provider' is actually (seemingly) connected # to this network. return self.provider.chain_id raise NetworkError( "Unable to reference provider to get `chain_id`: " f"Network '{self.name}' is detached and information is missing." ) @property def network_id(self) -> int: """ The ID of the network. **NOTE**: Unless overridden, returns same as :py:attr:`~ape.api.networks.NetworkAPI.chain_id`. """ return self.chain_id @property def required_confirmations(self) -> int: """ The default amount of confirmations recommended to wait before considering a transaction "confirmed". Confirmations refer to the number of blocks that have been added since the transaction's block. """ return self.config.get("required_confirmations", 0) @property def block_time(self) -> int: """ The approximate amount of time it takes for a new block to get mined to the chain. Configure in your ``ape-config.yaml`` file. Config example:: ethereum: mainnet: block_time: 15 """ return self.config.get("block_time", 0) @property def transaction_acceptance_timeout(self) -> int: """ The amount of time to wait for a transaction to be accepted on the network. Does not include waiting for block-confirmations. Defaults to two minutes. Local networks use smaller timeouts. """ return self.config.get( "transaction_acceptance_timeout", DEFAULT_TRANSACTION_ACCEPTANCE_TIMEOUT ) @cached_property def explorer(self) -> Optional["ExplorerAPI"]: """ The block-explorer for the given network. Returns: :class:`ape.api.explorers.ExplorerAPI`, optional """ chain_id = ( None if self.network_manager.active_provider is None else self.chain_manager.chain_id ) for plugin_name, plugin_tuple in self._plugin_explorers: ecosystem_name, network_name, explorer_class = plugin_tuple # Check for explicitly configured custom networks plugin_config = self.config_manager.get_config(plugin_name) has_explorer_config = ( plugin_config and self.ecosystem.name in plugin_config and self.name in plugin_config[self.ecosystem.name] ) # Return the first registered explorer (skipping any others) if self.ecosystem.name == ecosystem_name and ( self.name == network_name or has_explorer_config ): return explorer_class(name=plugin_name, network=self) elif chain_id is not None and explorer_class.supports_chain(chain_id): # NOTE: Adhoc networks will likely reach here. return explorer_class(name=plugin_name, network=self) return None # May not have an block explorer @property def _plugin_explorers(self) -> list[tuple]: # Abstracted for testing purposes. return self.plugin_manager.explorers @property def is_mainnet(self) -> bool: """ True when the network is the mainnet network for the ecosystem. """ cfg_is_mainnet: Optional[bool] = self.config.get("is_mainnet") if cfg_is_mainnet is not None: return cfg_is_mainnet return self.name == "mainnet" @property def is_fork(self) -> bool: """ True when using a forked network. """ return self.name.endswith("-fork") @property def is_local(self) -> bool: """ True when using the local network. """ return self.name == LOCAL_NETWORK_NAME @property def is_dev(self) -> bool: """ True when using a local network, including forks. """ return self.is_local or self.is_fork @property def is_adhoc(self) -> bool: """ Is a custom network from CLI only, e.g. was not configured in any CLI value and is mostly an "unknown" network. """ return self.name == "custom" and not self._is_custom @property def is_custom(self) -> bool: """ True when this network is a configured custom network. """ return self._is_custom @cached_property def providers(self): # -> dict[str, Partial[ProviderAPI]] """ The providers of the network, such as Infura, Alchemy, or Node. Returns: dict[str, partial[:class:`~ape.api.providers.ProviderAPI`]] """ providers = {} for _, plugin_tuple in self._get_plugin_providers(): ecosystem_name, network_name, provider_class = plugin_tuple provider_name = ( provider_class.__module__.split(".")[0].replace("_", "-").replace("ape-", "") ) is_custom_with_config = self._is_custom and self.default_provider_name == provider_name # NOTE: Custom networks that are NOT from config must work with any provider. # Also, ensure we are only adding forked providers for forked networks and # non-forking providers for non-forked networks. For custom networks, it # can be trickier (see last condition). # TODO: In 0.9, add a better way for class-level ForkedProviders to define # themselves as "Fork" providers. if ( (self.ecosystem.name == ecosystem_name and self.name == network_name) or self.is_adhoc or ( is_custom_with_config and ( (self.is_fork and "Fork" in provider_class.__name__) or (not self.is_fork and "Fork" not in provider_class.__name__) ) and provider_class.__name__ == "Node" # Ensure uses Node class instead of GethDev ) ): # NOTE: Lazily load provider config provider_name = provider_class.NAME or provider_name providers[provider_name] = partial( provider_class, name=provider_name, network=self, ) # Any EVM-chain works with node provider. if "node" not in providers and self.name in self.ecosystem._networks_from_evmchains: # NOTE: Arbitrarily using sepolia to access the Node class. node_provider_cls = self.network_manager.ethereum.sepolia.get_provider("node").__class__ providers["node"] = partial(node_provider_cls, name="node", network=self) return providers def _get_plugin_providers(self): # NOTE: Abstracted for testing purposes. return self.plugin_manager.providers def _get_plugin_provider_names(self) -> Iterator[str]: for _, plugin_tuple in self._get_plugin_providers(): ecosystem_name, network_name, provider_class = plugin_tuple yield provider_class.__module__.split(".")[0].replace("_", "-").replace("ape-", "") def get_provider( self, provider_name: Optional[str] = None, provider_settings: Optional[dict] = None, connect: bool = False, ): """ Get a provider for the given name. If given ``None``, returns the default provider. Args: provider_name (str, optional): The name of the provider to get. Defaults to ``None``. When ``None``, returns the default provider. provider_settings (dict, optional): Settings to apply to the provider. Defaults to ``None``. connect (bool): Set to ``True`` when you also want the provider to connect. Returns: :class:`~ape.api.providers.ProviderAPI` """ if not (provider_name := provider_name or self.default_provider_name): raise NetworkError( f"No default provider for network '{self.name}'. " "Set one in your pyproject.toml/ape-config.yaml file:\n" f"\n{self.ecosystem.name}:" f"\n {self.name}:" "\n default_provider: <DEFAULT_PROVIDER>" ) provider_settings = provider_settings or {} if ":" in provider_name: # NOTE: Shortcut that allows `--network ecosystem:network:http://...` to work provider_settings["uri"] = provider_name provider_name = "node" elif provider_name.endswith(".ipc"): provider_settings["ipc_path"] = provider_name provider_name = "node" if provider_name in self.providers: provider = self.providers[provider_name](provider_settings=provider_settings) return _connect_provider(provider) if connect else provider elif self.is_fork: # If it can fork Ethereum (and we are asking for it) assume it can fork this one. # TODO: Refactor this approach to work for custom-forked non-EVM networks. common_forking_providers = self.network_manager.ethereum.mainnet_fork.providers if provider_name in common_forking_providers: provider = common_forking_providers[provider_name]( provider_settings=provider_settings, network=self, ) return _connect_provider(provider) if connect else provider raise ProviderNotFoundError( provider_name, network=self.name, ecosystem=self.ecosystem.name, options=self.providers, ) def use_provider( self, provider: Union[str, "ProviderAPI"], provider_settings: Optional[dict] = None, disconnect_after: bool = False, disconnect_on_exit: bool = True, ) -> ProviderContextManager: """ Use and connect to a provider in a temporary context. When entering the context, it calls method :meth:`ape.api.providers.ProviderAPI.connect` and when exiting, it calls method :meth:`ape.api.providers.ProviderAPI.disconnect`. Usage example:: from ape import networks mainnet = networks.ethereum.mainnet # An instance of NetworkAPI with mainnet.use_provider("infura"): ... Args: provider (Union[str, :class:`~ape.api.providers.ProviderAPI`]): The provider instance or the name of the provider to use. provider_settings (dict, optional): Settings to apply to the provider. Defaults to ``None``. disconnect_after (bool): Set to ``True`` to force a disconnect after ending the context. This defaults to ``False`` so you can re-connect to the same network, such as in a multi-chain testing scenario. disconnect_on_exit (bool): Whether to disconnect on the exit of the python session. Defaults to ``True``. Returns: :class:`~ape.api.networks.ProviderContextManager` """ settings = provider_settings or {} # NOTE: The main reason we allow a provider instance here is to avoid unnecessarily # re-initializing the class. provider_obj = ( self.get_provider(provider_name=provider, provider_settings=settings, connect=True) if isinstance(provider, str) else provider ) return ProviderContextManager( provider=provider_obj, disconnect_after=disconnect_after, disconnect_on_exit=disconnect_on_exit, ) @property def default_provider_name(self) -> Optional[str]: """ The name of the default provider or ``None``. Returns: Optional[str] """ provider_from_config: str if provider := self._default_provider: # Was set programmatically. return provider elif provider_from_config := self.config.get("default_provider"): # The default is found in the Network's config class. return provider_from_config elif len(self.providers) > 0: # No default set anywhere - use the first installed. return list(self.providers)[0] # There are no providers at all for this network. return None @property def default_provider(self) -> Optional["ProviderAPI"]: if (name := self.default_provider_name) and name in self.providers: return self.get_provider(name) return None @property def choice(self) -> str: return f"{self.ecosystem.name}:{self.name}" def set_default_provider(self, provider_name: str): """ Change the default provider. Raises: :class:`~ape.exceptions.NetworkError`: When the given provider is not found. Args: provider_name (str): The name of the provider to switch to. """ if provider_name in self.providers: self._default_provider = provider_name else: raise NetworkError(f"Provider '{provider_name}' not found in network '{self.choice}'.") def use_default_provider( self, provider_settings: Optional[dict] = None, disconnect_after: bool = False, ) -> ProviderContextManager: """ Temporarily connect and use the default provider. When entering the context, it calls method :meth:`ape.api.providers.ProviderAPI.connect` and when exiting, it calls method :meth:`ape.api.providers.ProviderAPI.disconnect`. **NOTE**: If multiple providers exist, uses whatever was "first" registered. Usage example:: from ape import networks mainnet = networks.ethereum.mainnet # An instance of NetworkAPI with mainnet.use_default_provider(): ... Args: provider_settings (dict, optional): Settings to override the provider. disconnect_after (bool): Set to ``True`` to force a disconnect after ending the context. This defaults to ``False`` so you can re-connect to the same network, such as in a multi-chain testing scenario. Returns: :class:`~ape.api.networks.ProviderContextManager` """ if self.default_provider: settings = provider_settings or {} return self.use_provider( self.default_provider.name, provider_settings=settings, disconnect_after=disconnect_after, ) raise NetworkError(f"No providers for network '{self.name}'.") def publish_contract(self, address: AddressType): """ A convenience method to publish a contract to the explorer. Raises: :class:`~ape.exceptions.NetworkError`: When there is no explorer for this network. Args: address (:class:`~ape.types.address.AddressType`): The address of the contract. """ if not self.explorer: raise NetworkError("Unable to publish contract - no explorer plugin installed.") logger.info(f"Publishing and verifying contract using '{self.explorer.name}'.") self.explorer.publish_contract(address) def verify_chain_id(self, chain_id: int): """ Verify a chain ID for this network. Args: chain_id (int): The chain ID to verify. Raises: :class:`~ape.exceptions.NetworkMismatchError`: When the network is not local or adhoc and has a different hardcoded chain ID than the given one. """ if self.name not in ("custom", LOCAL_NETWORK_NAME) and self.chain_id != chain_id: raise NetworkMismatchError(chain_id, self) def _get_request_headers(self) -> RPCHeaders: # Internal helper method called by NetworkManager headers = RPCHeaders(**self.request_header) # Have to do it this way to avoid multiple-keys error. configured_headers: dict = self.config.get("request_headers", {}) for key, value in configured_headers.items(): headers[key] = value return headers
NetworkAPI
python
huggingface__transformers
src/transformers/models/layoutlmv2/modeling_layoutlmv2.py
{ "start": 1924, "end": 4249 }
class ____(nn.Module): """Construct the embeddings from word, position and token_type embeddings.""" def __init__(self, config): super().__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) self.x_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.coordinate_size) self.y_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.coordinate_size) self.h_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.shape_size) self.w_position_embeddings = nn.Embedding(config.max_2d_position_embeddings, config.shape_size) self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.register_buffer( "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False ) def _calc_spatial_position_embeddings(self, bbox): try: left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0]) upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1]) right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2]) lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3]) except IndexError as e: raise IndexError("The `bbox` coordinate values should be within 0-1000 range.") from e h_position_embeddings = self.h_position_embeddings(bbox[:, :, 3] - bbox[:, :, 1]) w_position_embeddings = self.w_position_embeddings(bbox[:, :, 2] - bbox[:, :, 0]) spatial_position_embeddings = torch.cat( [ left_position_embeddings, upper_position_embeddings, right_position_embeddings, lower_position_embeddings, h_position_embeddings, w_position_embeddings, ], dim=-1, ) return spatial_position_embeddings
LayoutLMv2Embeddings
python
getsentry__sentry
src/sentry/grouping/component.py
{ "start": 9100, "end": 9184 }
class ____(BaseGroupingComponent[str]): id: str = "module"
ModuleGroupingComponent
python
django__django
tests/apps/apps.py
{ "start": 276, "end": 374 }
class ____(AppConfig): """This class doesn't supply the mandatory 'name' attribute."""
BadConfig
python
numba__llvmlite
llvmlite/tests/test_binding.py
{ "start": 81565, "end": 82498 }
class ____(TestMCJit): @unittest.skipIf(platform.system() == "Darwin", "__cxa_atexit is broken on OSX in MCJIT") def test_global_ctors_dtors(self): # test issue #303 # (https://github.com/numba/llvmlite/issues/303) mod = self.module(asm_global_ctors) ee = self.jit(mod) ee.finalize_object() ee.run_static_constructors() # global variable should have been initialized ptr_addr = ee.get_global_value_address("A") ptr_t = ctypes.POINTER(ctypes.c_int32) ptr = ctypes.cast(ptr_addr, ptr_t) self.assertEqual(ptr.contents.value, 10) foo_addr = ee.get_function_address("foo") foo = ctypes.CFUNCTYPE(ctypes.c_int32)(foo_addr) self.assertEqual(foo(), 12) ee.run_static_destructors() # destructor should have run self.assertEqual(ptr.contents.value, 20)
TestGlobalConstructors
python
google__pytype
pytype/pytd/slots.py
{ "start": 353, "end": 12305 }
class ____: """A "slot" describes a Python operator. In particular, it describes how a magic method (E.g. "__add__") relates to the opcode ("BINARY_ADD") and the C function pointer ("nb_add"). Attributes: python_name: The name of the Python method. E.g. "__add__". c_name: The name of the C function pointer. Only use the base name, e.g. for tp_as_number->nb_add, use nb_add. function_type: Type of the C function index: If multiple python methods share the same function pointer (e.g. __add__ and __radd__), this is 0 or 1. opcode: The name of the opcode that CPython uses to call this function. This is only filled in for operators (e.g. BINARY_SUBSCR), but not for operations (e.g. STORE_SUBSCR). python_version: "2", "3", or (default) "*". symbol: Only filled in for operators. The corresponding symbol, e.g., "+" for __add__, if one exists; otherwise, a human-friendly description, e.g., "item retrieval" for __getitem__. """ python_name: str c_name: str function_type: str index: int | None = None opcode: str | None = None python_version: str | None = "*" symbol: str | None = None SLOTS: list[Slot] = [ # typeobject Slot("__new__", "tp_new", "new"), Slot("__init__", "tp_init", "init"), Slot("__str__", "tp_print", "print"), Slot("__repr__", "tp_repr", "repr", opcode="UNARY_CONVERT"), Slot("__hash__", "tp_hash", "hash"), Slot("__call__", "tp_call", "call"), # Note: In CPython, if tp_getattro exists, tp_getattr is never called. Slot("__getattribute__", "tp_getattro", "getattro"), Slot("__getattr__", "tp_getattro", "getattro"), Slot("__setattr__", "tp_setattro", "setattro"), Slot("__delattr__", "tp_setattro", "setattro"), # for Py_TPFLAGS_HAVE_ITER: Slot("__iter__", "tp_iter", "unary"), Slot("next", "tp_iternext", "next", python_version="2"), Slot("__next__", "tp_iternext", "next", python_version="3"), # for Py_TPFLAGS_HAVE_CLASS: Slot("__get__", "tp_descr_get", "descr_get"), Slot("__set__", "tp_descr_set", "descr_set"), Slot("__delete__", "tp_descr_set", "descr_delete"), Slot("__del__", "tp_del", "destructor"), # all typically done by __richcompare__ Slot( "__cmp__", "tp_compare", "cmp", python_version="2" ), # "tp_reserved" in Python 3 Slot("__lt__", "tp_richcompare", "richcmpfunc", symbol="<"), Slot("__le__", "tp_richcompare", "richcmpfunc", symbol="<="), Slot("__eq__", "tp_richcompare", "richcmpfunc", symbol="=="), Slot("__ne__", "tp_richcompare", "richcmpfunc", symbol="!="), Slot("__gt__", "tp_richcompare", "richcmpfunc", symbol=">"), Slot("__ge__", "tp_richcompare", "richcmpfunc", symbol=">="), Slot("__richcompare__", "tp_richcompare", "richcmpfunc"), # number methods: Slot( "__add__", "nb_add", "binary_nb", index=0, opcode="BINARY_ADD", symbol="+", ), Slot("__radd__", "nb_add", "binary_nb", index=1), Slot( "__sub__", "nb_subtract", "binary_nb", index=0, opcode="BINARY_SUBTRACT", symbol="-", ), Slot("__rsub__", "nb_subtract", "binary_nb", index=1), Slot("__mul__", "nb_multiply", "binary_nb", index=0, symbol="*"), Slot("__rmul__", "nb_multiply", "binary_nb", index=1), Slot( "__div__", "nb_divide", "binary_nb", index=0, opcode="BINARY_DIVIDE", symbol="/", ), Slot("__rdiv__", "nb_divide", "binary_nb", index=1), Slot( "__mod__", "nb_remainder", "binary_nb", index=0, opcode="BINARY_MODULO", symbol="%", ), Slot("__rmod__", "nb_remainder", "binary_nb", index=1), Slot("__divmod__", "nb_divmod", "binary_nb", index=0), Slot("__rdivmod__", "nb_divmod", "binary_nb", index=1), Slot( "__lshift__", "nb_lshift", "binary_nb", index=0, opcode="BINARY_LSHIFT", symbol="<<", ), Slot("__rlshift__", "nb_lshift", "binary_nb", index=1), Slot( "__rshift__", "nb_rshift", "binary_nb", index=0, opcode="BINARY_RSHIFT", symbol=">>", ), Slot("__rrshift__", "nb_rshift", "binary_nb", index=1), Slot( "__and__", "nb_and", "binary_nb", index=0, opcode="BINARY_AND", symbol="&", ), Slot("__rand__", "nb_and", "binary_nb", index=1), Slot( "__xor__", "nb_xor", "binary_nb", index=0, opcode="BINARY_XOR", symbol="^", ), Slot("__rxor__", "nb_xor", "binary_nb", index=1), Slot( "__or__", "nb_or", "binary_nb", index=0, opcode="BINARY_OR", symbol="|" ), Slot("__ror__", "nb_or", "binary_nb", index=1), # needs Py_TPFLAGS_HAVE_CLASS: Slot( "__floordiv__", "nb_floor_divide", "binary_nb", index=0, opcode="BINARY_FLOOR_DIVIDE", symbol="//", ), Slot("__rfloordiv__", "nb_floor_divide", "binary_nb", index=1), Slot( "__truediv__", "nb_true_divide", "binary_nb", index=0, opcode="BINARY_TRUE_DIVIDE", symbol="/", ), Slot("__rtruediv__", "nb_true_divide", "binary_nb", index=1), Slot( "__pow__", "nb_power", "ternary", index=0, opcode="BINARY_POWER", symbol="**", ), Slot("__rpow__", "nb_power", "ternary", index=1), # needs wrap_tenary_nb Slot( "__neg__", "nb_negative", "unary", opcode="UNARY_NEGATIVE", symbol="-" ), Slot( "__pos__", "nb_positive", "unary", opcode="UNARY_POSITIVE", symbol="+" ), Slot("__abs__", "nb_absolute", "unary"), Slot("__nonzero__", "nb_nonzero", "inquiry"), # inverse of UNARY_NOT opcode Slot("__invert__", "nb_invert", "unary", opcode="UNARY_INVERT", symbol="~"), Slot("__coerce__", "nb_coerce", "coercion"), # not needed Slot("__int__", "nb_int", "unary"), # expects exact int as return Slot("__long__", "nb_long", "unary"), # expects exact long as return Slot("__float__", "nb_float", "unary"), # expects exact float as return Slot("__oct__", "nb_oct", "unary"), Slot("__hex__", "nb_hex", "unary"), # Added in 2.0. These are probably largely useless. # (For list concatenation, use sl_inplace_concat) Slot( "__iadd__", "nb_inplace_add", "binary", opcode="INPLACE_ADD", symbol="+=", ), Slot( "__isub__", "nb_inplace_subtract", "binary", opcode="INPLACE_SUBTRACT", symbol="-=", ), Slot( "__imul__", "nb_inplace_multiply", "binary", opcode="INPLACE_MULTIPLY", symbol="*=", ), Slot( "__idiv__", "nb_inplace_divide", "binary", opcode="INPLACE_DIVIDE", symbol="/=", ), Slot( "__imod__", "nb_inplace_remainder", "binary", opcode="INPLACE_MODULO", symbol="%=", ), Slot( "__ipow__", "nb_inplace_power", "ternary", opcode="INPLACE_POWER", symbol="**=", ), Slot( "__ilshift__", "nb_inplace_lshift", "binary", opcode="INPLACE_LSHIFT", symbol="<<=", ), Slot( "__irshift__", "nb_inplace_rshift", "binary", opcode="INPLACE_RSHIFT", symbol=">>=", ), Slot( "__iand__", "nb_inplace_and", "binary", opcode="INPLACE_AND", symbol="&=", ), Slot( "__ixor__", "nb_inplace_xor", "binary", opcode="INPLACE_XOR", symbol="^=", ), Slot( "__ior__", "nb_inplace_or", "binary", opcode="INPLACE_OR", symbol="|=" ), Slot( "__ifloordiv__", "nb_inplace_floor_divide", "binary", opcode="INPLACE_FLOOR_DIVIDE", symbol="//=", ), Slot( "__itruediv__", "nb_inplace_true_divide", "binary", opcode="INPLACE_TRUE_DIVIDE", symbol="/=", ), # matrix methods: # Added in 3.5 Slot( "__matmul__", "nb_matrix_multiply", "binary_nb", index=0, opcode="BINARY_MATRIX_MULTIPLY", symbol="@", ), Slot("__rmatmul__", "nb_matrix_multiply", "binary_nb", index=1), Slot( "__imatmul__", "nb_inplace_matrix_multiply", "binary", opcode="INPLACE_MATRIX_MULTIPLY", symbol="@=", ), # Added in 2.5. Used whenever i acts as a sequence index (a[i]) Slot("__index__", "nb_index", "unary"), # needs int/long return # mapping # __getitem__: Python first tries mp_subscript, then sq_item # __len__: Python first tries sq_length, then mp_length # __delitem__: Reuses __setitem__ slot. Slot( "__getitem__", "mp_subscript", "binary", opcode="BINARY_SUBSCR", symbol="item retrieval", ), # In CPython, these two share a slot: Slot( "__delitem__", "mp_ass_subscript", "objobjargproc", symbol="item deletion", ), Slot( "__setitem__", "mp_ass_subscript", "objobjargproc", symbol="item assignment", ), Slot("__len__", "mp_length", "len"), # sequence Slot("__contains__", "sq_contains", "objobjproc", symbol="'in'"), # These sequence methods are duplicates of number or mapping methods. # For example, in the C API, "add" can be implemented either by sq_concat, # or by np_add. Python will try both. The opcode mapping is identical # between the two. So e.g. the implementation of the BINARY_SUBSCR opcode in # Python/ceval.c will try both sq_item and mp_subscript, which is why this # opcode appears twice in our list. Slot("__add__", "sq_concat", "binary", opcode="BINARY_ADD", symbol="+"), Slot( "__mul__", "sq_repeat", "indexargfunc", opcode="BINARY_MULTIPLY", symbol="*", ), Slot( "__iadd__", "sq_inplace_concat", "binary", opcode="INPLACE_ADD", symbol="+=", ), Slot( "__imul__", "sq_inplace_repeat", "indexargfunc", opcode="INPLACE_MUL", symbol="*=", ), Slot( "__getitem__", "sq_item", "sq_item", opcode="BINARY_SUBSCR", symbol="item retrieval", ), Slot( "__setitem__", "sq_ass_slice", "sq_ass_item", symbol="item assignment" ), Slot("__delitem__", "sq_ass_item", "sq_delitem", symbol="item deletion"), # slices are passed as explicit slice objects to mp_subscript. Slot("__getslice__", "sq_slice", "sq_slice", symbol="slicing"), Slot("__setslice__", "sq_ass_slice", "ssizessizeobjarg"), Slot("__delslice__", "sq_ass_slice", "delslice"), ] CMP_LT = 0 CMP_LE = 1 CMP_EQ = 2 CMP_NE = 3 CMP_GT = 4 CMP_GE = 5 CMP_IN = 6 CMP_NOT_IN = 7 CMP_IS = 8 CMP_IS_NOT = 9 CMP_EXC_MATCH = 10 CMP_ALWAYS_SUPPORTED = frozenset({CMP_EQ, CMP_NE, CMP_IS, CMP_IS_NOT}) EQ, NE, LT, LE, GT, GE = "==", "!=", "<", "<=", ">", ">=" COMPARES = { EQ: lambda x, y: x == y, NE: lambda x, y: x != y, LT: lambda x, y: x < y, LE: lambda x, y: x <= y, GT: lambda x, y: x > y, GE: lambda x, y: x >= y, } SYMBOL_MAPPING = { slot.python_name: slot.symbol for slot in SLOTS if slot.symbol } def _ReverseNameMapping(): """__add__ -> __radd__, __mul__ -> __rmul__ etc.""" c_name_to_reverse = { slot.c_name: slot.python_name for slot in SLOTS if slot.index == 1 } return { slot.python_name: c_name_to_reverse[slot.c_name] for slot in SLOTS if slot.index == 0 } REVERSE_NAME_MAPPING = _ReverseNameMapping()
Slot
python
ray-project__ray
python/ray/llm/_internal/serve/config_generator/utils/models.py
{ "start": 263, "end": 408 }
class ____(BaseModel): id: str hf_token: Optional[str] = None remote_storage_uri: Optional[str] = None gpu_type: GPUType
ServeModel
python
getsentry__sentry
src/sentry/api/endpoints/project_create_sample_transaction.py
{ "start": 2369, "end": 3527 }
class ____(ProjectEndpoint): owner = ApiOwner.DATA_BROWSING publish_status = { "POST": ApiPublishStatus.PRIVATE, } # Members should be able to create sample events. # This is the same scope that allows members to view all issues for a project. permission_classes = (ProjectEventPermission,) def post(self, request: Request, project) -> Response: samples_root = os.path.join(DATA_ROOT, "samples") expected_commonpath = os.path.realpath(samples_root) json_path = os.path.join(samples_root, get_json_name(project)) json_real_path = os.path.realpath(json_path) if expected_commonpath != os.path.commonpath([expected_commonpath, json_real_path]): return Response(status=status.HTTP_400_BAD_REQUEST) with open(json_path, "rb") as fp: data = orjson.loads(fp.read()) data = fix_event_data(data) event = create_sample_event_basic( data, project.id, raw=True, skip_send_first_transaction=True, tagged=True ) data = serialize(event, request.user) return Response(data)
ProjectCreateSampleTransactionEndpoint
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI029.py
{ "start": 516, "end": 656 }
class ____: def __str__(self, *, extra) -> builtins.str: ... def __repr__(self, /, extra) -> str: ...
NonMatchingArgs
python
scrapy__scrapy
scrapy/exceptions.py
{ "start": 1880, "end": 2048 }
class ____(Warning): """Warning category for deprecated features, since the default DeprecationWarning is silenced on Python 2.7+ """
ScrapyDeprecationWarning
python
prabhupant__python-ds
data_structures/bst/binary_search_tree.py
{ "start": 0, "end": 120 }
class ____(): def __init__(self, val): self.val = val self.left = None self.right = None
Node
python
pytorch__pytorch
torch/fx/experimental/symbolic_shapes.py
{ "start": 142498, "end": 142845 }
class ____: """ Locations of the guards that triggered lower and upper bound. """ lower: SLoc upper: SLoc @contextmanager def _suppress_guards(shape_env: ShapeEnv) -> Iterator[None]: shape_env._suppress_guards_enter() try: yield finally: shape_env._suppress_guards_exit() @dataclass
ValueRangesSLoc
python
sympy__sympy
sympy/stats/joint_rv.py
{ "start": 7003, "end": 8645 }
class ____: """Returns the sample from numpy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_numpy(dist, size, seed) @classmethod def _sample_numpy(cls, dist, size, seed): """Sample from NumPy.""" import numpy if seed is None or isinstance(seed, int): rand_state = numpy.random.default_rng(seed=seed) else: rand_state = seed numpy_rv_map = { 'MultivariateNormalDistribution': lambda dist, size: rand_state.multivariate_normal( mean=matrix2numpy(dist.mu, float).flatten(), cov=matrix2numpy(dist.sigma, float), size=size), 'MultivariateBetaDistribution': lambda dist, size: rand_state.dirichlet( alpha=list2numpy(dist.alpha, float).flatten(), size=size), 'MultinomialDistribution': lambda dist, size: rand_state.multinomial( n=int(dist.n), pvals=list2numpy(dist.p, float).flatten(), size=size) } sample_shape = { 'MultivariateNormalDistribution': lambda dist: matrix2numpy(dist.mu).flatten().shape, 'MultivariateBetaDistribution': lambda dist: list2numpy(dist.alpha).flatten().shape, 'MultinomialDistribution': lambda dist: list2numpy(dist.p).flatten().shape } dist_list = numpy_rv_map.keys() if dist.__class__.__name__ not in dist_list: return None samples = numpy_rv_map[dist.__class__.__name__](dist, prod(size)) return samples.reshape(size + sample_shape[dist.__class__.__name__](dist))
SampleJointNumpy
python
urllib3__urllib3
src/urllib3/exceptions.py
{ "start": 1513, "end": 1829 }
class ____(HTTPError): """Raised when the connection to a proxy fails.""" # The original error is also available as __cause__. original_error: Exception def __init__(self, message: str, error: Exception) -> None: super().__init__(message, error) self.original_error = error
ProxyError
python
astropy__astropy
astropy/io/fits/tests/test_fitsinfo.py
{ "start": 206, "end": 1655 }
class ____(FitsTestCase): def test_help(self): with pytest.raises(SystemExit) as e: fitsinfo.main(["-h"]) assert e.value.code == 0 def test_version(self, capsys): with pytest.raises(SystemExit) as e: fitsinfo.main(["--version"]) out = capsys.readouterr()[0] assert out == f"fitsinfo {version}" assert e.value.code == 0 def test_onefile(self, capsys): fitsinfo.main([self.data("arange.fits")]) out, err = capsys.readouterr() out = out.splitlines() assert len(out) == 3 assert out[1].startswith( "No. Name Ver Type Cards Dimensions Format" ) assert out[2].startswith( " 0 PRIMARY 1 PrimaryHDU 7 (11, 10, 7) int32" ) def test_multiplefiles(self, capsys): fitsinfo.main([self.data("arange.fits"), self.data("ascii.fits")]) out, err = capsys.readouterr() out = out.splitlines() assert len(out) == 8 assert out[1].startswith( "No. Name Ver Type Cards Dimensions Format" ) assert out[2].startswith( " 0 PRIMARY 1 PrimaryHDU 7 (11, 10, 7) int32" ) assert out[3] == "" assert out[7].startswith( " 1 1 TableHDU 20 5R x 2C [E10.4, I5]" )
TestFitsinfo
python
PyCQA__pylint
tests/functional/r/redefined/redefined_slots.py
{ "start": 313, "end": 502 }
class ____(Base): """Redefining the `a` & `deque.__name__` slots & adding the `d` & `e` slots""" __slots__ = ("a", deque.__name__, "d", "e") # [redefined-slots-in-subclass]
Subclass1
python
etianen__django-reversion
tests/test_app/migrations/0002_alter_testmodel_related_and_more.py
{ "start": 92, "end": 688 }
class ____(migrations.Migration): dependencies = [ ('test_app', '0001_initial'), ] operations = [ migrations.AlterField( model_name='testmodel', name='related', field=models.ManyToManyField(blank=True, related_name='+', to='test_app.testmodelrelated'), ), migrations.AlterField( model_name='testmodel', name='related_through', field=models.ManyToManyField(blank=True, related_name='+', through='test_app.TestModelThrough', to='test_app.testmodelrelated'), ), ]
Migration
python
python-openxml__python-docx
tests/opc/test_coreprops.py
{ "start": 368, "end": 7608 }
class ____: """Unit-test suite for `docx.opc.coreprops.CoreProperties` objects.""" @pytest.mark.parametrize( ("prop_name", "expected_value"), [ ("author", "python-docx"), ("category", ""), ("comments", ""), ("content_status", "DRAFT"), ("identifier", "GXS 10.2.1ab"), ("keywords", "foo bar baz"), ("language", "US-EN"), ("last_modified_by", "Steve Canny"), ("subject", "Spam"), ("title", "Word Document"), ("version", "1.2.88"), ], ) def it_knows_the_string_property_values( self, prop_name: str, expected_value: str, core_properties: CoreProperties ): actual_value = getattr(core_properties, prop_name) assert actual_value == expected_value @pytest.mark.parametrize( ("prop_name", "tagname", "value"), [ ("author", "dc:creator", "scanny"), ("category", "cp:category", "silly stories"), ("comments", "dc:description", "Bar foo to you"), ("content_status", "cp:contentStatus", "FINAL"), ("identifier", "dc:identifier", "GT 5.2.xab"), ("keywords", "cp:keywords", "dog cat moo"), ("language", "dc:language", "GB-EN"), ("last_modified_by", "cp:lastModifiedBy", "Billy Bob"), ("subject", "dc:subject", "Eggs"), ("title", "dc:title", "Dissertation"), ("version", "cp:version", "81.2.8"), ], ) def it_can_change_the_string_property_values(self, prop_name: str, tagname: str, value: str): coreProperties = self.coreProperties(tagname="", str_val="") core_properties = CoreProperties(cast("CT_CoreProperties", parse_xml(coreProperties))) setattr(core_properties, prop_name, value) assert core_properties._element.xml == self.coreProperties(tagname, value) @pytest.mark.parametrize( ("prop_name", "expected_datetime"), [ ("created", dt.datetime(2012, 11, 17, 16, 37, 40, tzinfo=dt.timezone.utc)), ("last_printed", dt.datetime(2014, 6, 4, 4, 28, tzinfo=dt.timezone.utc)), ("modified", None), ], ) def it_knows_the_date_property_values( self, prop_name: str, expected_datetime: dt.datetime, core_properties: CoreProperties ): actual_datetime = getattr(core_properties, prop_name) assert actual_datetime == expected_datetime @pytest.mark.parametrize( ("prop_name", "tagname", "value", "str_val", "attrs"), [ ( "created", "dcterms:created", dt.datetime(2001, 2, 3, 4, 5), "2001-02-03T04:05:00Z", ' xsi:type="dcterms:W3CDTF"', ), ( "last_printed", "cp:lastPrinted", dt.datetime(2014, 6, 4, 4), "2014-06-04T04:00:00Z", "", ), ( "modified", "dcterms:modified", dt.datetime(2005, 4, 3, 2, 1), "2005-04-03T02:01:00Z", ' xsi:type="dcterms:W3CDTF"', ), ], ) def it_can_change_the_date_property_values( self, prop_name: str, tagname: str, value: dt.datetime, str_val: str, attrs: str ): coreProperties = self.coreProperties(tagname="", str_val="") core_properties = CoreProperties(cast("CT_CoreProperties", parse_xml(coreProperties))) expected_xml = self.coreProperties(tagname, str_val, attrs) setattr(core_properties, prop_name, value) assert core_properties._element.xml == expected_xml @pytest.mark.parametrize( ("str_val", "expected_value"), [("42", 42), (None, 0), ("foobar", 0), ("-17", 0), ("32.7", 0)], ) def it_knows_the_revision_number(self, str_val: str | None, expected_value: int): tagname, str_val = ("cp:revision", str_val) if str_val else ("", "") coreProperties = self.coreProperties(tagname, str_val or "") core_properties = CoreProperties(cast("CT_CoreProperties", parse_xml(coreProperties))) assert core_properties.revision == expected_value @pytest.mark.parametrize(("value", "str_val"), [(42, "42")]) def it_can_change_the_revision_number(self, value: int, str_val: str): coreProperties = self.coreProperties(tagname="", str_val="") core_properties = CoreProperties(cast("CT_CoreProperties", parse_xml(coreProperties))) expected_xml = self.coreProperties("cp:revision", str_val) core_properties.revision = value assert core_properties._element.xml == expected_xml # fixtures ------------------------------------------------------- def coreProperties(self, tagname: str, str_val: str, attrs: str = "") -> str: tmpl = ( "<cp:coreProperties" ' xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties"' ' xmlns:dc="http://purl.org/dc/elements/1.1/"' ' xmlns:dcmitype="http://purl.org/dc/dcmitype/"' ' xmlns:dcterms="http://purl.org/dc/terms/"' ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' ">%s</cp:coreProperties>\n" ) if not tagname: child_element = "" elif not str_val: child_element = "\n <%s%s/>\n" % (tagname, attrs) else: child_element = "\n <%s%s>%s</%s>\n" % (tagname, attrs, str_val, tagname) return tmpl % child_element @pytest.fixture def core_properties(self): element = cast( "CT_CoreProperties", parse_xml( b"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" b'\n<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.o' b'rg/package/2006/metadata/core-properties" xmlns:dc="http://pur' b'l.org/dc/elements/1.1/" xmlns:dcmitype="http://purl.org/dc/dcm' b'itype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="h' b'ttp://www.w3.org/2001/XMLSchema-instance">\n' b" <cp:contentStatus>DRAFT</cp:contentStatus>\n" b" <dc:creator>python-docx</dc:creator>\n" b' <dcterms:created xsi:type="dcterms:W3CDTF">2012-11-17T11:07:' b"40-05:30</dcterms:created>\n" b" <dc:description/>\n" b" <dc:identifier>GXS 10.2.1ab</dc:identifier>\n" b" <dc:language>US-EN</dc:language>\n" b" <cp:lastPrinted>2014-06-04T04:28:00Z</cp:lastPrinted>\n" b" <cp:keywords>foo bar baz</cp:keywords>\n" b" <cp:lastModifiedBy>Steve Canny</cp:lastModifiedBy>\n" b" <cp:revision>4</cp:revision>\n" b" <dc:subject>Spam</dc:subject>\n" b" <dc:title>Word Document</dc:title>\n" b" <cp:version>1.2.88</cp:version>\n" b"</cp:coreProperties>\n" ), ) return CoreProperties(element)
DescribeCoreProperties
python
django__django
django/contrib/gis/db/models/lookups.py
{ "start": 6814, "end": 6914 }
class ____(GISLookup): lookup_name = "coveredby" @BaseSpatialField.register_lookup
CoveredByLookup
python
ansible__ansible
test/units/module_utils/facts/test_collector.py
{ "start": 4610, "end": 12919 }
class ____(unittest.TestCase): def test_none(self): res = collector.get_collector_names() self.assertIsInstance(res, set) self.assertEqual(res, set([])) def test_empty_sets(self): res = collector.get_collector_names(valid_subsets=frozenset([]), minimal_gather_subset=frozenset([]), gather_subset=[]) self.assertIsInstance(res, set) self.assertEqual(res, set([])) def test_empty_valid_and_min_with_all_gather_subset(self): res = collector.get_collector_names(valid_subsets=frozenset([]), minimal_gather_subset=frozenset([]), gather_subset=['all']) self.assertIsInstance(res, set) self.assertEqual(res, set([])) def test_one_valid_with_all_gather_subset(self): valid_subsets = frozenset(['my_fact']) res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=frozenset([]), gather_subset=['all']) self.assertIsInstance(res, set) self.assertEqual(res, set(['my_fact'])) def _compare_res(self, gather_subset1, gather_subset2, valid_subsets=None, min_subset=None): valid_subsets = valid_subsets or frozenset() minimal_gather_subset = min_subset or frozenset() res1 = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=gather_subset1) res2 = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=gather_subset2) return res1, res2 def test_not_all_other_order(self): valid_subsets = frozenset(['min_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['min_fact']) res1, res2 = self._compare_res(['!all', 'whatever'], ['whatever', '!all'], valid_subsets=valid_subsets, min_subset=minimal_gather_subset) self.assertEqual(res1, res2) self.assertEqual(res1, set(['min_fact', 'whatever'])) def test_not_all_other_order_min(self): valid_subsets = frozenset(['min_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['min_fact']) res1, res2 = self._compare_res(['!min_fact', 'whatever'], ['whatever', '!min_fact'], valid_subsets=valid_subsets, min_subset=minimal_gather_subset) self.assertEqual(res1, res2) self.assertEqual(res1, set(['whatever'])) def test_one_minimal_with_all_gather_subset(self): my_fact = 'my_fact' valid_subsets = frozenset([my_fact]) minimal_gather_subset = valid_subsets res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=['all']) self.assertIsInstance(res, set) self.assertEqual(res, set(['my_fact'])) def test_with_all_gather_subset(self): valid_subsets = frozenset(['my_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['my_fact']) # even with '!all', the minimal_gather_subset should be returned res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=['all']) self.assertIsInstance(res, set) self.assertEqual(res, set(['my_fact', 'something_else', 'whatever'])) def test_one_minimal_with_not_all_gather_subset(self): valid_subsets = frozenset(['my_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['my_fact']) # even with '!all', the minimal_gather_subset should be returned res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=['!all']) self.assertIsInstance(res, set) self.assertEqual(res, set(['my_fact'])) def test_gather_subset_excludes(self): valid_subsets = frozenset(['my_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['min_fact', 'min_another']) # even with '!all', the minimal_gather_subset should be returned res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, # gather_subset=set(['all', '!my_fact', '!whatever'])) # gather_subset=['all', '!my_fact', '!whatever']) gather_subset=['!min_fact', '!whatever']) self.assertIsInstance(res, set) # min_another is in minimal_gather_subset, so always returned self.assertEqual(res, set(['min_another'])) def test_gather_subset_excludes_ordering(self): valid_subsets = frozenset(['my_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['my_fact']) res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=['!all', 'whatever']) self.assertIsInstance(res, set) # excludes are higher precedence than includes, so !all excludes everything # and then minimal_gather_subset is added. so '!all', 'other' == '!all' self.assertEqual(res, set(['my_fact', 'whatever'])) def test_gather_subset_excludes_min(self): valid_subsets = frozenset(['min_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['min_fact']) res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=['whatever', '!min']) self.assertIsInstance(res, set) # excludes are higher precedence than includes, so !all excludes everything # and then minimal_gather_subset is added. so '!all', 'other' == '!all' self.assertEqual(res, set(['whatever'])) def test_gather_subset_excludes_min_and_all(self): valid_subsets = frozenset(['min_fact', 'something_else', 'whatever']) minimal_gather_subset = frozenset(['min_fact']) res = collector.get_collector_names(valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=['whatever', '!all', '!min']) self.assertIsInstance(res, set) # excludes are higher precedence than includes, so !all excludes everything # and then minimal_gather_subset is added. so '!all', 'other' == '!all' self.assertEqual(res, set(['whatever'])) def test_invalid_gather_subset(self): valid_subsets = frozenset(['my_fact', 'something_else']) minimal_gather_subset = frozenset(['my_fact']) self.assertRaisesRegex(TypeError, r'Bad subset .* given to Ansible.*allowed\:.*all,.*my_fact.*', collector.get_collector_names, valid_subsets=valid_subsets, minimal_gather_subset=minimal_gather_subset, gather_subset=['my_fact', 'not_a_valid_gather_subset'])
TestGetCollectorNames
python
langchain-ai__langchain
libs/core/langchain_core/stores.py
{ "start": 5852, "end": 7862 }
class ____(BaseStore[str, V], Generic[V]): """In-memory implementation of the BaseStore using a dictionary.""" def __init__(self) -> None: """Initialize an empty store.""" self.store: dict[str, V] = {} @override def mget(self, keys: Sequence[str]) -> list[V | None]: return [self.store.get(key) for key in keys] @override async def amget(self, keys: Sequence[str]) -> list[V | None]: return self.mget(keys) @override def mset(self, key_value_pairs: Sequence[tuple[str, V]]) -> None: for key, value in key_value_pairs: self.store[key] = value @override async def amset(self, key_value_pairs: Sequence[tuple[str, V]]) -> None: return self.mset(key_value_pairs) @override def mdelete(self, keys: Sequence[str]) -> None: for key in keys: if key in self.store: del self.store[key] @override async def amdelete(self, keys: Sequence[str]) -> None: self.mdelete(keys) def yield_keys(self, prefix: str | None = None) -> Iterator[str]: """Get an iterator over keys that match the given prefix. Args: prefix: The prefix to match. Yields: The keys that match the given prefix. """ if prefix is None: yield from self.store.keys() else: for key in self.store: if key.startswith(prefix): yield key async def ayield_keys(self, prefix: str | None = None) -> AsyncIterator[str]: """Async get an async iterator over keys that match the given prefix. Args: prefix: The prefix to match. Yields: The keys that match the given prefix. """ if prefix is None: for key in self.store: yield key else: for key in self.store: if key.startswith(prefix): yield key
InMemoryBaseStore
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/lookup_ops_test.py
{ "start": 112519, "end": 114286 }
class ____(test.TestCase): def test_index_to_string_table_from_tensor(self): vocabulary_list = constant_op.constant(["brain", "salad", "surgery"]) table = lookup_ops.index_to_string_table_from_tensor( vocabulary_list=vocabulary_list) indices = constant_op.constant([0, 1, 2, 3], dtypes.int64) features = table.lookup(indices) if not context.executing_eagerly(): with self.assertRaises(errors_impl.OpError): self.evaluate(features) self.evaluate(lookup_ops.tables_initializer()) self.assertAllEqual((b"brain", b"salad", b"surgery", b"UNK"), self.evaluate(features)) def test_duplicate_entries(self): vocabulary_list = constant_op.constant(["hello", "hello"]) table = lookup_ops.index_to_string_table_from_tensor( vocabulary_list=vocabulary_list) indices = constant_op.constant([0, 1, 4], dtypes.int64) features = table.lookup(indices) self.evaluate(lookup_ops.tables_initializer()) self.assertAllEqual((b"hello", b"hello", b"UNK"), self.evaluate(features)) def test_index_to_string_with_default_value(self): default_value = b"NONE" vocabulary_list = constant_op.constant(["brain", "salad", "surgery"]) table = lookup_ops.index_to_string_table_from_tensor( vocabulary_list=vocabulary_list, default_value=default_value) indices = constant_op.constant([1, 2, 4], dtypes.int64) features = table.lookup(indices) if not context.executing_eagerly(): with self.assertRaises(errors_impl.OpError): self.evaluate(features) self.evaluate(lookup_ops.tables_initializer()) self.assertAllEqual((b"salad", b"surgery", default_value), self.evaluate(features))
IndexToStringTableFromTensorTest
python
huggingface__transformers
src/transformers/models/qwen3_vl/modeling_qwen3_vl.py
{ "start": 59575, "end": 73549 }
class ____(Qwen3VLPreTrainedModel, GenerationMixin): _checkpoint_conversion_mapping = {} _tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"} # Reference: fix gemma3 grad acc #37208 accepts_loss_kwargs = False config: Qwen3VLConfig def __init__(self, config): super().__init__(config) self.model = Qwen3VLModel(config) self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False) self.post_init() def get_input_embeddings(self): return self.model.get_input_embeddings() def set_input_embeddings(self, value): self.model.set_input_embeddings(value) def get_video_features( self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None ): return self.model.get_video_features(pixel_values_videos, video_grid_thw) def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None): return self.model.get_image_features(pixel_values, image_grid_thw) @check_model_inputs() def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.Tensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_grid_thw: Optional[torch.LongTensor] = None, video_grid_thw: Optional[torch.LongTensor] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, Qwen3VLCausalLMOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*): The temporal, height and width of feature shape of each image in LLM. video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*): The temporal, height and width of feature shape of each video in LLM. Example: ```python >>> from transformers import AutoProcessor, Qwen3VLForConditionalGeneration >>> model = Qwen3VLForConditionalGeneration.from_pretrained("Qwen/Qwen3-VL-8B-Instruct") >>> processor = AutoProcessor.from_pretrained("Qwen/Qwen3-VL-8B-Instruct") >>> messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg", }, {"type": "text", "text": "Describe the image."}, ], } ] >>> inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) >>> # Generate >>> generated_ids = model.generate(**inputs, max_new_tokens=1024) >>> generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)] >>> output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] >>> print(output_text) ``` """ outputs = self.model( input_ids=input_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, position_ids=position_ids, attention_mask=attention_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, cache_position=cache_position, **kwargs, ) hidden_states = outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size) return Qwen3VLCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, rope_deltas=outputs.rope_deltas, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, position_ids=None, use_cache=True, pixel_values=None, pixel_values_videos=None, image_grid_thw=None, video_grid_thw=None, **kwargs, ): # Overwritten -- in specific circumstances we don't want to forward image inputs to the model model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, attention_mask=attention_mask, inputs_embeds=inputs_embeds, cache_position=cache_position, position_ids=position_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_grid_thw=image_grid_thw, video_grid_thw=video_grid_thw, use_cache=use_cache, **kwargs, ) # Qwen3VL position_ids are prepareed with rope_deltas in forward model_inputs["position_ids"] = None if cache_position[0] != 0: model_inputs["pixel_values"] = None model_inputs["pixel_values_videos"] = None return model_inputs def _get_image_nums_and_video_nums( self, input_ids: Optional[torch.LongTensor], inputs_embeds: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Get the number of images and videos for each sample to calculate the separation length of the sample tensor. These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Returns: image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`) video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`) """ image_token_id = self.config.image_token_id video_token_id = self.config.video_token_id vision_start_token_id = self.config.vision_start_token_id if inputs_embeds is not None: vision_start_mask = ( inputs_embeds == self.get_input_embeddings()( torch.tensor(vision_start_token_id, dtype=torch.long, device=inputs_embeds.device) ) )[..., 0] image_mask = ( inputs_embeds == self.get_input_embeddings()( torch.tensor(image_token_id, dtype=torch.long, device=inputs_embeds.device) ) )[..., 0] video_mask = ( inputs_embeds == self.get_input_embeddings()( torch.tensor(video_token_id, dtype=torch.long, device=inputs_embeds.device) ) )[..., 0] else: vision_start_mask = input_ids == vision_start_token_id image_mask = input_ids == image_token_id video_mask = input_ids == video_token_id vision_first_mask = torch.roll(vision_start_mask, shifts=1, dims=1) image_nums = torch.sum(vision_first_mask & image_mask, dim=1) video_nums = torch.sum(vision_first_mask & video_mask, dim=1) return image_nums, video_nums def _expand_inputs_for_generation( self, expand_size: int = 1, is_encoder_decoder: bool = False, input_ids: Optional[torch.LongTensor] = None, **model_kwargs, ) -> tuple[torch.LongTensor, dict[str, Any]]: # Overwritten -- Qwen3VL use timestamps and remove second_per_grid_ts # Support for expanding tensors without a batch size dimension # e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw # pixel_values.shape[0] is sum(seqlen_images for samples) # image_grid_thw.shape[0] is sum(num_images for samples) if expand_size == 1: return input_ids, model_kwargs visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw"] def _expand_dict_for_generation_visual(dict_to_expand): image_grid_thw = model_kwargs.get("image_grid_thw", None) video_grid_thw = model_kwargs.get("video_grid_thw", None) image_nums, video_nums = self._get_image_nums_and_video_nums( input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None) ) # video_nums: (batch_size,) # since video_nums is the number of videos in the input dependent on the input_ids(vision_start), # but qwen3vl append vision_start to each frame of each video, so we need to recover the real video_nums according to video_grid_thw if video_grid_thw is not None: cumulative_frame_counts = torch.cumsum(video_grid_thw[:, 0], dim=0) cumulative_token_video_counts = torch.cumsum(video_nums, dim=0) # Find video boundaries in cumulative_frame_counts video_boundary_indices = torch.searchsorted(cumulative_frame_counts, cumulative_token_video_counts) # example: video_boundary_indices = [3, 5] means video_nums = [4, 2] video_nums = torch.diff(torch.cat([-video_boundary_indices.new_ones(1), video_boundary_indices])) def _repeat_interleave_samples(x, lengths, repeat_times): samples = torch.split(x, lengths) repeat_args = [repeat_times] + [1] * (x.dim() - 1) result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0) return result for key in dict_to_expand: if key == "pixel_values": # split images into samples samples = torch.split(image_grid_thw, list(image_nums)) # compute the sequence length of images for each sample lengths = [torch.prod(sample, dim=1).sum() for sample in samples] dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "image_grid_thw": # get the num of images for each sample lengths = list(image_nums) dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "pixel_values_videos": samples = torch.split(video_grid_thw, list(video_nums)) lengths = [torch.prod(sample, dim=1).sum() for sample in samples] dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) elif key == "video_grid_thw": lengths = list(video_nums) dict_to_expand[key] = _repeat_interleave_samples( dict_to_expand[key], lengths=lengths, repeat_times=expand_size ) return dict_to_expand def _expand_dict_for_generation(dict_to_expand): for key in dict_to_expand: if ( key != "cache_position" and dict_to_expand[key] is not None and isinstance(dict_to_expand[key], torch.Tensor) and key not in visual_keys ): dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0) return dict_to_expand model_kwargs = _expand_dict_for_generation_visual(model_kwargs) if input_ids is not None: input_ids = input_ids.repeat_interleave(expand_size, dim=0) model_kwargs = _expand_dict_for_generation(model_kwargs) if is_encoder_decoder: if model_kwargs.get("encoder_outputs") is None: raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.") model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"]) return input_ids, model_kwargs __all__ = [ "Qwen3VLVisionModel", "Qwen3VLForConditionalGeneration", "Qwen3VLModel", "Qwen3VLPreTrainedModel", "Qwen3VLTextModel", ]
Qwen3VLForConditionalGeneration
python
sqlalchemy__sqlalchemy
test/orm/test_eager_relations.py
{ "start": 151302, "end": 161257 }
class ____(fixtures.MappedTest): @classmethod def define_tables(cls, metadata): Table( "nodes", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("parent_id", Integer, ForeignKey("nodes.id")), Column("data", String(30)), ) def test_basic(self): nodes = self.tables.nodes class Node(ComparableEntity): def append(self, node): self.children.append(node) self.mapper_registry.map_imperatively( Node, nodes, properties={ "children": relationship( Node, lazy="joined", join_depth=3, order_by=nodes.c.id ) }, ) sess = fixture_session() n1 = Node(data="n1") n1.append(Node(data="n11")) n1.append(Node(data="n12")) n1.append(Node(data="n13")) n1.children[1].append(Node(data="n121")) n1.children[1].append(Node(data="n122")) n1.children[1].append(Node(data="n123")) sess.add(n1) sess.flush() sess.expunge_all() def go(): d = sess.query(Node).filter_by(data="n1").all()[0] eq_( Node( data="n1", children=[ Node(data="n11"), Node( data="n12", children=[ Node(data="n121"), Node(data="n122"), Node(data="n123"), ], ), Node(data="n13"), ], ), d, ) self.assert_sql_count(testing.db, go, 1) sess.expunge_all() def go(): d = sess.query(Node).filter_by(data="n1").first() eq_( Node( data="n1", children=[ Node(data="n11"), Node( data="n12", children=[ Node(data="n121"), Node(data="n122"), Node(data="n123"), ], ), Node(data="n13"), ], ), d, ) self.assert_sql_count(testing.db, go, 1) def test_lazy_fallback_doesnt_affect_eager(self): nodes = self.tables.nodes class Node(ComparableEntity): def append(self, node): self.children.append(node) self.mapper_registry.map_imperatively( Node, nodes, properties={ "children": relationship( Node, lazy="joined", join_depth=1, order_by=nodes.c.id ) }, ) sess = fixture_session() n1 = Node(data="n1") n1.append(Node(data="n11")) n1.append(Node(data="n12")) n1.append(Node(data="n13")) n1.children[1].append(Node(data="n121")) n1.children[1].append(Node(data="n122")) n1.children[1].append(Node(data="n123")) sess.add(n1) sess.flush() sess.expunge_all() # eager load with join depth 1. when eager load of 'n1' hits the # children of 'n12', no columns are present, eager loader degrades to # lazy loader; fine. but then, 'n12' is *also* in the first level of # columns since we're loading the whole table. when those rows # arrive, now we *can* eager load its children and an eager collection # should be initialized. essentially the 'n12' instance is present in # not just two different rows but two distinct sets of columns in this # result set. def go(): allnodes = sess.query(Node).order_by(Node.data).all() n12 = allnodes[2] eq_(n12.data, "n12") eq_( [Node(data="n121"), Node(data="n122"), Node(data="n123")], list(n12.children), ) self.assert_sql_count(testing.db, go, 1) def test_with_deferred(self): nodes = self.tables.nodes class Node(ComparableEntity): def append(self, node): self.children.append(node) self.mapper_registry.map_imperatively( Node, nodes, properties={ "children": relationship( Node, lazy="joined", join_depth=3, order_by=nodes.c.id ), "data": deferred(nodes.c.data), }, ) sess = fixture_session() n1 = Node(data="n1") n1.append(Node(data="n11")) n1.append(Node(data="n12")) sess.add(n1) sess.flush() sess.expunge_all() def go(): eq_( Node(data="n1", children=[Node(data="n11"), Node(data="n12")]), sess.query(Node).order_by(Node.id).first(), ) self.assert_sql_count(testing.db, go, 4) sess.expunge_all() def go(): eq_( Node(data="n1", children=[Node(data="n11"), Node(data="n12")]), sess.query(Node) .options(undefer(Node.data)) .order_by(Node.id) .first(), ) self.assert_sql_count(testing.db, go, 3) sess.expunge_all() def go(): eq_( Node(data="n1", children=[Node(data="n11"), Node(data="n12")]), sess.query(Node) .options( undefer(Node.data), defaultload(Node.children).undefer(Node.data), ) .first(), ) self.assert_sql_count(testing.db, go, 1) def test_options(self): nodes = self.tables.nodes class Node(ComparableEntity): def append(self, node): self.children.append(node) self.mapper_registry.map_imperatively( Node, nodes, properties={ "children": relationship( Node, lazy="select", order_by=nodes.c.id ) }, ) sess = fixture_session() n1 = Node(data="n1") n1.append(Node(data="n11")) n1.append(Node(data="n12")) n1.append(Node(data="n13")) n1.children[1].append(Node(data="n121")) n1.children[1].append(Node(data="n122")) n1.children[1].append(Node(data="n123")) sess.add(n1) sess.flush() sess.expunge_all() def go(): d = ( sess.query(Node) .filter_by(data="n1") .order_by(Node.id) .options(joinedload(Node.children, Node.children)) .first() ) eq_( Node( data="n1", children=[ Node(data="n11"), Node( data="n12", children=[ Node(data="n121"), Node(data="n122"), Node(data="n123"), ], ), Node(data="n13"), ], ), d, ) self.assert_sql_count(testing.db, go, 2) def go(): sess.query(Node).order_by(Node.id).filter_by(data="n1").options( joinedload(Node.children, Node.children) ).first() # test that the query isn't wrapping the initial query for eager # loading. self.assert_sql_execution( testing.db, go, CompiledSQL( "SELECT nodes.id AS nodes_id, nodes.parent_id AS " "nodes_parent_id, nodes.data AS nodes_data FROM nodes " "WHERE nodes.data = :data_1 ORDER BY nodes.id LIMIT :param_1", {"data_1": "n1"}, ), ) def test_no_depth(self): nodes = self.tables.nodes class Node(ComparableEntity): def append(self, node): self.children.append(node) self.mapper_registry.map_imperatively( Node, nodes, properties={"children": relationship(Node, lazy="joined")}, ) sess = fixture_session() n1 = Node(data="n1") n1.append(Node(data="n11")) n1.append(Node(data="n12")) n1.append(Node(data="n13")) n1.children[1].append(Node(data="n121")) n1.children[1].append(Node(data="n122")) n1.children[1].append(Node(data="n123")) sess.add(n1) sess.flush() sess.expunge_all() def go(): d = sess.query(Node).filter_by(data="n1").first() eq_( Node( data="n1", children=[ Node(data="n11"), Node( data="n12", children=[ Node(data="n121"), Node(data="n122"), Node(data="n123"), ], ), Node(data="n13"), ], ), d, ) self.assert_sql_count(testing.db, go, 3)
SelfReferentialEagerTest
python
spack__spack
lib/spack/spack/test/entry_points.py
{ "start": 246, "end": 764 }
class ____: def __init__(self, tmp_path: pathlib.Path): self.dir = tmp_path self.name = "mypackage_config" def load(self): etc_path = self.dir.joinpath("spack/etc") etc_path.mkdir(exist_ok=True, parents=True) f = self.dir / "spack/etc/config.yaml" with open(f, "w", encoding="utf-8") as fh: fh.write("config:\n install_tree:\n root: /spam/opt\n") def ep(): return self.dir / "spack/etc" return ep
MockConfigEntryPoint
python
pytorch__pytorch
test/lazy/test_ts_opinfo.py
{ "start": 6021, "end": 11208 }
class ____(TestCase): @ops( [ op for op in op_db if op.name in LAZY_OPS_LIST and op.name not in SKIP_RUNTIME_ERROR_LIST and op.name not in FUNCTIONAL_DECOMPOSE_LIST and op.formatted_name not in SKIP_VARIANT_LIST ], allowed_dtypes=(torch.float,), ) def test_dispatched_to_lazy(self, device, dtype, op): def get_name(op): # noqa: F841 l = [op.name] if op.variant_test_name != "": l.append(op.variant_test_name) return ".".join(l) global HAS_SYMINT_SUFFIX, FALLBACK_LIST samples = op.sample_inputs("lazy", dtype, requires_grad=False) sample = next(iter(samples)) args = [sample.input] + list(sample.args) kwargs = sample.kwargs torch._lazy.mark_step() torch._lazy.wait_device_ops() torch._lazy.metrics.reset() op(*args, **kwargs) torch._lazy.mark_step() torch._lazy.wait_device_ops() prefix = "aten" if op.name in FALLBACK_LIST else "lazy" symint_suffix = "_symint" if op.name in HAS_SYMINT_SUFFIX else "" metrics = remove_suffixes(torch._lazy.metrics.counter_names()) cands = [f"{prefix}::{op.name}{symint_suffix}"] # check aliases for alias in op.aliases: cands.append(f"{prefix}::{alias.name}{symint_suffix}") self.assertTrue( any(c in metrics for c in cands), f"none of {cands} not found in {metrics}" ) @ops( [ op for op in op_db if op.name in LAZY_OPS_LIST and op.name not in SKIP_RUNTIME_ERROR_LIST | SKIP_INCORRECT_RESULTS_LIST ], allowed_dtypes=(torch.float,), ) # noqa: B950 def test_correctness(self, device, dtype, op): test_device = get_test_device() def clone_to_device(input, dev): if isinstance(input, torch.Tensor): return input.detach().clone().to(device=dev) if isinstance(input, Sequence) and not isinstance(input, str): return tuple(map(functools.partial(clone_to_device, dev=dev), input)) return input def assert_allclose_rec(t): a, b = t self.assertEqual(type(a), type(b)) if isinstance(a, torch.Tensor): self.assertTrue( torch.allclose(clone_to_device(a, test_device), b, atol=1e-4) ) if isinstance(a, Sequence): map(assert_allclose_rec, zip(a, b)) samples = op.sample_inputs("lazy", dtype, requires_grad=False) for sample in samples: # Need to run mark step so that all random ops are computed in the right order torch._lazy.mark_step() args = [sample.input] + list(sample.args) kwargs = sample.kwargs copy_args = clone_to_device(args, test_device) r_exp = op(*copy_args, **kwargs) r_actual = op(*args, **kwargs) torch._lazy.mark_step() assert_allclose_rec((r_actual, r_exp)) @ops( [ op for op in op_db if op.name in LAZY_OPS_LIST and op.name not in SKIP_RUNTIME_ERROR_LIST | SKIP_INCORRECT_RESULTS_LIST ], allowed_dtypes=(torch.float,), ) # noqa: B950 def test_correctness_with_reusing_ir(self, device, dtype, op): torch._lazy.config.set_reuse_ir(True) test_device = get_test_device() def clone_to_device(input, dev): if isinstance(input, torch.Tensor): return input.detach().clone().to(device=dev) if isinstance(input, Sequence) and not isinstance(input, str): return tuple(map(functools.partial(clone_to_device, dev=dev), input)) return input def assert_allclose_rec(t): a, b = t self.assertEqual(type(a), type(b)) if isinstance(a, torch.Tensor): self.assertTrue( torch.allclose(clone_to_device(a, test_device), b, atol=1e-4) ) if isinstance(a, Sequence): map(assert_allclose_rec, zip(a, b)) samples = op.sample_inputs("lazy", dtype, requires_grad=False) for sample in samples: # Need to run mark step so that all random ops are computed in the right order torch._lazy.mark_step() args = [sample.input] + list(sample.args) kwargs = sample.kwargs copy_args = clone_to_device(args, test_device) r_exp = op(*copy_args, **kwargs) r_actual = op(*args, **kwargs) torch._lazy.mark_step() assert_allclose_rec((r_actual, r_exp)) torch._lazy.ir_cache.reset() torch._lazy.config.set_reuse_ir(False) # TODO: after we move to master, add Lazy as a new Device here: # https://github.com/pytorch/pytorch/blob/master/torch/testing/_internal/common_device_type.py#L532 instantiate_device_type_tests(TestLazyOpInfo, globals(), only_for="cpu")
TestLazyOpInfo