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
pytorch__pytorch
test/fx/test_z3_gradual_types.py
{ "start": 85191, "end": 87827 }
class ____(unittest.TestCase): def test_resnet50_unsat(self): traced = symbolic_trace(models.resnet50()) for n in traced.graph.nodes: n.type = Dyn constraints = transform_all_constraints(traced, counter=0) solver = z3.Solver() solver.add(constraints) input = z3.Const(1, tensor_type) # input with 3 dimensions solver.add(input == tensor_type.tensor3(D(1, 1), D(1, 3), D(1, 224))) self.assertEqual(solver.check(), z3.unsat) def test_resnet50(self): traced = symbolic_trace(models.resnet50()) for n in traced.graph.nodes: n.type = Dyn sample_input = torch.randn(1, 3, 224, 224) res = models.resnet50().forward(sample_input).size() constraints = transform_all_constraints(traced, counter=0) solver = z3.Solver() solver.add(constraints) self.assertEqual(solver.check(), z3.sat) linear = z3.Const(650, tensor_type) input = z3.Const(1, tensor_type) solver.add(input == tensor_type.tensor4(D(1, 1), D(1, 3), D(1, 224), D(1, 224))) self.assertEqual(solver.check(), z3.sat) assert solver.model()[linear] == tensor_type.tensor2(D(1, res[0]), D(1, res[1])) def test_resnet502(self): traced = symbolic_trace(models.resnet50()) for n in traced.graph.nodes: n.type = Dyn constraints = transform_all_constraints(traced, counter=0) solver = z3.Solver() solver.add(constraints) linear = z3.Const(650, tensor_type) input = z3.Const(1, tensor_type) batch = z3.Int("b") solver.add( input == tensor_type.tensor4(D(1, batch), D(1, 3), D(1, 224), D(1, 224)) ) solver.add(batch > 4) solver.check() assert solver.model()[batch] == solver.model()[linear].arg(0).arg(1) def test_resnet503(self): traced = symbolic_trace(models.resnet50()) for n in traced.graph.nodes: n.type = Dyn constraints = transform_all_constraints(traced, counter=0) solver = z3.Solver() solver.add(constraints) linear = z3.Const(650, tensor_type) input = z3.Const(1, tensor_type) batch, d1, d2 = z3.Ints("b d1 d2") solver.add( input == tensor_type.tensor4(D(1, batch), D(1, 3), D(1, 224), D(1, 224)) ) solver.add(linear == tensor_type.tensor2(D(1, d1), D(1, d2))) self.assertEqual(solver.check(), z3.sat) solver.add(batch != d1) self.assertEqual(solver.check(), z3.unsat) @skipIfNoTorchVision
TestResNet
python
getsentry__sentry
src/sentry/seer/models.py
{ "start": 2116, "end": 2249 }
class ____(BaseModel): preference: SeerProjectPreference | None code_mapping_repos: list[SeerRepoDefinition]
PreferenceResponse
python
apache__airflow
helm-tests/tests/helm_tests/other/test_redis.py
{ "start": 20159, "end": 21553 }
class ____: """Tests redis service.""" @pytest.mark.parametrize( ("redis_values", "expected"), [ ({"redis": {"service": {"type": "ClusterIP"}}}, "ClusterIP"), ({"redis": {"service": {"type": "NodePort"}}}, "NodePort"), ({"redis": {"service": {"type": "LoadBalancer"}}}, "LoadBalancer"), ], ) def test_redis_service_type(self, redis_values, expected): docs = render_chart( values=redis_values, show_only=["templates/redis/redis-service.yaml"], ) assert expected == jmespath.search("spec.type", docs[0]) def test_redis_service_nodeport(self): docs = render_chart( values={ "redis": { "service": {"type": "NodePort", "nodePort": 11111}, }, }, show_only=["templates/redis/redis-service.yaml"], ) assert jmespath.search("spec.ports[0].nodePort", docs[0]) == 11111 def test_redis_service_clusterIP(self): docs = render_chart( values={ "redis": { "service": {"type": "ClusterIP", "clusterIP": "127.0.0.1"}, }, }, show_only=["templates/redis/redis-service.yaml"], ) assert jmespath.search("spec.clusterIP", docs[0]) == "127.0.0.1"
TestRedisService
python
ray-project__ray
python/ray/util/collective/collective.py
{ "start": 1798, "end": 29043 }
class ____(object): """Use this class to manage the collective groups we created so far. Each process will have an instance of `GroupManager`. Each process could belong to multiple collective groups. The membership information and other metadata are stored in the global `_group_mgr` object. """ def __init__(self): self._name_group_map = {} def create_collective_group( self, backend, world_size, rank, group_name, gloo_timeout ): """The entry to create new collective groups in the manager. Put the registration and the group information into the manager metadata as well. """ backend = types.Backend(backend) if backend == types.Backend.MPI: raise RuntimeError("Ray does not support MPI.") elif backend == types.Backend.GLOO or backend == types.Backend.TORCH_GLOO: # Rendezvous: ensure a MASTER_ADDR:MASTER_PORT is published in internal_kv. metadata_key = _get_master_addr_key(group_name) if rank == 0: addr, port = _get_address_and_port() _internal_kv._internal_kv_put(metadata_key, f"{addr}:{port}") else: # Wait until rank 0 publishes the metadata or timeout. deadline_s = time.time() + ( gloo_timeout / 1000.0 if gloo_timeout else 30.0 ) while True: meta = _internal_kv._internal_kv_get(metadata_key) if meta is not None: break if time.time() > deadline_s: raise TimeoutError( f"Timed out waiting for GLOO rendezvous metadata for group '{group_name}'." ) time.sleep(0.05) logger.debug( "Creating torch.distributed GLOO group: '{}'...".format(group_name) ) g = TorchGLOOGroup(world_size, rank, group_name, gloo_timeout) elif backend == types.Backend.NCCL: _check_backend_availability(backend) logger.debug("Creating NCCL group: '{}'...".format(group_name)) g = NCCLGroup(world_size, rank, group_name) elif backend == types.Backend.NIXL: _check_backend_availability(backend) logger.debug("Creating NIXL Backend: '{}'...".format(group_name)) g = NixlBackend() else: raise RuntimeError(f"Unexpected backend: {backend}") self._name_group_map[group_name] = g return self._name_group_map[group_name] def is_group_exist(self, group_name): return group_name in self._name_group_map def get_group_by_name(self, group_name): """Get the collective group handle by its name.""" if not self.is_group_exist(group_name): logger.warning("The group '{}' is not initialized.".format(group_name)) return None return self._name_group_map[group_name] def destroy_collective_group(self, group_name): """Group destructor.""" if not self.is_group_exist(group_name): logger.warning("The group '{}' does not exist.".format(group_name)) return # release the collective group resource g = self._name_group_map[group_name] # clean up the dicts del self._name_group_map[group_name] # Release the communicator resources g.destroy_group() # Release the detached actors spawned by `create_collective_group()` name = "info_" + group_name try: store = ray.get_actor(name) ray.kill(store) except ValueError: pass _group_mgr = GroupManager() # This lock is used to make external calls to the _group_mgr thread-safe. _group_mgr_lock = threading.Lock() def is_group_initialized(group_name): """Check if the group is initialized in this process by the group name.""" global _group_mgr global _group_mgr_lock with _group_mgr_lock: return _group_mgr.is_group_exist(group_name) def init_collective_group( world_size: int, rank: int, backend=types.Backend.NCCL, group_name: str = "default", gloo_timeout: int = 30000, ): """Initialize a collective group inside an actor process. Args: world_size: the total number of processes in the group. rank: the rank of the current process. backend: the CCL backend to use, NCCL or GLOO. group_name: the name of the collective group. Returns: None """ _check_inside_actor() backend = types.Backend(backend) _check_backend_availability(backend) global _group_mgr global _group_mgr_lock # TODO(Hao): implement a group auto-counter. if not group_name: raise ValueError("group_name '{}' needs to be a string.".format(group_name)) with _group_mgr_lock: if _group_mgr.is_group_exist(group_name): raise RuntimeError("Trying to initialize a group twice.") assert world_size > 0 assert rank >= 0 assert rank < world_size _group_mgr.create_collective_group( backend, world_size, rank, group_name, gloo_timeout ) def create_collective_group( actors, world_size: int, ranks: List[int], backend=types.Backend.NCCL, group_name: str = "default", gloo_timeout: int = 30000, ): """Declare a list of actors as a collective group. Note: This function should be called in a driver process. Args: actors: a list of actors to be set in a collective group. world_size: the total number of processes in the group. ranks (List[int]): the rank of each actor. backend: the CCL backend to use, NCCL or GLOO. group_name: the name of the collective group. Returns: None """ backend = types.Backend(backend) _check_backend_availability(backend) name = "info_" + group_name try: ray.get_actor(name) raise RuntimeError("Trying to initialize a group twice.") except ValueError: pass if len(ranks) != len(actors): raise RuntimeError( "Each actor should correspond to one rank. Got '{}' " "ranks but '{}' actors".format(len(ranks), len(actors)) ) if set(ranks) != set(range(len(ranks))): raise RuntimeError( "Ranks must be a permutation from 0 to '{}'. Got '{}'.".format( len(ranks), "".join([str(r) for r in ranks]) ) ) if world_size <= 0: raise RuntimeError( "World size must be greater than zero. Got '{}'.".format(world_size) ) if not all(ranks) >= 0: raise RuntimeError("Ranks must be non-negative.") if not all(ranks) < world_size: raise RuntimeError("Ranks cannot be greater than world_size.") # avoid a circular dependency from ray.util.collective.util import Info # store the information into a NamedActor that can be accessed later. name = "info_" + group_name actors_id = [a._ray_actor_id for a in actors] # TODO (Dacheng): how do we recycle this name actor? info = Info.options(name=name, lifetime="detached").remote() ray.get([info.set_info.remote(actors_id, world_size, ranks, backend, gloo_timeout)]) # TODO (we need a declarative destroy() API here.) def destroy_collective_group(group_name: str = "default") -> None: """Destroy a collective group given its group name.""" _check_inside_actor() global _group_mgr global _group_mgr_lock with _group_mgr_lock: _group_mgr.destroy_collective_group(group_name) def get_rank(group_name: str = "default") -> int: """Return the rank of this process in the given group. Args: group_name: the name of the group to query Returns: the rank of this process in the named group, -1 if the group does not exist or the process does not belong to the group. """ _check_inside_actor() global _group_mgr global _group_mgr_lock with _group_mgr_lock: if not _group_mgr.is_group_exist(group_name): return -1 g = _group_mgr.get_group_by_name(group_name) return g.rank def get_collective_group_size(group_name: str = "default") -> int: """Return the size of the collective group with the given name. Args: group_name: the name of the group to query Returns: The world size of the collective group, -1 if the group does not exist or the process does not belong to the group. """ _check_inside_actor() global _group_mgr global _group_mgr_lock with _group_mgr_lock: if not _group_mgr.is_group_exist(group_name): return -1 g = _group_mgr.get_group_by_name(group_name) return g.world_size def allreduce(tensor, group_name: str = "default", op=types.ReduceOp.SUM): """Collective allreduce the tensor across the group. Args: tensor: the tensor to be all-reduced on this process. group_name: the collective group name to perform allreduce. op: The reduce operation. Returns: None """ _check_single_tensor_input(tensor) g = get_group_handle(group_name) opts = types.AllReduceOptions opts.reduceOp = op g.allreduce([tensor], opts) def allreduce_multigpu( tensor_list: list, group_name: str = "default", op=types.ReduceOp.SUM ): """Collective allreduce a list of tensors across the group. Args: tensor_list (List[tensor]): list of tensors to be allreduced, each on a GPU. group_name: the collective group name to perform allreduce. Returns: None """ if not types.cupy_available(): raise RuntimeError("Multigpu calls requires NCCL and Cupy.") _check_tensor_list_input(tensor_list) g = get_group_handle(group_name) opts = types.AllReduceOptions opts.reduceOp = op g.allreduce(tensor_list, opts) def barrier(group_name: str = "default"): """Barrier all processes in the collective group. Args: group_name: the name of the group to barrier. Returns: None """ g = get_group_handle(group_name) g.barrier() def reduce( tensor, dst_rank: int = 0, group_name: str = "default", op=types.ReduceOp.SUM ): """Reduce the tensor across the group to the destination rank. Args: tensor: the tensor to be reduced on this process. dst_rank: the rank of the destination process. group_name: the collective group name to perform reduce. op: The reduce operation. Returns: None """ _check_single_tensor_input(tensor) g = get_group_handle(group_name) # check dst rank _check_rank_valid(g, dst_rank) opts = types.ReduceOptions() opts.reduceOp = op opts.root_rank = dst_rank opts.root_tensor = 0 g.reduce([tensor], opts) def reduce_multigpu( tensor_list: list, dst_rank: int = 0, dst_tensor: int = 0, group_name: str = "default", op=types.ReduceOp.SUM, ): """Reduce the tensor across the group to the destination rank and destination tensor. Args: tensor_list: the list of tensors to be reduced on this process; each tensor located on a GPU. dst_rank: the rank of the destination process. dst_tensor: the index of GPU at the destination. group_name: the collective group name to perform reduce. op: The reduce operation. Returns: None """ if not types.cupy_available(): raise RuntimeError("Multigpu calls requires NCCL and Cupy.") _check_tensor_list_input(tensor_list) g = get_group_handle(group_name) # check dst rank _check_rank_valid(g, dst_rank) _check_root_tensor_valid(len(tensor_list), dst_tensor) opts = types.ReduceOptions() opts.reduceOp = op opts.root_rank = dst_rank opts.root_tensor = dst_tensor g.reduce(tensor_list, opts) def broadcast(tensor, src_rank: int = 0, group_name: str = "default"): """Broadcast the tensor from a source process to all others. Args: tensor: the tensor to be broadcasted (src) or received (destination). src_rank: the rank of the source process. group_name: the collective group name to perform broadcast. Returns: None """ _check_single_tensor_input(tensor) g = get_group_handle(group_name) # check src rank _check_rank_valid(g, src_rank) opts = types.BroadcastOptions() opts.root_rank = src_rank opts.root_tensor = 0 g.broadcast([tensor], opts) def broadcast_multigpu( tensor_list, src_rank: int = 0, src_tensor: int = 0, group_name: str = "default" ): """Broadcast the tensor from a source GPU to all other GPUs. Args: tensor_list: the tensors to broadcast (src) or receive (dst). src_rank: the rank of the source process. src_tensor: the index of the source GPU on the source process. group_name: the collective group name to perform broadcast. Returns: None """ if not types.cupy_available(): raise RuntimeError("Multigpu calls requires NCCL and Cupy.") _check_tensor_list_input(tensor_list) g = get_group_handle(group_name) # check src rank _check_rank_valid(g, src_rank) _check_root_tensor_valid(len(tensor_list), src_tensor) opts = types.BroadcastOptions() opts.root_rank = src_rank opts.root_tensor = src_tensor g.broadcast(tensor_list, opts) def allgather(tensor_list: list, tensor, group_name: str = "default"): """Allgather tensors from each process of the group into a list. Args: tensor_list: the results, stored as a list of tensors. tensor: the tensor (to be gathered) in the current process group_name: the name of the collective group. Returns: None """ _check_single_tensor_input(tensor) _check_tensor_list_input(tensor_list) g = get_group_handle(group_name) if len(tensor_list) != g.world_size: # Typically CLL lib requires len(tensor_list) >= world_size; # Here we make it more strict: len(tensor_list) == world_size. raise RuntimeError( "The length of the tensor list operands to allgather " "must be equal to world_size." ) opts = types.AllGatherOptions() g.allgather([tensor_list], [tensor], opts) def allgather_multigpu( output_tensor_lists: list, input_tensor_list: list, group_name: str = "default" ): """Allgather tensors from each gpus of the group into lists. Args: output_tensor_lists (List[List[tensor]]): gathered results, with shape must be num_gpus * world_size * shape(tensor). input_tensor_list: (List[tensor]): a list of tensors, with shape num_gpus * shape(tensor). group_name: the name of the collective group. Returns: None """ if not types.cupy_available(): raise RuntimeError("Multigpu calls requires NCCL and Cupy.") _check_tensor_lists_input(output_tensor_lists) _check_tensor_list_input(input_tensor_list) g = get_group_handle(group_name) opts = types.AllGatherOptions() g.allgather(output_tensor_lists, input_tensor_list, opts) def reducescatter( tensor, tensor_list: list, group_name: str = "default", op=types.ReduceOp.SUM ): """Reducescatter a list of tensors across the group. Reduce the list of the tensors across each process in the group, then scatter the reduced list of tensors -- one tensor for each process. Args: tensor: the resulted tensor on this process. tensor_list: The list of tensors to be reduced and scattered. group_name: the name of the collective group. op: The reduce operation. Returns: None """ _check_single_tensor_input(tensor) _check_tensor_list_input(tensor_list) g = get_group_handle(group_name) opts = types.ReduceScatterOptions() opts.reduceOp = op if len(tensor_list) != g.world_size: raise RuntimeError( "The length of the tensor list operands to reducescatter " "must not be equal to world_size." ) g.reducescatter([tensor], [tensor_list], opts) def reducescatter_multigpu( output_tensor_list, input_tensor_lists, group_name: str = "default", op=types.ReduceOp.SUM, ): """Reducescatter a list of tensors across all GPUs. Args: output_tensor_list: the resulted list of tensors, with shape: num_gpus * shape(tensor). input_tensor_lists: the original tensors, with shape: num_gpus * world_size * shape(tensor). group_name: the name of the collective group. op: The reduce operation. Returns: None. """ if not types.cupy_available(): raise RuntimeError("Multigpu calls requires NCCL and Cupy.") _check_tensor_lists_input(input_tensor_lists) _check_tensor_list_input(output_tensor_list) g = get_group_handle(group_name) opts = types.ReduceScatterOptions() opts.reduceOp = op g.reducescatter(output_tensor_list, input_tensor_lists, opts) def send(tensor, dst_rank: int, group_name: str = "default"): """Send a tensor to a remote process synchronously. Args: tensor: the tensor to send. dst_rank: the rank of the destination process. group_name: the name of the collective group. Returns: None """ _check_single_tensor_input(tensor) g = get_group_handle(group_name) _check_rank_valid(g, dst_rank) if dst_rank == g.rank: raise RuntimeError("The destination rank '{}' is self.".format(dst_rank)) opts = types.SendOptions() opts.dst_rank = dst_rank g.send([tensor], opts) def send_multigpu( tensor, dst_rank: int, dst_gpu_index: int, group_name: str = "default", n_elements: int = 0, ): """Send a tensor to a remote GPU synchronously. The function assumes each process owns >1 GPUs, and the sender process and receiver process has equal number of GPUs. Args: tensor: the tensor to send, located on a GPU. dst_rank: the rank of the destination process. dst_gpu_index: the destination gpu index. group_name: the name of the collective group. n_elements: if specified, send the next n elements from the starting address of tensor. Returns: None """ if not types.cupy_available(): raise RuntimeError("send_multigpu call requires NCCL.") _check_single_tensor_input(tensor) g = get_group_handle(group_name) _check_rank_valid(g, dst_rank) if dst_rank == g.rank: raise RuntimeError( "The dst_rank '{}' is self. Considering " "doing GPU to GPU memcpy instead?".format(dst_rank) ) if n_elements < 0: raise RuntimeError("The n_elements '{}' should >= 0.".format(n_elements)) opts = types.SendOptions() opts.dst_rank = dst_rank opts.dst_gpu_index = dst_gpu_index opts.n_elements = n_elements g.send([tensor], opts) def recv(tensor, src_rank: int, group_name: str = "default"): """Receive a tensor from a remote process synchronously. Args: tensor: the received tensor. src_rank: the rank of the source process. group_name: the name of the collective group. Returns: None """ _check_single_tensor_input(tensor) g = get_group_handle(group_name) _check_rank_valid(g, src_rank) if src_rank == g.rank: raise RuntimeError("The destination rank '{}' is self.".format(src_rank)) opts = types.RecvOptions() opts.src_rank = src_rank g.recv([tensor], opts) def recv_multigpu( tensor, src_rank: int, src_gpu_index: int, group_name: str = "default", n_elements: int = 0, ): """Receive a tensor from a remote GPU synchronously. The function asssume each process owns >1 GPUs, and the sender process and receiver process has equal nubmer of GPUs. Args: tensor: The received tensor, located on a GPU. src_rank: The rank of the source process. src_gpu_index: The index of the source GPU on the src process. group_name: The name of the collective group. Returns: None """ if not types.cupy_available(): raise RuntimeError("recv_multigpu call requires NCCL.") _check_single_tensor_input(tensor) g = get_group_handle(group_name) _check_rank_valid(g, src_rank) if src_rank == g.rank: raise RuntimeError( "The dst_rank '{}' is self. Considering " "doing GPU to GPU memcpy instead?".format(src_rank) ) if n_elements < 0: raise RuntimeError("The n_elements '{}' should be >= 0.".format(n_elements)) opts = types.RecvOptions() opts.src_rank = src_rank opts.src_gpu_index = src_gpu_index opts.n_elements = n_elements g.recv([tensor], opts) def synchronize(gpu_id: int): """Synchronize the current process to a give device. Args: gpu_id: the GPU device id to synchronize. Returns: None """ if not types.cupy_available(): raise RuntimeError("synchronize call requires CUDA and NCCL.") import cupy as cp cp.cuda.Device(gpu_id).synchronize() def get_group_handle(group_name: str = "default"): """Check if the group is initialized and return the group handle. Args: group_name: the name of the collective group. Returns: The collective group handle. """ if group_name != types.NIXL_GROUP_NAME: _check_inside_actor() global _group_mgr global _group_mgr_lock with _group_mgr_lock: if not _group_mgr.is_group_exist(group_name): # try loading from remote info store try: if group_name == types.NIXL_GROUP_NAME: _group_mgr.create_collective_group( types.Backend.NIXL, None, None, group_name, None ) else: # if the information is stored in an Info object, # get and create the group. name = "info_" + group_name mgr = ray.get_actor(name=name) ids, world_size, rank, backend, gloo_timeout = ray.get( mgr.get_info.remote() ) worker = ray._private.worker.global_worker id_ = worker.core_worker.get_actor_id() r = rank[ids.index(id_)] _group_mgr.create_collective_group( backend, world_size, r, group_name, gloo_timeout ) except ValueError as exc: # check if this group is initialized using options() if ( "collective_group_name" in os.environ and os.environ["collective_group_name"] == group_name ): rank = int(os.environ["collective_rank"]) world_size = int(os.environ["collective_world_size"]) backend = os.environ["collective_backend"] gloo_timeout = os.getenv("collective_gloo_timeout", 30000) _group_mgr.create_collective_group( backend, world_size, rank, group_name, gloo_timeout ) else: raise RuntimeError( "The collective group '{}' is not " "initialized in the process.".format(group_name) ) from exc g = _group_mgr.get_group_by_name(group_name) return g def _check_single_tensor_input(tensor): """Check if the tensor is with a supported type.""" if isinstance(tensor, np.ndarray): return if types.cupy_available(): if isinstance(tensor, types.cp.ndarray): return if types.torch_available(): if isinstance(tensor, types.th.Tensor): return raise RuntimeError( "Unrecognized tensor type '{}'. Supported types are: " "np.ndarray, torch.Tensor, cupy.ndarray.".format(type(tensor)) ) def _check_backend_availability(backend: types.Backend): """Check whether the backend is available.""" if backend == types.Backend.GLOO: # Now we have deprecated pygloo, and use torch_gloo in all cases. if not torch_distributed_available(): raise RuntimeError("torch.distributed is not available.") elif backend == types.Backend.NCCL: if not nccl_available(): raise RuntimeError("NCCL is not available.") elif backend == types.Backend.TORCH_GLOO: if not torch_distributed_available(): raise RuntimeError("torch.distributed is not available.") elif backend == types.Backend.NIXL: if not nixl_available(): raise RuntimeError("NIXL is not available.") def _check_inside_actor(): """Check if currently it is inside a Ray actor/task.""" worker = ray._private.worker.global_worker if worker.mode == ray.WORKER_MODE: return else: raise RuntimeError( "The collective APIs shall be only used inside a Ray actor or task." ) def _check_rank_valid(g, rank: int): """Check the rank: 0 <= rank < world_size.""" if rank < 0: raise ValueError("rank '{}' is negative.".format(rank)) if rank >= g.world_size: raise ValueError( "rank '{}' must be less than world size '{}'".format(rank, g.world_size) ) def _check_tensor_list_input(tensor_list): """Check if the input is a list of supported tensor types.""" if not isinstance(tensor_list, list): raise RuntimeError( "The input must be a list of tensors. " "Got '{}'.".format(type(tensor_list)) ) if not tensor_list: raise RuntimeError("Got an empty list of tensors.") for t in tensor_list: _check_single_tensor_input(t) def _check_tensor_lists_input(tensor_lists): """Check if the input is a list of lists of supported tensor types.""" if not isinstance(tensor_lists, list): raise RuntimeError( "The input must be a list of lists of tensors. " "Got '{}'.".format(type(tensor_lists)) ) if not tensor_lists: raise RuntimeError(f"Did not receive tensors. Got: {tensor_lists}") for t in tensor_lists: _check_tensor_list_input(t) def _check_root_tensor_valid(length, root_tensor): """Check the root_tensor device is 0 <= root_tensor < length""" if root_tensor < 0: raise ValueError("root_tensor '{}' is negative.".format(root_tensor)) if root_tensor >= length: raise ValueError( "root_tensor '{}' is greater than the number of GPUs: " "'{}'".format(root_tensor, length) )
GroupManager
python
tensorflow__tensorflow
tensorflow/python/debug/lib/debug_graphs_test.py
{ "start": 1880, "end": 2827 }
class ____(test_util.TensorFlowTestCase): def testIsCopyNode(self): self.assertTrue(debug_graphs.is_copy_node("__copy_ns1/ns2/node3_0")) self.assertFalse(debug_graphs.is_copy_node("copy_ns1/ns2/node3_0")) self.assertFalse(debug_graphs.is_copy_node("_copy_ns1/ns2/node3_0")) self.assertFalse(debug_graphs.is_copy_node("_copyns1/ns2/node3_0")) self.assertFalse(debug_graphs.is_copy_node("__dbg_ns1/ns2/node3_0")) def testIsDebugNode(self): self.assertTrue( debug_graphs.is_debug_node("__dbg_ns1/ns2/node3:0_0_DebugIdentity")) self.assertFalse( debug_graphs.is_debug_node("dbg_ns1/ns2/node3:0_0_DebugIdentity")) self.assertFalse( debug_graphs.is_debug_node("_dbg_ns1/ns2/node3:0_0_DebugIdentity")) self.assertFalse( debug_graphs.is_debug_node("_dbgns1/ns2/node3:0_0_DebugIdentity")) self.assertFalse(debug_graphs.is_debug_node("__copy_ns1/ns2/node3_0"))
NodeNameChecksTest
python
pandas-dev__pandas
pandas/tests/libs/test_lib.py
{ "start": 217, "end": 2433 }
class ____: def test_max_len_string_array(self): arr = a = np.array(["foo", "b", np.nan], dtype="object") assert libwriters.max_len_string_array(arr) == 3 # unicode arr = a.astype("U").astype(object) assert libwriters.max_len_string_array(arr) == 3 # bytes for python3 arr = a.astype("S").astype(object) assert libwriters.max_len_string_array(arr) == 3 # raises msg = "No matching signature found" with pytest.raises(TypeError, match=msg): libwriters.max_len_string_array(arr.astype("U")) def test_fast_unique_multiple_list_gen_sort(self): keys = [["p", "a"], ["n", "d"], ["a", "s"]] gen = (key for key in keys) expected = np.array(["a", "d", "n", "p", "s"]) out = lib.fast_unique_multiple_list_gen(gen, sort=True) tm.assert_numpy_array_equal(np.array(out), expected) gen = (key for key in keys) expected = np.array(["p", "a", "n", "d", "s"]) out = lib.fast_unique_multiple_list_gen(gen, sort=False) tm.assert_numpy_array_equal(np.array(out), expected) def test_fast_multiget_timedelta_resos(self): # This will become relevant for test_constructor_dict_timedelta64_index # once Timedelta constructor preserves reso when passed a # np.timedelta64 object td = Timedelta(days=1) mapping1 = {td: 1} mapping2 = {td.as_unit("s"): 1} oindex = Index([td * n for n in range(3)])._values.astype(object) expected = lib.fast_multiget(mapping1, oindex) result = lib.fast_multiget(mapping2, oindex) tm.assert_numpy_array_equal(result, expected) # case that can't be cast to td64ns td = Timedelta(np.timedelta64(146000, "D")) assert hash(td) == hash(td.as_unit("ms")) assert hash(td) == hash(td.as_unit("us")) mapping1 = {td: 1} mapping2 = {td.as_unit("ms"): 1} oindex = Index([td * n for n in range(3)])._values.astype(object) expected = lib.fast_multiget(mapping1, oindex) result = lib.fast_multiget(mapping2, oindex) tm.assert_numpy_array_equal(result, expected)
TestMisc
python
doocs__leetcode
solution/1200-1299/1236.Web Crawler/Solution.py
{ "start": 254, "end": 720 }
class ____: def crawl(self, startUrl: str, htmlParser: 'HtmlParser') -> List[str]: def host(url): url = url[7:] return url.split('/')[0] def dfs(url): if url in ans: return ans.add(url) for next in htmlParser.getUrls(url): if host(url) == host(next): dfs(next) ans = set() dfs(startUrl) return list(ans)
Solution
python
pydantic__pydantic
pydantic-core/python/pydantic_core/core_schema.py
{ "start": 98801, "end": 100762 }
class ____(TypedDict, total=False): type: Required[Literal['lax-or-strict']] lax_schema: Required[CoreSchema] strict_schema: Required[CoreSchema] strict: bool ref: str metadata: dict[str, Any] serialization: SerSchema def lax_or_strict_schema( lax_schema: CoreSchema, strict_schema: CoreSchema, *, strict: bool | None = None, ref: str | None = None, metadata: dict[str, Any] | None = None, serialization: SerSchema | None = None, ) -> LaxOrStrictSchema: """ Returns a schema that uses the lax or strict schema, e.g.: ```py from pydantic_core import SchemaValidator, core_schema def fn(v: str, info: core_schema.ValidationInfo) -> str: assert 'hello' in v return v + ' world' lax_schema = core_schema.int_schema(strict=False) strict_schema = core_schema.int_schema(strict=True) schema = core_schema.lax_or_strict_schema( lax_schema=lax_schema, strict_schema=strict_schema, strict=True ) v = SchemaValidator(schema) assert v.validate_python(123) == 123 schema = core_schema.lax_or_strict_schema( lax_schema=lax_schema, strict_schema=strict_schema, strict=False ) v = SchemaValidator(schema) assert v.validate_python('123') == 123 ``` Args: lax_schema: The lax schema to use strict_schema: The strict schema to use strict: Whether the strict schema should be used ref: optional unique identifier of the schema, used to reference the schema in other places metadata: Any other information you want to include with the schema, not used by pydantic-core serialization: Custom serialization schema """ return _dict_not_none( type='lax-or-strict', lax_schema=lax_schema, strict_schema=strict_schema, strict=strict, ref=ref, metadata=metadata, serialization=serialization, )
LaxOrStrictSchema
python
fsspec__filesystem_spec
fsspec/implementations/gist.py
{ "start": 130, "end": 8528 }
class ____(AbstractFileSystem): """ Interface to files in a single GitHub Gist. Provides read-only access to a gist's files. Gists do not contain subdirectories, so file listing is straightforward. Parameters ---------- gist_id: str The ID of the gist you want to access (the long hex value from the URL). filenames: list[str] (optional) If provided, only make a file system representing these files, and do not fetch the list of all files for this gist. sha: str (optional) If provided, fetch a particular revision of the gist. If omitted, the latest revision is used. username: str (optional) GitHub username for authentication. token: str (optional) GitHub personal access token (required if username is given), or. timeout: (float, float) or float, optional Connect and read timeouts for requests (default 60s each). kwargs: dict Stored on `self.request_kw` and passed to `requests.get` when fetching Gist metadata or reading ("opening") a file. """ protocol = "gist" gist_url = "https://api.github.com/gists/{gist_id}" gist_rev_url = "https://api.github.com/gists/{gist_id}/{sha}" def __init__( self, gist_id, filenames=None, sha=None, username=None, token=None, timeout=None, **kwargs, ): super().__init__() self.gist_id = gist_id self.filenames = filenames self.sha = sha # revision of the gist (optional) if username is not None and token is None: raise ValueError("User auth requires a token") self.username = username self.token = token self.request_kw = kwargs # Default timeouts to 60s connect/read if none provided self.timeout = timeout if timeout is not None else (60, 60) # We use a single-level "directory" cache, because a gist is essentially flat self.dircache[""] = self._fetch_file_list() @property def kw(self): """Auth parameters passed to 'requests' if we have username/token.""" kw = { "headers": { "Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", } } kw.update(self.request_kw) if self.username and self.token: kw["auth"] = (self.username, self.token) elif self.token: kw["headers"]["Authorization"] = f"Bearer {self.token}" return kw def _fetch_gist_metadata(self): """ Fetch the JSON metadata for this gist (possibly for a specific revision). """ if self.sha: url = self.gist_rev_url.format(gist_id=self.gist_id, sha=self.sha) else: url = self.gist_url.format(gist_id=self.gist_id) r = requests.get(url, timeout=self.timeout, **self.kw) if r.status_code == 404: raise FileNotFoundError( f"Gist not found: {self.gist_id}@{self.sha or 'latest'}" ) r.raise_for_status() return r.json() def _fetch_file_list(self): """ Returns a list of dicts describing each file in the gist. These get stored in self.dircache[""]. """ meta = self._fetch_gist_metadata() if self.filenames: available_files = meta.get("files", {}) files = {} for fn in self.filenames: if fn not in available_files: raise FileNotFoundError(fn) files[fn] = available_files[fn] else: files = meta.get("files", {}) out = [] for fname, finfo in files.items(): if finfo is None: # Occasionally GitHub returns a file entry with null if it was deleted continue # Build a directory entry out.append( { "name": fname, # file's name "type": "file", # gists have no subdirectories "size": finfo.get("size", 0), # file size in bytes "raw_url": finfo.get("raw_url"), } ) return out @classmethod def _strip_protocol(cls, path): """ Remove 'gist://' from the path, if present. """ # The default infer_storage_options can handle gist://username:token@id/file # or gist://id/file, but let's ensure we handle a normal usage too. # We'll just strip the protocol prefix if it exists. path = infer_storage_options(path).get("path", path) return path.lstrip("/") @staticmethod def _get_kwargs_from_urls(path): """ Parse 'gist://' style URLs into GistFileSystem constructor kwargs. For example: gist://:TOKEN@<gist_id>/file.txt gist://username:TOKEN@<gist_id>/file.txt """ so = infer_storage_options(path) out = {} if "username" in so and so["username"]: out["username"] = so["username"] if "password" in so and so["password"]: out["token"] = so["password"] if "host" in so and so["host"]: # We interpret 'host' as the gist ID out["gist_id"] = so["host"] # Extract SHA and filename from path if "path" in so and so["path"]: path_parts = so["path"].rsplit("/", 2)[-2:] if len(path_parts) == 2: if path_parts[0]: # SHA present out["sha"] = path_parts[0] if path_parts[1]: # filename also present out["filenames"] = [path_parts[1]] return out def ls(self, path="", detail=False, **kwargs): """ List files in the gist. Gists are single-level, so any 'path' is basically the filename, or empty for all files. Parameters ---------- path : str, optional The filename to list. If empty, returns all files in the gist. detail : bool, default False If True, return a list of dicts; if False, return a list of filenames. """ path = self._strip_protocol(path or "") # If path is empty, return all if path == "": results = self.dircache[""] else: # We want just the single file with this name all_files = self.dircache[""] results = [f for f in all_files if f["name"] == path] if not results: raise FileNotFoundError(path) if detail: return results else: return sorted(f["name"] for f in results) def _open(self, path, mode="rb", block_size=None, **kwargs): """ Read a single file from the gist. """ if mode != "rb": raise NotImplementedError("GitHub Gist FS is read-only (no write).") path = self._strip_protocol(path) # Find the file entry in our dircache matches = [f for f in self.dircache[""] if f["name"] == path] if not matches: raise FileNotFoundError(path) finfo = matches[0] raw_url = finfo.get("raw_url") if not raw_url: raise FileNotFoundError(f"No raw_url for file: {path}") r = requests.get(raw_url, timeout=self.timeout, **self.kw) if r.status_code == 404: raise FileNotFoundError(path) r.raise_for_status() return MemoryFile(path, None, r.content) def cat(self, path, recursive=False, on_error="raise", **kwargs): """ Return {path: contents} for the given file or files. If 'recursive' is True, and path is empty, returns all files in the gist. """ paths = self.expand_path(path, recursive=recursive) out = {} for p in paths: try: with self.open(p, "rb") as f: out[p] = f.read() except FileNotFoundError as e: if on_error == "raise": raise e elif on_error == "omit": pass # skip else: out[p] = e if len(paths) == 1 and paths[0] == path: return out[path] return out
GistFileSystem
python
python-attrs__attrs
typing-examples/baseline.py
{ "start": 731, "end": 857 }
class ____(Exception): x: int try: raise Error(1) except Error as e: e.x e.args str(e) @attrs.define
Error
python
ray-project__ray
rllib/algorithms/dreamerv3/torch/models/critic_network.py
{ "start": 485, "end": 7376 }
class ____(nn.Module): """The critic network described in [1], predicting values for policy learning. Contains a copy of itself (EMA net) for weight regularization. The EMA net is updated after each train step via EMA (using the `ema_decay` parameter and the actual critic's weights). The EMA net is NOT used for target computations (we use the actual critic for that), its only purpose is to compute a weights regularizer term for the critic's loss such that the actual critic does not move too quickly. """ def __init__( self, *, input_size: int, model_size: str = "XS", num_buckets: int = 255, lower_bound: float = -20.0, upper_bound: float = 20.0, ema_decay: float = 0.98, ): """Initializes a CriticNetwork instance. Args: input_size: The input size of the critic network. model_size: The "Model Size" used according to [1] Appendinx B. Use None for manually setting the different network sizes. num_buckets: The number of buckets to create. Note that the number of possible symlog'd outcomes from the used distribution is `num_buckets` + 1: lower_bound --bucket-- o[1] --bucket-- o[2] ... --bucket-- upper_bound o=outcomes lower_bound=o[0] upper_bound=o[num_buckets] lower_bound: The symlog'd lower bound for a possible reward value. Note that a value of -20.0 here already allows individual (actual env) rewards to be as low as -400M. Buckets will be created between `lower_bound` and `upper_bound`. upper_bound: The symlog'd upper bound for a possible reward value. Note that a value of +20.0 here already allows individual (actual env) rewards to be as high as 400M. Buckets will be created between `lower_bound` and `upper_bound`. ema_decay: The weight to use for updating the weights of the critic's copy vs the actual critic. After each training update, the EMA copy of the critic gets updated according to: ema_net=(`ema_decay`*ema_net) + (1.0-`ema_decay`)*critic_net The EMA copy of the critic is used inside the critic loss function only to produce a regularizer term against the current critic's weights, NOT to compute any target values. """ super().__init__() self.input_size = input_size self.model_size = model_size self.ema_decay = ema_decay # "Fast" critic network(s) (mlp + reward-pred-layer). This is the network # we actually train with our critic loss. # IMPORTANT: We also use this to compute the return-targets, BUT we regularize # the critic loss term such that the weights of this fast critic stay close # to the EMA weights (see below). self.mlp = MLP( input_size=self.input_size, model_size=self.model_size, output_layer_size=None, ) reward_predictor_input_size = get_dense_hidden_units(self.model_size) self.return_layer = reward_predictor_layer.RewardPredictorLayer( input_size=reward_predictor_input_size, num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper_bound, ) # Weights-EMA (EWMA) containing networks for critic loss (similar to a # target net, BUT not used to compute anything, just for the # weights regularizer term inside the critic loss). self.mlp_ema = MLP( input_size=self.input_size, model_size=self.model_size, output_layer_size=None, ) self.return_layer_ema = reward_predictor_layer.RewardPredictorLayer( input_size=reward_predictor_input_size, num_buckets=num_buckets, lower_bound=lower_bound, upper_bound=upper_bound, ) def forward(self, h, z, return_logits=False, use_ema=False): """Performs a forward pass through the critic network. 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]. return_logits: Whether also return (as a second tuple item) the logits computed by the binned return layer (instead of only the value itself). use_ema: Whether to use the EMA-copy of the critic instead of the actual critic to perform this computation. """ # 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) if not use_ema: # Send h-cat-z through MLP. out = self.mlp(out) # Return expected return OR (expected return, probs of bucket values). return self.return_layer(out, return_logits=return_logits) else: out = self.mlp_ema(out) return self.return_layer_ema(out, return_logits=return_logits) def init_ema(self) -> None: """Initializes the EMA-copy of the critic from the critic's weights. After calling this method, the two networks have identical weights and the EMA net will be non-trainable. """ for param_ema, param in zip(self.mlp_ema.parameters(), self.mlp.parameters()): param_ema.data.copy_(param.data) # Make all EMA parameters non-trainable. param_ema.requires_grad = False assert param_ema.grad is None for param_ema, param in zip( self.return_layer_ema.parameters(), self.return_layer.parameters() ): param_ema.data.copy_(param.data) # Make all EMA parameters non-trainable. param_ema.requires_grad = False assert param_ema.grad is None def update_ema(self) -> None: """Updates the EMA-copy of the critic according to the update formula: ema_net=(`ema_decay`*ema_net) + (1.0-`ema_decay`)*critic_net """ for param_ema, param in zip(self.mlp_ema.parameters(), self.mlp.parameters()): param_ema.data.mul_(self.ema_decay).add_( (1.0 - self.ema_decay) * param.data ) for param_ema, param in zip( self.return_layer_ema.parameters(), self.return_layer.parameters() ): param_ema.data.mul_(self.ema_decay).add_( (1.0 - self.ema_decay) * param.data )
CriticNetwork
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 277, "end": 762 }
class ____(object): """* jina gRPC service for DataRequests. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.process_data = channel.unary_unary( '/jina.JinaDataRequestRPC/process_data', request_serializer=jina__pb2.DataRequestListProto.SerializeToString, response_deserializer=jina__pb2.DataRequestProto.FromString, )
JinaDataRequestRPCStub
python
keras-team__keras
keras/src/utils/torch_utils.py
{ "start": 371, "end": 6619 }
class ____(Layer): """Torch module wrapper layer. `TorchModuleWrapper` is a wrapper class that can turn any `torch.nn.Module` into a Keras layer, in particular by making its parameters trackable by Keras. `TorchModuleWrapper` is only compatible with the PyTorch backend and cannot be used with the TensorFlow or JAX backends. Args: module: `torch.nn.Module` instance. If it's a `LazyModule` instance, then its parameters must be initialized before passing the instance to `TorchModuleWrapper` (e.g. by calling it once). output_shape :The shape of the output of this layer. It helps Keras perform automatic shape inference. name: The name of the layer (string). Example: Here's an example of how the `TorchModuleWrapper` can be used with vanilla PyTorch modules. ```python import torch import torch.nn as nn import torch.nn.functional as F import keras from keras.layers import TorchModuleWrapper class Classifier(keras.Model): def __init__(self, **kwargs): super().__init__(**kwargs) # Wrap `torch.nn.Module`s with `TorchModuleWrapper` # if they contain parameters self.conv1 = TorchModuleWrapper( nn.Conv2d(in_channels=1, out_channels=32, kernel_size=(3, 3)) ) self.conv2 = TorchModuleWrapper( nn.Conv2d(in_channels=32, out_channels=64, kernel_size=(3, 3)) ) self.pool = nn.MaxPool2d(kernel_size=(2, 2)) self.flatten = nn.Flatten() self.dropout = nn.Dropout(p=0.5) self.fc = TorchModuleWrapper(nn.Linear(1600, 10)) def call(self, inputs): x = F.relu(self.conv1(inputs)) x = self.pool(x) x = F.relu(self.conv2(x)) x = self.pool(x) x = self.flatten(x) x = self.dropout(x) x = self.fc(x) return F.softmax(x, dim=1) model = Classifier() model.build((1, 28, 28)) print("Output shape:", model(torch.ones(1, 1, 28, 28).to("cuda")).shape) model.compile( loss="sparse_categorical_crossentropy", optimizer="adam", metrics=["accuracy"] ) model.fit(train_loader, epochs=5) ``` """ def __init__(self, module, name=None, output_shape=None, **kwargs): super().__init__(name=name, **kwargs) import torch.nn as nn from keras.src.backend.torch.core import get_device if ( isinstance(module, nn.modules.lazy.LazyModuleMixin) and module.has_uninitialized_params() ): raise ValueError( "LazyModules are not supported unless they " "are already initialized. " f"Received uninitialized LazyModule: module={module}" ) self.module = module.to(get_device()) self._track_module_parameters() self.output_shape = output_shape def parameters(self, recurse=True): return self.module.parameters(recurse=recurse) def _track_module_parameters(self): for param in self.module.parameters(): # The Variable will reuse the raw `param` # and simply wrap it. variable = backend.Variable( initializer=param, trainable=param.requires_grad ) self._track_variable(variable) self.built = True def call(self, *args, training=None, **kwargs): if training is False: self.eval() else: self.train() return self.module(*args, **kwargs) def save_own_variables(self, store): """Saves model's state from `state_dict`. `model.parameters` excludes some of model's state like `BatchNorm` mean and variance. So, use `state_dict` to obtain all of model's state. """ state_dict = self.module.state_dict() for key in state_dict.keys(): store[key] = convert_to_numpy(state_dict[key]) def load_own_variables(self, store): """Loads model's state via `state_dict`.""" state_dict = {} for key in store.keys(): if isinstance(key, bytes): key = key.decode() state_dict[key] = convert_to_tensor(store[key]) self.module.load_state_dict(state_dict) def compute_output_shape(self, input_shape): if self.output_shape is None: return super().compute_output_shape(input_shape) return self.output_shape def get_config(self): base_config = super().get_config() import torch buffer = io.BytesIO() torch.save(self.module, buffer) # Encode the buffer using base64 to ensure safe serialization buffer_b64 = base64.b64encode(buffer.getvalue()).decode("ascii") config = { "module": buffer_b64, "output_shape": self.output_shape, } return {**base_config, **config} @classmethod def from_config(cls, config): import torch if "module" in config: if in_safe_mode(): raise ValueError( "Requested the deserialization of a `torch.nn.Module` " "object via `torch.load()`. This carries a potential risk " "of arbitrary code execution and thus it is disallowed by " "default. If you trust the source of the artifact, you can " "override this error by passing `safe_mode=False` to the " "loading function, or calling " "`keras.config.enable_unsafe_deserialization()." ) # Decode the base64 string back to bytes buffer_bytes = base64.b64decode(config["module"].encode("ascii")) buffer = io.BytesIO(buffer_bytes) config["module"] = torch.load(buffer, weights_only=False) return cls(**config) def no_grad(orig_func): import torch if parse(torch.__version__) >= parse("2.1.0"): return torch.no_grad(orig_func) else: return orig_func
TorchModuleWrapper
python
pdm-project__pdm
src/pdm/models/finder.py
{ "start": 919, "end": 2086 }
class ____(Evaluator): def __init__(self, *args: Any, env_spec: EnvSpec, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.env_spec = env_spec def check_requires_python(self, link: unearth.Link) -> None: if link.requires_python: try: requires_python = parse_version_specifier(link.requires_python) except InvalidSpecifier as e: logger.debug( "Invalid requires-python specifier for link(%s) %s: %s", link.redacted, link.requires_python, e ) return if (requires_python & self.env_spec.requires_python).is_empty(): raise LinkMismatchError( f"The package requires-python {link.requires_python} is not compatible with the target {self.env_spec.requires_python}." ) def check_wheel_tags(self, filename: str) -> None: if self.env_spec.wheel_compatibility(filename) is None: raise LinkMismatchError( f"The wheel file {filename} is not compatible with the target environment {self.env_spec}." )
PDMEvaluator
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/images/api/blobstore.py
{ "start": 1633, "end": 2389 }
class ____(webapp2.RequestHandler): def get(self): blob_key = self.request.get("blob_key") if blob_key: blob_info = blobstore.get(blob_key) if blob_info: # [START gae_get_serving_url] url = images.get_serving_url( blob_key, size=150, crop=True, secure_url=True ) # [END gae_get_serving_url] return webapp2.redirect(url) # Either "blob_key" wasn't provided, or there was no value with that ID # in the Blobstore. self.error(404) app = webapp2.WSGIApplication( [("/img", Thumbnailer), ("/redirect", ServingUrlRedirect)], debug=True ) # [END gae_images_api_blobstore]
ServingUrlRedirect
python
kubernetes-client__python
kubernetes/client/models/v1_custom_resource_subresources.py
{ "start": 383, "end": 4885 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'scale': 'V1CustomResourceSubresourceScale', 'status': 'object' } attribute_map = { 'scale': 'scale', 'status': 'status' } def __init__(self, scale=None, status=None, local_vars_configuration=None): # noqa: E501 """V1CustomResourceSubresources - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._scale = None self._status = None self.discriminator = None if scale is not None: self.scale = scale if status is not None: self.status = status @property def scale(self): """Gets the scale of this V1CustomResourceSubresources. # noqa: E501 :return: The scale of this V1CustomResourceSubresources. # noqa: E501 :rtype: V1CustomResourceSubresourceScale """ return self._scale @scale.setter def scale(self, scale): """Sets the scale of this V1CustomResourceSubresources. :param scale: The scale of this V1CustomResourceSubresources. # noqa: E501 :type: V1CustomResourceSubresourceScale """ self._scale = scale @property def status(self): """Gets the status of this V1CustomResourceSubresources. # noqa: E501 status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. # noqa: E501 :return: The status of this V1CustomResourceSubresources. # noqa: E501 :rtype: object """ return self._status @status.setter def status(self, status): """Sets the status of this V1CustomResourceSubresources. status indicates the custom resource should serve a `/status` subresource. When enabled: 1. requests to the custom resource primary endpoint ignore changes to the `status` stanza of the object. 2. requests to the custom resource `/status` subresource ignore changes to anything other than the `status` stanza of the object. # noqa: E501 :param status: The status of this V1CustomResourceSubresources. # noqa: E501 :type: object """ self._status = status def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1CustomResourceSubresources): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1CustomResourceSubresources): return True return self.to_dict() != other.to_dict()
V1CustomResourceSubresources
python
joke2k__faker
faker/providers/ssn/et_EE/__init__.py
{ "start": 948, "end": 2665 }
class ____(SsnProvider): scale1 = (1, 2, 3, 4, 5, 6, 7, 8, 9, 1) scale2 = (3, 4, 5, 6, 7, 8, 9, 1, 2, 3) def ssn(self, min_age: int = 16, max_age: int = 90) -> str: """ Returns 11 character Estonian personal identity code (isikukood, IK). Age of person is between 16 and 90 years, based on local computer date. This function assigns random sex to person. An Estonian Personal identification code consists of 11 digits, generally given without any whitespace or other delimiters. The form is GYYMMDDSSSC, where G shows sex and century of birth (odd number male, even number female, 1-2 19th century, 3-4 20th century, 5-6 21st century), SSS is a serial number separating persons born on the same date and C a checksum. https://en.wikipedia.org/wiki/National_identification_number#Estonia """ age = datetime.timedelta(days=self.generator.random.randrange(min_age * 365, max_age * 365)) birthday = datetime.date.today() - age if birthday.year < 2000: ik = self.generator.random.choice(("3", "4")) elif birthday.year < 2100: ik = self.generator.random.choice(("5", "6")) else: ik = self.generator.random.choice(("7", "8")) ik += f"{birthday:%y%m%d}{self.generator.random.randrange(999):03}" return ik + str(checksum([int(ch) for ch in ik])) vat_id_formats = ("EE#########",) def vat_id(self) -> str: """ http://ec.europa.eu/taxation_customs/vies/faq.html#item_11 :return: A random Estonian VAT ID """ return self.bothify(self.random_element(self.vat_id_formats))
Provider
python
Pylons__pyramid
src/pyramid/interfaces.py
{ "start": 42153, "end": 43327 }
class ____(Interface): """An object that offers the ability to verify CSRF tokens and generate new ones.""" def new_csrf_token(request): """Create and return a new, random cross-site request forgery protection token. The token will be an ascii-compatible unicode string. """ def get_csrf_token(request): """Return a cross-site request forgery protection token. It will be an ascii-compatible unicode string. If a token was previously set for this user via ``new_csrf_token``, that token will be returned. If no CSRF token was previously set, ``new_csrf_token`` will be called, which will create and set a token, and this token will be returned. """ def check_csrf_token(request, token): """Determine if the supplied ``token`` is valid. Most implementations should simply compare the ``token`` to the current value of ``get_csrf_token`` but it is possible to verify the token using any mechanism necessary using this method. Returns ``True`` if the ``token`` is valid, otherwise ``False``. """
ICSRFStoragePolicy
python
openai__openai-python
src/openai/types/chat/chat_completion_content_part_param.py
{ "start": 566, "end": 910 }
class ____(TypedDict, total=False): file_data: str """ The base64 encoded file data, used when passing the file to the model as a string. """ file_id: str """The ID of an uploaded file to use as input.""" filename: str """The name of the file, used when passing the file to the model as a string."""
FileFile
python
jmcnamara__XlsxWriter
xlsxwriter/test/workbook/test_write_workbook_pr.py
{ "start": 299, "end": 875 }
class ____(unittest.TestCase): """ Test the Workbook _write_workbook_pr() method. """ def setUp(self): self.fh = StringIO() self.workbook = Workbook() self.workbook._set_filehandle(self.fh) def test_write_workbook_pr(self): """Test the _write_workbook_pr() method""" self.workbook._write_workbook_pr() exp = """<workbookPr defaultThemeVersion="124226"/>""" got = self.fh.getvalue() self.assertEqual(exp, got) def tearDown(self): self.workbook.fileclosed = 1
TestWriteWorkbookPr
python
gevent__gevent
src/greentest/3.11/test_httplib.py
{ "start": 60763, "end": 60964 }
class ____(ExtendedReadTest): _header, _body = ExtendedReadTest.lines.split('\r\n\r\n', 1) lines = _header + f'\r\nContent-Length: {len(_body)}\r\n\r\n' + _body
ExtendedReadTestContentLengthKnown
python
allegroai__clearml
clearml/backend_api/services/v2_13/events.py
{ "start": 335, "end": 4834 }
class ____(NonStrictDataModel): """ Used for reporting scalar metrics during training task :param timestamp: Epoch milliseconds UTC, will be set by the server if not set. :type timestamp: float :param task: Task ID (required) :type task: str :param iter: Iteration :type iter: int :param metric: Metric name, e.g. 'count', 'loss', 'accuracy' :type metric: str :param variant: E.g. 'class_1', 'total', 'average :type variant: str :param value: :type value: float """ _schema = { "description": "Used for reporting scalar metrics during training task", "properties": { "iter": {"description": "Iteration", "type": "integer"}, "metric": { "description": "Metric name, e.g. 'count', 'loss', 'accuracy'", "type": "string", }, "task": {"description": "Task ID (required)", "type": "string"}, "timestamp": { "description": "Epoch milliseconds UTC, will be set by the server if not set.", "type": ["number", "null"], }, "type": { "const": "training_stats_scalar", "description": "training_stats_vector", }, "value": {"description": "", "type": "number"}, "variant": { "description": "E.g. 'class_1', 'total', 'average", "type": "string", }, }, "required": ["task", "type"], "type": "object", } def __init__( self, task: str, timestamp: Optional[float] = None, iter: Optional[int] = None, metric: Optional[str] = None, variant: Optional[str] = None, value: Optional[float] = None, **kwargs: Any ) -> None: super(MetricsScalarEvent, self).__init__(**kwargs) self.timestamp = timestamp self.task = task self.iter = iter self.metric = metric self.variant = variant self.value = value @schema_property("timestamp") def timestamp(self) -> Optional[float]: return self._property_timestamp @timestamp.setter def timestamp(self, value: Optional[float]) -> None: if value is None: self._property_timestamp = None return self.assert_isinstance(value, "timestamp", six.integer_types + (float,)) self._property_timestamp = value @schema_property("type") def type(self) -> Any: return "training_stats_scalar" @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("iter") def iter(self) -> Optional[int]: return self._property_iter @iter.setter def iter(self, value: Optional[int]) -> None: if value is None: self._property_iter = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "iter", six.integer_types) self._property_iter = value @schema_property("metric") def metric(self) -> Optional[str]: return self._property_metric @metric.setter def metric(self, value: Optional[str]) -> None: if value is None: self._property_metric = None return self.assert_isinstance(value, "metric", six.string_types) self._property_metric = value @schema_property("variant") def variant(self) -> Optional[str]: return self._property_variant @variant.setter def variant(self, value: Optional[str]) -> None: if value is None: self._property_variant = None return self.assert_isinstance(value, "variant", six.string_types) self._property_variant = value @schema_property("value") def value(self) -> Optional[float]: return self._property_value @value.setter def value(self, value: Optional[float]) -> None: if value is None: self._property_value = None return self.assert_isinstance(value, "value", six.integer_types + (float,)) self._property_value = value
MetricsScalarEvent
python
allegroai__clearml
clearml/backend_api/services/v2_23/datasets.py
{ "start": 245318, "end": 250276 }
class ____(Request): """ Updates an existing dataset object :param dataset: Dataset ID :type dataset: str :param name: Dataset name Unique within the company. :type name: str :param comment: Dataset comment :type comment: str :param tags: User-defined tags list :type tags: Sequence[str] :param system_tags: System tags list. This field is reserved for system use, please don't use it. :type system_tags: Sequence[str] :param terms_of_use: Terms of use string :type terms_of_use: str :param metadata: User-specified metadata object. Keys must not include '$' and '.'. :type metadata: dict """ _service = "datasets" _action = "update" _version = "2.23" _schema = { "definitions": {}, "properties": { "comment": {"description": "Dataset comment", "type": "string"}, "dataset": {"description": "Dataset ID", "type": "string"}, "metadata": { "additionalProperties": True, "description": "User-specified metadata object. Keys must not include '$' and '.'.", "type": "object", }, "name": { "description": "Dataset name Unique within the company.", "type": "string", }, "system_tags": { "description": "System tags list. This field is reserved for system use, please don't use it.", "items": {"type": "string"}, "type": "array", }, "tags": { "description": "User-defined tags list", "items": {"type": "string"}, "type": "array", }, "terms_of_use": {"description": "Terms of use string", "type": "string"}, }, "required": ["dataset"], "type": "object", } def __init__( self, dataset, name=None, comment=None, tags=None, system_tags=None, terms_of_use=None, metadata=None, **kwargs ): super(UpdateRequest, self).__init__(**kwargs) self.dataset = dataset self.name = name self.comment = comment self.tags = tags self.system_tags = system_tags self.terms_of_use = terms_of_use self.metadata = metadata @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("name") def name(self): return self._property_name @name.setter def name(self, value): if value is None: self._property_name = None return self.assert_isinstance(value, "name", six.string_types) self._property_name = value @schema_property("comment") def comment(self): return self._property_comment @comment.setter def comment(self, value): if value is None: self._property_comment = None return self.assert_isinstance(value, "comment", six.string_types) self._property_comment = value @schema_property("tags") def tags(self): return self._property_tags @tags.setter def tags(self, value): if value is None: self._property_tags = None return self.assert_isinstance(value, "tags", (list, tuple)) self.assert_isinstance(value, "tags", six.string_types, is_array=True) self._property_tags = value @schema_property("system_tags") def system_tags(self): return self._property_system_tags @system_tags.setter def system_tags(self, value): if value is None: self._property_system_tags = None return self.assert_isinstance(value, "system_tags", (list, tuple)) self.assert_isinstance(value, "system_tags", six.string_types, is_array=True) self._property_system_tags = value @schema_property("terms_of_use") def terms_of_use(self): return self._property_terms_of_use @terms_of_use.setter def terms_of_use(self, value): if value is None: self._property_terms_of_use = None return self.assert_isinstance(value, "terms_of_use", six.string_types) self._property_terms_of_use = value @schema_property("metadata") def metadata(self): return self._property_metadata @metadata.setter def metadata(self, value): if value is None: self._property_metadata = None return self.assert_isinstance(value, "metadata", (dict,)) self._property_metadata = value
UpdateRequest
python
pydantic__pydantic
tests/test_validate_call.py
{ "start": 37805, "end": 38025 }
class ____[T]: class B: @validate_call(validate_return=True) def f(a: T) -> T: ... class C[S]: @validate_call(validate_return=True) def f(a: T) -> S: ... """ )
A
python
scrapy__scrapy
scrapy/statscollectors.py
{ "start": 368, "end": 2870 }
class ____: def __init__(self, crawler: Crawler): self._dump: bool = crawler.settings.getbool("STATS_DUMP") self._stats: StatsT = {} self._crawler: Crawler = crawler def __getattribute__(self, name): cached_name = f"_cached_{name}" try: return super().__getattribute__(cached_name) except AttributeError: pass original_attr = super().__getattribute__(name) if name in { "get_value", "get_stats", "set_value", "set_stats", "inc_value", "max_value", "min_value", "clear_stats", "open_spider", "close_spider", } and callable(original_attr): wrapped = _warn_spider_arg(original_attr) setattr(self, cached_name, wrapped) return wrapped return original_attr def get_value( self, key: str, default: Any = None, spider: Spider | None = None ) -> Any: return self._stats.get(key, default) def get_stats(self, spider: Spider | None = None) -> StatsT: return self._stats def set_value(self, key: str, value: Any, spider: Spider | None = None) -> None: self._stats[key] = value def set_stats(self, stats: StatsT, spider: Spider | None = None) -> None: self._stats = stats def inc_value( self, key: str, count: int = 1, start: int = 0, spider: Spider | None = None ) -> None: d = self._stats d[key] = d.setdefault(key, start) + count def max_value(self, key: str, value: Any, spider: Spider | None = None) -> None: self._stats[key] = max(self._stats.setdefault(key, value), value) def min_value(self, key: str, value: Any, spider: Spider | None = None) -> None: self._stats[key] = min(self._stats.setdefault(key, value), value) def clear_stats(self, spider: Spider | None = None) -> None: self._stats.clear() def open_spider(self, spider: Spider | None = None) -> None: pass def close_spider( self, spider: Spider | None = None, reason: str | None = None ) -> None: if self._dump: logger.info( "Dumping Scrapy stats:\n" + pprint.pformat(self._stats), extra={"spider": self._crawler.spider}, ) self._persist_stats(self._stats) def _persist_stats(self, stats: StatsT) -> None: pass
StatsCollector
python
pytorch__pytorch
torch/testing/_internal/distributed/_tensor/common_dtensor.py
{ "start": 19086, "end": 19557 }
class ____(MultiThreadedTestCase): @property def world_size(self) -> int: return NUM_DEVICES @property def device_type(self) -> str: return DEVICE_TYPE def build_device_mesh(self): return init_device_mesh(self.device_type, (self.world_size,)) def setUp(self) -> None: super().setUp() self._spawn_threads() # This is a class for converting args/kwargs of an op into distributed args/kwargs
DTensorOpTestBase
python
Pylons__pyramid
tests/test_request.py
{ "start": 13797, "end": 16739 }
class ____(unittest.TestCase): def _callFUT(self, request, app): from pyramid.request import call_app_with_subpath_as_path_info return call_app_with_subpath_as_path_info(request, app) def test_it_all_request_and_environment_data_missing(self): request = DummyRequest({}) response = self._callFUT(request, 'app') self.assertTrue(request.copied) self.assertEqual(response, 'app') self.assertEqual(request.environ['SCRIPT_NAME'], '') self.assertEqual(request.environ['PATH_INFO'], '/') def test_it_with_subpath_and_path_info(self): request = DummyRequest({'PATH_INFO': '/hello'}) request.subpath = ('hello',) response = self._callFUT(request, 'app') self.assertTrue(request.copied) self.assertEqual(response, 'app') self.assertEqual(request.environ['SCRIPT_NAME'], '') self.assertEqual(request.environ['PATH_INFO'], '/hello') def test_it_with_subpath_and_path_info_path_info_endswith_slash(self): request = DummyRequest({'PATH_INFO': '/hello/'}) request.subpath = ('hello',) response = self._callFUT(request, 'app') self.assertTrue(request.copied) self.assertEqual(response, 'app') self.assertEqual(request.environ['SCRIPT_NAME'], '') self.assertEqual(request.environ['PATH_INFO'], '/hello/') def test_it_with_subpath_and_path_info_extra_script_name(self): request = DummyRequest( {'PATH_INFO': '/hello', 'SCRIPT_NAME': '/script'} ) request.subpath = ('hello',) response = self._callFUT(request, 'app') self.assertTrue(request.copied) self.assertEqual(response, 'app') self.assertEqual(request.environ['SCRIPT_NAME'], '/script') self.assertEqual(request.environ['PATH_INFO'], '/hello') def test_it_with_extra_slashes_in_path_info(self): request = DummyRequest( {'PATH_INFO': '//hello/', 'SCRIPT_NAME': '/script'} ) request.subpath = ('hello',) response = self._callFUT(request, 'app') self.assertTrue(request.copied) self.assertEqual(response, 'app') self.assertEqual(request.environ['SCRIPT_NAME'], '/script') self.assertEqual(request.environ['PATH_INFO'], '/hello/') def test_subpath_path_info_and_script_name_have_utf8(self): encoded = text_(b'La Pe\xc3\xb1a') decoded = text_(bytes_(encoded), 'utf-8') request = DummyRequest( {'PATH_INFO': '/' + encoded, 'SCRIPT_NAME': '/' + encoded} ) request.subpath = (decoded,) response = self._callFUT(request, 'app') self.assertTrue(request.copied) self.assertEqual(response, 'app') self.assertEqual(request.environ['SCRIPT_NAME'], '/' + encoded) self.assertEqual(request.environ['PATH_INFO'], '/' + encoded)
Test_call_app_with_subpath_as_path_info
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/assets.py
{ "start": 2626, "end": 2763 }
class ____(BaseModel): """Asset collection response.""" assets: list[AssetResponse] total_entries: int
AssetCollectionResponse
python
getsentry__sentry
tests/sentry/deletions/tasks/test_scheduled.py
{ "start": 7374, "end": 8333 }
class ____(RegionalRunScheduleDeletionTest): @property def ScheduledDeletion(self) -> type[BaseScheduledDeletion]: return RegionScheduledDeletion def run_scheduled_deletions(self) -> None: return run_scheduled_deletions() def reattempt_deletions(self) -> None: return reattempt_deletions() def create_simple_deletion(self) -> QuerySet[Team]: org = self.create_organization(name="test") team = self.create_team(organization=org, name="delete") return Team.objects.filter(id=team.id) def create_does_not_proceed_deletion(self) -> QuerySet[Repository]: org = self.create_organization(name="test") project = self.create_project(organization=org) repo = self.create_repo(project=project, name="example/example") assert repo.status == ObjectStatus.ACTIVE return Repository.objects.filter(id=repo.id) @control_silo_test
RunRegionScheduledDeletionTest
python
scipy__scipy
benchmarks/benchmarks/optimize_lap.py
{ "start": 1500, "end": 1956 }
class ____(Benchmark): shape = (100, 100) param_names = ['threads'] params = [[1, 2, 4]] def setup(self, threads): self.cost_matrices = [random_uniform(self.shape) for _ in range(20)] def time_evaluation(self, threads): with ThreadPoolExecutor(max_workers=threads) as pool: wait({pool.submit(linear_sum_assignment, cost_matrix) for cost_matrix in self.cost_matrices})
ParallelLinearAssignment
python
kamyu104__LeetCode-Solutions
Python/build-array-from-permutation.py
{ "start": 48, "end": 590 }
class ____(object): def buildArray(self, nums): """ :type nums: List[int] :rtype: List[int] """ for i in xrange(len(nums)): prev, curr = i, nums[i] while curr >= 0 and curr != i: nums[prev], nums[curr] = ~nums[curr], ~nums[prev] if prev == i else nums[prev] prev, curr = curr, ~nums[prev] for i in xrange(len(nums)): if nums[i] < 0: nums[i] = ~nums[i] return nums # Time: O(n) # Space: O(1)
Solution
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar19.py
{ "start": 315, "end": 1494 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar19.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "bar"}) chart.axis_ids = [66558592, 66569344] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series({"values": "=Sheet1!$A$1:$A$5"}) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) chart.set_x_axis({"name": "=Sheet1!$A$2"}) chart.set_y_axis({"name": "=Sheet1!$A$3"}) chart.set_title({"name": "=Sheet1!$A$1"}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
scikit-learn__scikit-learn
sklearn/manifold/_locally_linear.py
{ "start": 20775, "end": 30531 }
class ____( ClassNamePrefixFeaturesOutMixin, TransformerMixin, _UnstableArchMixin, BaseEstimator, ): """Locally Linear Embedding. Read more in the :ref:`User Guide <locally_linear_embedding>`. Parameters ---------- n_neighbors : int, default=5 Number of neighbors to consider for each point. n_components : int, default=2 Number of coordinates for the manifold. reg : float, default=1e-3 Regularization constant, multiplies the trace of the local covariance matrix of the distances. eigen_solver : {'auto', 'arpack', 'dense'}, default='auto' The solver used to compute the eigenvectors. The available options are: - `'auto'` : algorithm will attempt to choose the best method for input data. - `'arpack'` : use arnoldi iteration in shift-invert mode. For this method, M may be a dense matrix, sparse matrix, or general linear operator. - `'dense'` : use standard dense matrix operations for the eigenvalue decomposition. For this method, M must be an array or matrix type. This method should be avoided for large problems. .. warning:: ARPACK can be unstable for some problems. It is best to try several random seeds in order to check results. tol : float, default=1e-6 Tolerance for 'arpack' method Not used if eigen_solver=='dense'. max_iter : int, default=100 Maximum number of iterations for the arpack solver. Not used if eigen_solver=='dense'. method : {'standard', 'hessian', 'modified', 'ltsa'}, default='standard' - `standard`: use the standard locally linear embedding algorithm. see reference [1]_ - `hessian`: use the Hessian eigenmap method. This method requires ``n_neighbors > n_components * (1 + (n_components + 1) / 2``. see reference [2]_ - `modified`: use the modified locally linear embedding algorithm. see reference [3]_ - `ltsa`: use local tangent space alignment algorithm. see reference [4]_ hessian_tol : float, default=1e-4 Tolerance for Hessian eigenmapping method. Only used if ``method == 'hessian'``. modified_tol : float, default=1e-12 Tolerance for modified LLE method. Only used if ``method == 'modified'``. neighbors_algorithm : {'auto', 'brute', 'kd_tree', 'ball_tree'}, \ default='auto' Algorithm to use for nearest neighbors search, passed to :class:`~sklearn.neighbors.NearestNeighbors` instance. random_state : int, RandomState instance, default=None Determines the random number generator when ``eigen_solver`` == 'arpack'. Pass an int for reproducible results across multiple function calls. See :term:`Glossary <random_state>`. n_jobs : int or None, default=None The number of parallel jobs to run. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. Attributes ---------- embedding_ : array-like, shape [n_samples, n_components] Stores the embedding vectors reconstruction_error_ : float Reconstruction error associated with `embedding_` n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 nbrs_ : NearestNeighbors object Stores nearest neighbors instance, including BallTree or KDtree if applicable. See Also -------- SpectralEmbedding : Spectral embedding for non-linear dimensionality reduction. TSNE : Distributed Stochastic Neighbor Embedding. References ---------- .. [1] Roweis, S. & Saul, L. Nonlinear dimensionality reduction by locally linear embedding. Science 290:2323 (2000). .. [2] Donoho, D. & Grimes, C. Hessian eigenmaps: Locally linear embedding techniques for high-dimensional data. Proc Natl Acad Sci U S A. 100:5591 (2003). .. [3] `Zhang, Z. & Wang, J. MLLE: Modified Locally Linear Embedding Using Multiple Weights. <https://citeseerx.ist.psu.edu/doc_view/pid/0b060fdbd92cbcc66b383bcaa9ba5e5e624d7ee3>`_ .. [4] Zhang, Z. & Zha, H. Principal manifolds and nonlinear dimensionality reduction via tangent space alignment. Journal of Shanghai Univ. 8:406 (2004) Examples -------- >>> from sklearn.datasets import load_digits >>> from sklearn.manifold import LocallyLinearEmbedding >>> X, _ = load_digits(return_X_y=True) >>> X.shape (1797, 64) >>> embedding = LocallyLinearEmbedding(n_components=2) >>> X_transformed = embedding.fit_transform(X[:100]) >>> X_transformed.shape (100, 2) """ _parameter_constraints: dict = { "n_neighbors": [Interval(Integral, 1, None, closed="left")], "n_components": [Interval(Integral, 1, None, closed="left")], "reg": [Interval(Real, 0, None, closed="left")], "eigen_solver": [StrOptions({"auto", "arpack", "dense"})], "tol": [Interval(Real, 0, None, closed="left")], "max_iter": [Interval(Integral, 1, None, closed="left")], "method": [StrOptions({"standard", "hessian", "modified", "ltsa"})], "hessian_tol": [Interval(Real, 0, None, closed="left")], "modified_tol": [Interval(Real, 0, None, closed="left")], "neighbors_algorithm": [StrOptions({"auto", "brute", "kd_tree", "ball_tree"})], "random_state": ["random_state"], "n_jobs": [None, Integral], } def __init__( self, *, n_neighbors=5, n_components=2, reg=1e-3, eigen_solver="auto", tol=1e-6, max_iter=100, method="standard", hessian_tol=1e-4, modified_tol=1e-12, neighbors_algorithm="auto", random_state=None, n_jobs=None, ): self.n_neighbors = n_neighbors self.n_components = n_components self.reg = reg self.eigen_solver = eigen_solver self.tol = tol self.max_iter = max_iter self.method = method self.hessian_tol = hessian_tol self.modified_tol = modified_tol self.random_state = random_state self.neighbors_algorithm = neighbors_algorithm self.n_jobs = n_jobs def _fit_transform(self, X): self.nbrs_ = NearestNeighbors( n_neighbors=self.n_neighbors, algorithm=self.neighbors_algorithm, n_jobs=self.n_jobs, ) random_state = check_random_state(self.random_state) X = validate_data(self, X, dtype=float) self.nbrs_.fit(X) self.embedding_, self.reconstruction_error_ = _locally_linear_embedding( X=self.nbrs_, n_neighbors=self.n_neighbors, n_components=self.n_components, eigen_solver=self.eigen_solver, tol=self.tol, max_iter=self.max_iter, method=self.method, hessian_tol=self.hessian_tol, modified_tol=self.modified_tol, random_state=random_state, reg=self.reg, n_jobs=self.n_jobs, ) self._n_features_out = self.embedding_.shape[1] @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y=None): """Compute the embedding vectors for data X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training set. y : Ignored Not used, present here for API consistency by convention. Returns ------- self : object Fitted `LocallyLinearEmbedding` class instance. """ self._fit_transform(X) return self @_fit_context(prefer_skip_nested_validation=True) def fit_transform(self, X, y=None): """Compute the embedding vectors for data X and transform X. Parameters ---------- X : array-like of shape (n_samples, n_features) Training set. y : Ignored Not used, present here for API consistency by convention. Returns ------- X_new : array-like, shape (n_samples, n_components) Returns the instance itself. """ self._fit_transform(X) return self.embedding_ def transform(self, X): """ Transform new points into embedding space. Parameters ---------- X : array-like of shape (n_samples, n_features) Training set. Returns ------- X_new : ndarray of shape (n_samples, n_components) Returns the instance itself. Notes ----- Because of scaling performed by this method, it is discouraged to use it together with methods that are not scale-invariant (like SVMs). """ check_is_fitted(self) X = validate_data(self, X, reset=False) ind = self.nbrs_.kneighbors( X, n_neighbors=self.n_neighbors, return_distance=False ) weights = barycenter_weights(X, self.nbrs_._fit_X, ind, reg=self.reg) X_new = np.empty((X.shape[0], self.n_components)) for i in range(X.shape[0]): X_new[i] = np.dot(self.embedding_[ind[i]].T, weights[i]) return X_new
LocallyLinearEmbedding
python
ipython__ipython
IPython/core/formatters.py
{ "start": 25804, "end": 26381 }
class ____(BaseFormatter): """An HTML formatter. To define the callables that compute the HTML representation of your objects, define a :meth:`_repr_html_` method or use the :meth:`for_type` or :meth:`for_type_by_name` methods to register functions that handle this. The return value of this formatter should be a valid HTML snippet that could be injected into an existing DOM. It should *not* include the ```<html>`` or ```<body>`` tags. """ format_type = Unicode('text/html') print_method = ObjectName('_repr_html_')
HTMLFormatter
python
apache__airflow
task-sdk/src/airflow/sdk/definitions/taskgroup.py
{ "start": 2998, "end": 24751 }
class ____(DAGNode): """ A collection of tasks. When set_downstream() or set_upstream() are called on the TaskGroup, it is applied across all tasks within the group if necessary. :param group_id: a unique, meaningful id for the TaskGroup. group_id must not conflict with group_id of TaskGroup or task_id of tasks in the Dag. Root TaskGroup has group_id set to None. :param prefix_group_id: If set to True, child task_id and group_id will be prefixed with this TaskGroup's group_id. If set to False, child task_id and group_id are not prefixed. Default is True. :param parent_group: The parent TaskGroup of this TaskGroup. parent_group is set to None for the root TaskGroup. :param dag: The Dag that this TaskGroup belongs to. :param default_args: A dictionary of default parameters to be used as constructor keyword parameters when initialising operators, will override default_args defined in the Dag level. Note that operators have the same hook, and precede those defined here, meaning that if your dict contains `'depends_on_past': True` here and `'depends_on_past': False` in the operator's call `default_args`, the actual value will be `False`. :param tooltip: The tooltip of the TaskGroup node when displayed in the UI :param ui_color: The fill color of the TaskGroup node when displayed in the UI :param ui_fgcolor: The label color of the TaskGroup node when displayed in the UI :param add_suffix_on_collision: If this task group name already exists, automatically add `__1` etc suffixes :param group_display_name: If set, this will be the display name for the TaskGroup node in the UI. """ _group_id: str | None = attrs.field( validator=attrs.validators.optional(_validate_group_id), # This is the default behaviour for attrs, but by specifying this it makes IDEs happier alias="group_id", ) group_display_name: str = attrs.field(default="", validator=attrs.validators.instance_of(str)) prefix_group_id: bool = attrs.field(default=True) parent_group: TaskGroup | None = attrs.field(factory=_default_parent_group) dag: DAG = attrs.field(default=attrs.Factory(_default_dag, takes_self=True)) default_args: dict[str, Any] = attrs.field(factory=dict, converter=copy.deepcopy) tooltip: str = attrs.field(default="", validator=attrs.validators.instance_of(str)) children: dict[str, DAGNode] = attrs.field(factory=dict, init=False) upstream_group_ids: set[str | None] = attrs.field(factory=set, init=False) downstream_group_ids: set[str | None] = attrs.field(factory=set, init=False) upstream_task_ids: set[str] = attrs.field(factory=set, init=False) downstream_task_ids: set[str] = attrs.field(factory=set, init=False) used_group_ids: set[str] = attrs.field( default=attrs.Factory(_parent_used_group_ids, takes_self=True), init=False, on_setattr=attrs.setters.frozen, ) ui_color: str = attrs.field(default="CornflowerBlue", validator=attrs.validators.instance_of(str)) ui_fgcolor: str = attrs.field(default="#000", validator=attrs.validators.instance_of(str)) add_suffix_on_collision: bool = False @dag.validator def _validate_dag(self, _attr, dag): if not dag: raise RuntimeError("TaskGroup can only be used inside a dag") def __attrs_post_init__(self): # TODO: If attrs supported init only args we could use that here # https://github.com/python-attrs/attrs/issues/342 self._check_for_group_id_collisions(self.add_suffix_on_collision) if self._group_id and not self.parent_group and self.dag: # Support `tg = TaskGroup(x, dag=dag)` self.parent_group = self.dag.task_group if self.parent_group: self.parent_group.add(self) if self.parent_group.default_args: self.default_args = { **self.parent_group.default_args, **self.default_args, } if self._group_id: self.used_group_ids.add(self.group_id) self.used_group_ids.add(self.downstream_join_id) self.used_group_ids.add(self.upstream_join_id) def _check_for_group_id_collisions(self, add_suffix_on_collision: bool): if self._group_id is None: return # if given group_id already used assign suffix by incrementing largest used suffix integer # Example : task_group ==> task_group__1 -> task_group__2 -> task_group__3 if self.group_id in self.used_group_ids: if not add_suffix_on_collision: raise DuplicateTaskIdFound(f"group_id '{self._group_id}' has already been added to the DAG") base = re.split(r"__\d+$", self._group_id)[0] suffixes = sorted( int(re.split(r"^.+__", used_group_id)[1]) for used_group_id in self.used_group_ids if used_group_id is not None and re.match(rf"^{base}__\d+$", used_group_id) ) if not suffixes: self._group_id += "__1" else: self._group_id = f"{base}__{suffixes[-1] + 1}" @classmethod def create_root(cls, dag: DAG) -> TaskGroup: """Create a root TaskGroup with no group_id or parent.""" return cls(group_id=None, dag=dag, parent_group=None) @property def node_id(self): return self.group_id @property def is_root(self) -> bool: """Returns True if this TaskGroup is the root TaskGroup. Otherwise False.""" return not self._group_id @property def task_group(self) -> TaskGroup | None: return self.parent_group @task_group.setter def task_group(self, value: TaskGroup | None): self.parent_group = value def __iter__(self): for child in self.children.values(): yield from self._iter_child(child) @staticmethod def _iter_child(child): """Iterate over the children of this TaskGroup.""" if isinstance(child, TaskGroup): yield from child else: yield child def add(self, task: DAGNode) -> DAGNode: """ Add a task or TaskGroup to this TaskGroup. :meta private: """ from airflow.sdk.definitions._internal.abstractoperator import AbstractOperator from airflow.sdk.definitions._internal.contextmanager import TaskGroupContext if TaskGroupContext.active: if task.task_group and task.task_group != self: task.task_group.children.pop(task.node_id, None) task.task_group = self existing_tg = task.task_group if isinstance(task, AbstractOperator) and existing_tg is not None and existing_tg != self: raise TaskAlreadyInTaskGroup(task.node_id, existing_tg.node_id, self.node_id) # Set the TG first, as setting it might change the return value of node_id! task.task_group = weakref.proxy(self) key = task.node_id if key in self.children: node_type = "Task" if hasattr(task, "task_id") else "Task Group" raise DuplicateTaskIdFound(f"{node_type} id '{key}' has already been added to the Dag") if isinstance(task, TaskGroup): if self.dag: if task.dag is not None and self.dag is not task.dag: raise ValueError( "Cannot mix TaskGroups from different Dags: %s and %s", self.dag, task.dag, ) task.dag = self.dag if task.children: raise ValueError("Cannot add a non-empty TaskGroup") self.children[key] = task return task def _remove(self, task: DAGNode) -> None: key = task.node_id if key not in self.children: raise KeyError(f"Node id {key!r} not part of this task group") self.used_group_ids.remove(key) del self.children[key] @property def group_id(self) -> str | None: """group_id of this TaskGroup.""" if ( self._group_id and self.parent_group and self.parent_group.prefix_group_id and self.parent_group._group_id ): # defer to parent whether it adds a prefix return self.parent_group.child_id(self._group_id) return self._group_id @property def label(self) -> str | None: """group_id excluding parent's group_id used as the node label in UI.""" return self.group_display_name or self._group_id def update_relative( self, other: DependencyMixin, upstream: bool = True, edge_modifier: EdgeModifier | None = None, ) -> None: """ Override TaskMixin.update_relative. Update upstream_group_ids/downstream_group_ids/upstream_task_ids/downstream_task_ids accordingly so that we can reduce the number of edges when displaying Graph view. """ if isinstance(other, TaskGroup): # Handles setting relationship between a TaskGroup and another TaskGroup if upstream: parent, child = (self, other) if edge_modifier: edge_modifier.add_edge_info(self.dag, other.downstream_join_id, self.upstream_join_id) else: parent, child = (other, self) if edge_modifier: edge_modifier.add_edge_info(self.dag, self.downstream_join_id, other.upstream_join_id) parent.upstream_group_ids.add(child.group_id) child.downstream_group_ids.add(parent.group_id) else: # Handles setting relationship between a TaskGroup and a task for task in other.roots: if not isinstance(task, DAGNode): raise RuntimeError( "Relationships can only be set between TaskGroup " f"or operators; received {task.__class__.__name__}" ) # Do not set a relationship between a TaskGroup and a Label's roots if self == task: continue if upstream: self.upstream_task_ids.add(task.node_id) if edge_modifier: edge_modifier.add_edge_info(self.dag, task.node_id, self.upstream_join_id) else: self.downstream_task_ids.add(task.node_id) if edge_modifier: edge_modifier.add_edge_info(self.dag, self.downstream_join_id, task.node_id) def _set_relatives( self, task_or_task_list: DependencyMixin | Sequence[DependencyMixin], upstream: bool = False, edge_modifier: EdgeModifier | None = None, ) -> None: """ Call set_upstream/set_downstream for all root/leaf tasks within this TaskGroup. Update upstream_group_ids/downstream_group_ids/upstream_task_ids/downstream_task_ids. """ if not isinstance(task_or_task_list, Sequence): task_or_task_list = [task_or_task_list] # Helper function to find leaves from a task list or task group def find_leaves(group_or_task) -> list[Any]: while group_or_task: group_or_task_leaves = list(group_or_task.get_leaves()) if group_or_task_leaves: return group_or_task_leaves if group_or_task.upstream_task_ids: upstream_task_ids_list = list(group_or_task.upstream_task_ids) return [self.dag.get_task(task_id) for task_id in upstream_task_ids_list] group_or_task = group_or_task.parent_group return [] # Check if the current TaskGroup is empty leaves = find_leaves(self) for task_like in task_or_task_list: self.update_relative(task_like, upstream, edge_modifier=edge_modifier) if upstream: for task in self.get_roots(): task.set_upstream(task_or_task_list) else: for task in leaves: # Use the fetched leaves task.set_downstream(task_or_task_list) def __enter__(self) -> TaskGroup: from airflow.sdk.definitions._internal.contextmanager import TaskGroupContext TaskGroupContext.push(self) return self def __exit__(self, _type, _value, _tb): from airflow.sdk.definitions._internal.contextmanager import TaskGroupContext TaskGroupContext.pop() def has_task(self, task: BaseOperator) -> bool: """Return True if this TaskGroup or its children TaskGroups contains the given task.""" if task.task_id in self.children: return True return any(child.has_task(task) for child in self.children.values() if isinstance(child, TaskGroup)) @property def roots(self) -> list[BaseOperator]: """Required by DependencyMixin.""" return list(self.get_roots()) @property def leaves(self) -> list[BaseOperator]: """Required by DependencyMixin.""" return list(self.get_leaves()) def get_roots(self) -> Generator[BaseOperator, None, None]: """Return a generator of tasks with no upstream dependencies within the TaskGroup.""" tasks = list(self) ids = {x.task_id for x in tasks} for task in tasks: if task.upstream_task_ids.isdisjoint(ids): yield task def get_leaves(self) -> Generator[BaseOperator, None, None]: """Return a generator of tasks with no downstream dependencies within the TaskGroup.""" tasks = list(self) ids = {x.task_id for x in tasks} def has_non_teardown_downstream(task, exclude: str): for down_task in task.downstream_list: if down_task.task_id == exclude: continue if down_task.task_id not in ids: continue if not down_task.is_teardown: return True return False def recurse_for_first_non_teardown(task): for upstream_task in task.upstream_list: if upstream_task.task_id not in ids: # upstream task is not in task group continue elif upstream_task.is_teardown: yield from recurse_for_first_non_teardown(upstream_task) elif task.is_teardown and upstream_task.is_setup: # don't go through the teardown-to-setup path continue # return unless upstream task already has non-teardown downstream in group elif not has_non_teardown_downstream(upstream_task, exclude=task.task_id): yield upstream_task for task in tasks: if task.downstream_task_ids.isdisjoint(ids): if not task.is_teardown: yield task else: yield from recurse_for_first_non_teardown(task) def child_id(self, label): """Prefix label with group_id if prefix_group_id is True. Otherwise return the label as-is.""" if self.prefix_group_id: group_id = self.group_id if group_id: return f"{group_id}.{label}" return label @property def upstream_join_id(self) -> str: """ Creates a unique ID for upstream dependencies of this TaskGroup. If this TaskGroup has immediate upstream TaskGroups or tasks, a proxy node called upstream_join_id will be created in Graph view to join the outgoing edges from this TaskGroup to reduce the total number of edges needed to be displayed. """ return f"{self.group_id}.upstream_join_id" @property def downstream_join_id(self) -> str: """ Creates a unique ID for downstream dependencies of this TaskGroup. If this TaskGroup has immediate downstream TaskGroups or tasks, a proxy node called downstream_join_id will be created in Graph view to join the outgoing edges from this TaskGroup to reduce the total number of edges needed to be displayed. """ return f"{self.group_id}.downstream_join_id" def get_task_group_dict(self) -> dict[str, TaskGroup]: """Return a flat dictionary of group_id: TaskGroup.""" task_group_map = {} def build_map(task_group): if not isinstance(task_group, TaskGroup): return task_group_map[task_group.group_id] = task_group for child in task_group.children.values(): build_map(child) build_map(self) return task_group_map def get_child_by_label(self, label: str) -> DAGNode: """Get a child task/TaskGroup by its label (i.e. task_id/group_id without the group_id prefix).""" return self.children[self.child_id(label)] def serialize_for_task_group(self) -> tuple[DagAttributeTypes, Any]: """Serialize task group; required by DagNode.""" from airflow.serialization.enums import DagAttributeTypes from airflow.serialization.serialized_objects import TaskGroupSerialization return ( DagAttributeTypes.TASK_GROUP, TaskGroupSerialization.serialize_task_group(self), ) def hierarchical_alphabetical_sort(self): """ Sort children in hierarchical alphabetical order. - groups in alphabetical order first - tasks in alphabetical order after them. :return: list of tasks in hierarchical alphabetical order """ return sorted( self.children.values(), key=lambda node: (not isinstance(node, TaskGroup), node.node_id), ) def topological_sort(self): """ Sorts children in topographical order, such that a task comes after any of its upstream dependencies. :return: list of tasks in topological order """ # This uses a modified version of Kahn's Topological Sort algorithm to # not have to pre-compute the "in-degree" of the nodes. graph_unsorted = copy.copy(self.children) graph_sorted: list[DAGNode] = [] # special case if not self.children: return graph_sorted # Run until the unsorted graph is empty. while graph_unsorted: # Go through each of the node/edges pairs in the unsorted graph. If a set of edges doesn't contain # any nodes that haven't been resolved, that is, that are still in the unsorted graph, remove the # pair from the unsorted graph, and append it to the sorted graph. Note here that by using # the values() method for iterating, a copy of the unsorted graph is used, allowing us to modify # the unsorted graph as we move through it. # # We also keep a flag for checking that graph is acyclic, which is true if any nodes are resolved # during each pass through the graph. If not, we need to exit as the graph therefore can't be # sorted. acyclic = False for node in list(graph_unsorted.values()): for edge in node.upstream_list: if edge.node_id in graph_unsorted: break # Check for task's group is a child (or grand child) of this TG, tg = edge.task_group while tg: if tg.node_id in graph_unsorted: break tg = tg.parent_group if tg: # We are already going to visit that TG break else: acyclic = True del graph_unsorted[node.node_id] graph_sorted.append(node) if not acyclic: raise AirflowDagCycleException(f"A cyclic dependency occurred in dag: {self.dag_id}") return graph_sorted def iter_mapped_task_groups(self) -> Iterator[MappedTaskGroup]: """ Return mapped task groups in the hierarchy. Groups are returned from the closest to the outmost. If *self* is a mapped task group, it is returned first. :meta private: """ group: TaskGroup | None = self while group is not None: if isinstance(group, MappedTaskGroup): yield group group = group.parent_group def iter_tasks(self) -> Iterator[AbstractOperator]: """Return an iterator of the child tasks.""" from airflow.sdk.definitions._internal.abstractoperator import AbstractOperator groups_to_visit = [self] while groups_to_visit: visiting = groups_to_visit.pop(0) for child in visiting.children.values(): if isinstance(child, AbstractOperator): yield child elif isinstance(child, TaskGroup): groups_to_visit.append(child) else: raise ValueError( f"Encountered a DAGNode that is not a TaskGroup or an " f"AbstractOperator: {type(child).__module__}.{type(child)}" ) @attrs.define(kw_only=True, repr=False)
TaskGroup
python
spack__spack
lib/spack/spack/vendor/macholib/mach_o.py
{ "start": 35843, "end": 36846 }
class ____(Structure): _fields_ = ( ("rebase_off", p_uint32), ("rebase_size", p_uint32), ("bind_off", p_uint32), ("bind_size", p_uint32), ("weak_bind_off", p_uint32), ("weak_bind_size", p_uint32), ("lazy_bind_off", p_uint32), ("lazy_bind_size", p_uint32), ("export_off", p_uint32), ("export_size", p_uint32), ) def describe(self): dyld = {} dyld["rebase_off"] = int(self.rebase_off) dyld["rebase_size"] = int(self.rebase_size) dyld["bind_off"] = int(self.bind_off) dyld["bind_size"] = int(self.bind_size) dyld["weak_bind_off"] = int(self.weak_bind_off) dyld["weak_bind_size"] = int(self.weak_bind_size) dyld["lazy_bind_off"] = int(self.lazy_bind_off) dyld["lazy_bind_size"] = int(self.lazy_bind_size) dyld["export_off"] = int(self.export_off) dyld["export_size"] = int(self.export_size) return dyld
dyld_info_command
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 206886, "end": 208196 }
class ____(sgqlc.types.Input): """Autogenerated input type of CreateSponsorships""" __schema__ = github_schema __field_names__ = ("sponsor_login", "sponsorships", "receive_emails", "privacy_level", "client_mutation_id") sponsor_login = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="sponsorLogin") """The username of the user or organization who is acting as the sponsor, paying for the sponsorships. """ sponsorships = sgqlc.types.Field( sgqlc.types.non_null(sgqlc.types.list_of(sgqlc.types.non_null(BulkSponsorship))), graphql_name="sponsorships" ) """The list of maintainers to sponsor and for how much apiece.""" receive_emails = sgqlc.types.Field(Boolean, graphql_name="receiveEmails") """Whether the sponsor should receive email updates from the sponsorables. """ privacy_level = sgqlc.types.Field(SponsorshipPrivacy, graphql_name="privacyLevel") """Specify whether others should be able to see that the sponsor is sponsoring the sponsorables. Public visibility still does not reveal the dollar value of the sponsorship. """ client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
CreateSponsorshipsInput
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 46532, "end": 47020 }
class ____(VOTableSpecWarning): """Incorrect ``system`` attribute on COOSYS element. The ``system`` attribute must be one of the following:: 'eq_FK4', 'eq_FK5', 'ICRS', 'ecl_FK4', 'ecl_FK5', 'galactic', 'supergalactic', 'xy', 'barycentric', 'geo_app' **References**: `1.1 <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:COOSYS>`__ """ message_template = "Invalid system attribute '{}'" default_args = ("x",)
E16
python
numba__numba
numba/core/types/common.py
{ "start": 190, "end": 266 }
class ____(Dummy): """ A type that is a opaque pointer. """
Opaque
python
PrefectHQ__prefect
tests/test_tasks.py
{ "start": 138600, "end": 143537 }
class ____: def test_noniterable_hook_raises(self): def completion_hook(): pass with pytest.raises( TypeError, match=re.escape( "Expected iterable for 'on_completion'; got function instead. Please" " provide a list of hooks to 'on_completion':\n\n" "@task(on_completion=[hook1, hook2])\ndef my_task():\n\tpass" ), ): @task(on_completion=completion_hook) def task1(): pass def test_decorated_on_completion_hooks_run_on_completed(self): my_mock = MagicMock() @task def my_task(): pass @my_task.on_completion def completed1(task, task_run, state): my_mock("completed1") @my_task.on_completion def completed2(task, task_run, state): my_mock("completed2") @flow def my_flow(): return my_task(return_state=True) state = my_flow() assert state.type == StateType.COMPLETED assert my_mock.call_args_list == [call("completed1"), call("completed2")] def test_noncallable_hook_raises(self): with pytest.raises( TypeError, match=re.escape( "Expected callables in 'on_completion'; got str instead. Please provide" " a list of hooks to 'on_completion':\n\n" "@task(on_completion=[hook1, hook2])\ndef my_task():\n\tpass" ), ): @task(on_completion=["test"]) def task1(): pass def test_callable_noncallable_hook_raises(self): def completion_hook(): pass with pytest.raises( TypeError, match=re.escape( "Expected callables in 'on_completion'; got str instead. Please provide" " a list of hooks to 'on_completion':\n\n" "@task(on_completion=[hook1, hook2])\ndef my_task():\n\tpass" ), ): @task(on_completion=[completion_hook, "test"]) def task2(): pass def test_on_completion_hooks_run_on_completed(self): my_mock = MagicMock() def completed1(task, task_run, state): my_mock("completed1") def completed2(task, task_run, state): my_mock("completed2") @task(on_completion=[completed1, completed2]) def my_task(): pass @flow def my_flow(): return my_task(return_state=True) state = my_flow() assert state.type == StateType.COMPLETED assert my_mock.call_args_list == [call("completed1"), call("completed2")] def test_on_completion_hooks_dont_run_on_failure(self): my_mock = MagicMock() def completed1(task, task_run, state): my_mock("completed1") def completed2(task, task_run, state): my_mock("completed2") @task(on_completion=[completed1, completed2]) def my_task(): raise Exception("oops") @flow def my_flow(): future = my_task.submit() future.wait() return future.state with pytest.raises(Exception, match="oops"): state = my_flow() assert state == StateType.FAILED assert my_mock.call_args_list == [] def test_other_completion_hooks_run_if_a_hook_fails(self): my_mock = MagicMock() def completed1(task, task_run, state): my_mock("completed1") def exception_hook(task, task_run, state): raise Exception("oops") def completed2(task, task_run, state): my_mock("completed2") @task(on_completion=[completed1, exception_hook, completed2]) def my_task(): pass @flow def my_flow(): return my_task(return_state=True) state = my_flow() assert state.type == StateType.COMPLETED assert my_mock.call_args_list == [call("completed1"), call("completed2")] @pytest.mark.parametrize( "hook1, hook2", [ (create_hook, create_hook), (create_hook, create_async_hook), (create_async_hook, create_hook), (create_async_hook, create_async_hook), ], ) def test_on_completion_hooks_work_with_sync_and_async(self, hook1, hook2): my_mock = MagicMock() hook1_with_mock = hook1(my_mock) hook2_with_mock = hook2(my_mock) @task(on_completion=[hook1_with_mock, hook2_with_mock]) def my_task(): pass @flow def my_flow(): return my_task(return_state=True) state = my_flow() assert state.type == StateType.COMPLETED assert my_mock.call_args_list == [call(), call()]
TestTaskHooksOnCompletion
python
ansible__ansible
lib/ansible/module_utils/facts/hardware/freebsd.py
{ "start": 9910, "end": 10021 }
class ____(HardwareCollector): _fact_class = FreeBSDHardware _platform = 'FreeBSD'
FreeBSDHardwareCollector
python
simplejson__simplejson
simplejson/tests/test_namedtuple.py
{ "start": 1041, "end": 1167 }
class ____(dict): _asdict = None CONSTRUCTORS = [ lambda v: v, lambda v: [v], lambda v: [{'key': v}], ]
DeadDict
python
dagster-io__dagster
python_modules/dagster/dagster/_config/config_type.py
{ "start": 509, "end": 1768 }
class ____(PythonEnum): ANY = "ANY" SCALAR = "SCALAR" ENUM = "ENUM" SELECTOR = "SELECTOR" STRICT_SHAPE = "STRICT_SHAPE" PERMISSIVE_SHAPE = "PERMISSIVE_SHAPE" SCALAR_UNION = "SCALAR_UNION" MAP = "MAP" # Closed generic types ARRAY = "ARRAY" NONEABLE = "NONEABLE" @staticmethod def has_fields(kind: "ConfigTypeKind") -> bool: check.inst_param(kind, "kind", ConfigTypeKind) return kind == ConfigTypeKind.SELECTOR or ConfigTypeKind.is_shape(kind) @staticmethod def is_closed_generic(kind: "ConfigTypeKind") -> bool: check.inst_param(kind, "kind", ConfigTypeKind) return ( kind == ConfigTypeKind.ARRAY or kind == ConfigTypeKind.NONEABLE or kind == ConfigTypeKind.SCALAR_UNION or kind == ConfigTypeKind.MAP ) @staticmethod def is_shape(kind: "ConfigTypeKind") -> bool: check.inst_param(kind, "kind", ConfigTypeKind) return kind == ConfigTypeKind.STRICT_SHAPE or kind == ConfigTypeKind.PERMISSIVE_SHAPE @staticmethod def is_selector(kind: "ConfigTypeKind") -> bool: check.inst_param(kind, "kind", ConfigTypeKind) return kind == ConfigTypeKind.SELECTOR
ConfigTypeKind
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events_stats_profile_functions.py
{ "start": 189, "end": 1687 }
class ____(OrganizationEventsEndpointTestBase): dataset = "profile_functions" viewname = "sentry-api-0-organization-events-stats" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) self.start = self.day_ago = before_now(days=1).replace( hour=10, minute=0, second=0, microsecond=0 ) self.end = self.start + timedelta(hours=4) def test_simple(self) -> None: function_values = [1, 2, 3, 4] profile_functions = [ self.create_profile_function( timestamp=self.start + timedelta(hours=i), attributes={"name": function_name, "self_time_ns": function_value}, ) for function_name in ["foo", "bar"] for i, function_value in enumerate(function_values) ] self.store_profile_functions(profile_functions) response = self.do_request( { "start": self.start, "end": self.end, "interval": "1h", "yAxis": "sum(function.self_time)", "query": "function:foo", "project": self.project.id, "dataset": self.dataset, } ) assert response.status_code == 200, response.content assert [bucket for _, bucket in response.data["data"]] == [ [{"count": value}] for value in function_values ]
OrganizationEventsStatsProfileFunctionsEndpointTest
python
pytorch__pytorch
torch/_inductor/cudagraph_trees.py
{ "start": 16399, "end": 21094 }
class ____: """ Wrapper around a storage weak ref. Will deallocate it upon expiration if invoked. """ __slots__ = ["ref", "_data_ptr", "extra_ref_check"] storage_ref: Optional[StorageWeakRef] def __init__( self, inp: Union[Tensor, UntypedStorage], extra_ref_check: Optional[Callable[[], bool]] = None, ) -> None: """ extra_ref_check is an additional check we need to run to check if the weak ref has expired. in checking storage use count we assume extra_ref_check will hold an additional reference to the storage. """ if isinstance(inp, Tensor): stor = inp.untyped_storage() else: assert isinstance(inp, UntypedStorage) stor = inp self.ref = StorageWeakRef(stor) self._data_ptr = stor.data_ptr() self.extra_ref_check = extra_ref_check @classmethod def from_weakref_and_data_ptr( cls: type[StorageWeakRefWrapper], cdata: Any, data_ptr: int, extra_ref_check: Optional[Callable[[], bool]] = None, ) -> StorageWeakRefWrapper: instance = cls.__new__(cls) instance._data_ptr = data_ptr instance.ref = StorageWeakRef.from_weakref(cdata) instance.extra_ref_check = extra_ref_check return instance def __call__(self) -> Optional[StorageWeakRefPointer]: if self.expired(): return None return self.ref.cdata def swap_weakref(self, cdata: Any) -> None: self.ref.__del__() self.ref.cdata = cdata def data_ptr(self) -> int: "NB: returns the data ptr even if the storage has expired" return self._data_ptr def remove_extra_reference(self) -> None: self.extra_ref_check = None def expired(self) -> bool: if self.extra_ref_check is not None and not self.extra_ref_check(): return False stor_count = torch._C._storage_Use_Count(self.ref.cdata) if self.extra_ref_check is not None: # if extra_ref_check is not None we expect two additional references: # - one from the Python storage object # - one from the cached Tensor stor_count -= 2 assert stor_count >= 0 return stor_count == 0 def __repr__(self) -> str: if self.ref is None or self.ref.expired(): return f"StorageWeakRefWrapper to {self.data_ptr()}; dead" else: return f"StorageWeakRefWrapper to {self.data_ptr()}; alive" def is_live(weak_ref: Optional[StorageWeakRefWrapper]) -> bool: return maybe_deref(weak_ref) is not None def maybe_deref( weak_ref: Optional[StorageWeakRefWrapper], ) -> Optional[tuple[StorageWeakRefPointer, int]]: if weak_ref is None: return None r = weak_ref() if r is None: return None # NB: r.data_ptr() does not necessarily equal weak_ref.data_ptr() return r, weak_ref.data_ptr() @contextlib.contextmanager def _use_cuda_memory_pool_manager( device: int, mem_pool: tuple[int, int], stream: torch.cuda.Stream ) -> Generator[None, None, None]: """ Context manager to use cuda graph pool for new allocations. If you use this manager all cudagraph tensors in use should be reflected in the allocator or they will be overwritten. existing_graph should already have been used in a capture, and the mem_pool must already exist, because this manager will not preserve a reference to the pool which keeps it alive. """ torch.cuda.synchronize() stream.wait_stream(torch.cuda.current_stream()) with torch.cuda.stream(stream), torch.device(device): # Begin allocate to mem pool for all memory allocation on the current thread. # This is thread safe since a thread can only warmup or record 1 cudagraph # at the same time. torch._C._cuda_beginAllocateCurrentThreadToPool(device, mem_pool) try: yield finally: torch._C._cuda_endAllocateToPool(device, mem_pool) torch._C._cuda_releasePool(device, mem_pool) torch.cuda.current_stream().wait_stream(stream) def map_to_ref(t: Optional[Tensor]) -> Optional[StorageWeakRefWrapper]: if not isinstance(t, torch.Tensor): assert t is None return None return StorageWeakRefWrapper(t) # A path index of (depth, offset) indices into a graph that is `depth`` number of nodes from the root # at graph output offset PathOutputIndex = tuple[int, int] # For each node in the path, for each output, is the output alive PathLiveness = list[list[bool]] StackTraces = list[Optional[str]]
StorageWeakRefWrapper
python
google__jax
jax/_src/interpreters/pxla.py
{ "start": 3063, "end": 14320 }
class ____(list): pass unsafe_map, map = map, safe_map # type: ignore zip, unsafe_zip = safe_zip, zip # type: ignore logger = logging.getLogger(__name__) Index = Union[int, slice, tuple[Union[int, slice], ...]] PyTreeDef = tree_util.PyTreeDef NoSharding = sharding_specs.NoSharding Chunked = sharding_specs.Chunked Unstacked = sharding_specs.Unstacked ShardedAxis = sharding_specs.ShardedAxis Replicated = sharding_specs.Replicated AvalDimSharding = Union[Unstacked, Chunked, NoSharding] MeshAxisName = sharding_impls.MeshAxisName MeshDimAssignment = Union[ShardedAxis, Replicated] ShardingSpec = sharding_specs.ShardingSpec ### util def identity(x): return x @profiler.annotate_function def shard_args( shardings: Sequence[JSharding], layouts: Sequence[Any | None], copy_semantics: Sequence[xc.ArrayCopySemantics], args: Sequence[Any], canonicalize: bool = True, ) -> Sequence[xc.ArrayImpl]: # Fast path for one argument. if len(args) == 1: arg = args[0] if canonicalize: arg = dtypes.canonicalize_value(arg) return shard_arg_handlers[type(arg)]([arg], shardings, layouts, copy_semantics) # type(arg) -> (list[indices], list[args], list[shardings], list[layouts], # list[copy_semantics]) batches = collections.defaultdict(lambda: ([], [], [], [], [])) # type: ignore for i, (arg, sharding, layout, cs) in enumerate( safe_zip(args, shardings, layouts, copy_semantics)): if canonicalize: arg = dtypes.canonicalize_value(arg) batch = batches[type(arg)] batch[0].append(i) batch[1].append(arg) batch[2].append(sharding) batch[3].append(layout) batch[4].append(cs) # Call `shard_arg_handlers` per batch and build a flat list of arrays returned # from each call in the same order as `args`. Since `batches` is grouped by # types, we cannot simply flatten the results and we have to use the original # indices to put each array back to its original position. results: list[typing.Array | None] = [None] * len(args) for t, (indices, a, s, l, xcs) in batches.items(): outs = shard_arg_handlers[t](a, s, l, xcs) for i, out in safe_zip(indices, outs): results[i] = out assert all(result is not None for result in results) return results shard_arg_handlers: dict[ Any, Callable[ [Sequence[Any], Sequence[Any], Sequence[Any], Sequence[xc.ArrayCopySemantics]], Sequence[Any], ], ] = {} @util.cache(max_size=2048, trace_context_in_key=False) def is_default_layout(curr_layout, sharding, aval): if curr_layout is None or sharding is None or isinstance(sharding, UnspecifiedValue): return True if (aval is core.abstract_token or aval.dtype == dtypes.float0 or dtypes.issubdtype(aval.dtype, dtypes.extended)): return True if isinstance(curr_layout, AutoLayout): return False d = sharding._device_assignment[0] shard_shape = sharding.shard_shape(aval.shape) try: # TODO(yashkatariya): Replace this with normal `==` check once CPU supports # int4. return is_user_xla_layout_equal( curr_layout, Layout.from_pjrt_layout( d.client.get_default_layout(aval.dtype, shard_shape, d))) except _jax.JaxRuntimeError as e: msg, *_ = e.args if isinstance(msg, str) and msg.startswith("UNIMPLEMENTED"): return True else: raise def _masked_array_error(xs, shardings, layouts, copy_semantics): raise ValueError("numpy masked arrays are not supported as direct inputs to JAX functions. " "Use arr.filled() to convert the value to a standard numpy array.") shard_arg_handlers[np.ma.MaskedArray] = _masked_array_error def _shard_np_array(xs, shardings, layouts, copy_semantics): results = [] for x, sharding, layout in safe_zip(xs, shardings, layouts): devices = sharding._addressable_device_assignment if x.dtype == dtypes.float0: x = np.zeros(x.shape, dtype=np.dtype(bool)) aval = core.shaped_abstractify(x) if layout is not None: results.append(api.device_put(x, Format(layout, sharding))) else: if sharding.is_fully_replicated: shards = [x] * len(devices) else: indices = tuple(sharding.addressable_devices_indices_map(x.shape).values()) shards = [x[i] for i in indices] results.append(batched_device_put(aval, sharding, shards, devices)) return results for _t in array_types: shard_arg_handlers[_t] = _shard_np_array shard_arg_handlers[literals.TypedNdArray] = _shard_np_array def _shard_python_scalar(xs, shardings, layouts, copy_semantics): return shard_args(shardings, layouts, copy_semantics, [np.array(x) for x in xs]) for _t in dtypes.python_scalar_types: shard_arg_handlers[_t] = _shard_python_scalar def _shard_typed_scalar(xs, shardings, layouts, copy_semantics): return _shard_np_array( [literals.TypedNdArray(np.array(x, dtype=x.dtype), weak_type=True) for x in xs], shardings, layouts, copy_semantics ) for _t in literals.typed_scalar_types: shard_arg_handlers[_t] = _shard_typed_scalar def _shard_darray(xs, shardings, layouts, copy_semantics): bufs = [x._data for x in xs] return shard_args(shardings, layouts, copy_semantics, bufs) shard_arg_handlers[core.DArray] = _shard_darray def _shard_mutable_array(xs, shardings, layouts, copy_semantics): bufs = [x._refs._buf for x in xs] return shard_args(shardings, layouts, copy_semantics, bufs) shard_arg_handlers[core.Ref] = _shard_mutable_array def batched_device_put(aval: core.ShapedArray, sharding: JSharding, xs: Sequence[Any], devices: Sequence[xc.Device], committed: bool = True, enable_x64: bool | None = None): util.test_event("batched_device_put_start") try: bufs = [x for x, d in safe_zip(xs, devices) if (isinstance(x, array.ArrayImpl) and dispatch.is_single_device_sharding(x.sharding) and x.devices() == {d})] if len(bufs) == len(xs) > 0: return array.ArrayImpl( aval, sharding, bufs, committed=committed, _skip_checks=True) return xc.batched_device_put(aval, sharding, xs, list(devices), committed, enable_x64=enable_x64) finally: util.test_event("batched_device_put_end") def _shard_aval(size, axis: int, aval): try: return _shard_aval_handlers[type(aval)](size, axis, aval) except KeyError as err: raise TypeError(f"No _shard_aval handler for type: {type(aval)}") from err _shard_aval_handlers: dict[type[core.AbstractValue], Callable[[int, int, Any], Any]] = {} def _shard_abstract_array(size, axis: int, x): try: if x.shape[axis] != size: raise ValueError(f"Axis size {size} does not match dimension {axis} of " f"shape {x.shape}") except IndexError: raise ValueError(f"Cannot split a {x.dim}D value along axis {axis}") from None if config.pmap_no_rank_reduction.value: return x.update(shape=tuple_update(x.shape, axis, 1)) else: return x.update(shape=tuple_delete(x.shape, axis)) _shard_aval_handlers[ShapedArray] = _shard_abstract_array def local_aval_to_result_handler( aval: core.AbstractValue, sharding: JSharding, indices: tuple[Index, ...] | None, ) -> Callable[[list[xc.ArrayImpl]], Any]: """Returns a function for handling the raw buffers of a single output aval. Args: aval: The local output AbstractValue. sharding_spec: Indicates how the output is sharded across devices, or None for non-array avals. indices: The pre-computed result of spec_to_indices, or None for non-array avals. Returns: A function for handling the Buffers that will eventually be produced for this output. The function will return an object suitable for returning to the user, e.g. an Array. """ try: return local_result_handlers[(type(aval))](aval, sharding, indices) except KeyError as err: raise TypeError( f"No pxla_result_handler for type: {type(aval)}") from err PxlaResultHandler = Callable[..., Callable[[Any], Any]] local_result_handlers: dict[type[core.AbstractValue], PxlaResultHandler] = {} def global_aval_to_result_handler( aval: core.AbstractValue, out_sharding, committed: bool ) -> Callable[[Sequence[xc.ArrayImpl]], Any]: """Returns a function for handling the raw buffers of a single output aval. Args: aval: The global output AbstractValue. out_axis_resources: A PartitionSpec specifying the sharding of outputs. Used for creating GSDAs. global_mesh: The global device mesh that generated this output. Used for creating GSDAs. Returns: A function for handling the Buffers that will eventually be produced for this output. The function will return an object suitable for returning to the user, e.g. an Array. """ try: return global_result_handlers[type(aval)](aval, out_sharding, committed) except KeyError as err: raise TypeError( f"No pxla_result_handler for type: {type(aval)}") from err global_result_handlers: dict[type[core.AbstractValue], PxlaResultHandler] = {} ### lazy device-memory persistence and result handling ### the xla_pmap primitive and its rules are comparable to xla_call in xla.py def xla_pmap_impl_lazy( fun: lu.WrappedFun, *args, backend: str | None, axis_name: core.AxisName, axis_size: int, global_axis_size: int, devices: Sequence[Any] | None, name: str, in_axes: Sequence[int | None], out_axes_thunk: Callable[[], Sequence[int | None]], donated_invars: Sequence[bool], is_explicit_global_axis_size: bool, ) -> tuple[Callable, list[ArrayLike]]: if (config.disable_jit.value and not is_explicit_global_axis_size and not any(donated_invars)): def _emap_apply_fn(*args): return _emap_impl(fun, *args, backend=backend, axis_name=axis_name, axis_size=axis_size, global_axis_size=global_axis_size, devices=devices, name=name, in_axes=in_axes, out_axes_thunk=out_axes_thunk, donated_invars=donated_invars, is_explicit_global_axis_size=is_explicit_global_axis_size) return _emap_apply_fn, [] abstract_args = unsafe_map(core.abstractify, args) compiled_fun, fingerprint, const_args = parallel_callable( fun, backend, axis_name, axis_size, global_axis_size, devices, name, in_axes, out_axes_thunk, donated_invars, is_explicit_global_axis_size, *abstract_args) # Don't re-abstractify args unless logging is enabled for performance. if config.distributed_debug.value: distributed_debug_log(("Running pmapped function", name), ("python function", fun.f), ("devices", devices), ("abstract args", map(core.abstractify, args)), ("fingerprint", fingerprint)) return compiled_fun, const_args def xla_pmap_impl(fun: lu.WrappedFun, *args, **params): compiled_fun, const_args = xla_pmap_impl_lazy(fun, *args, **params) return compiled_fun(*const_args, *args)
WeakRefList
python
doocs__leetcode
solution/0900-0999/0921.Minimum Add to Make Parentheses Valid/Solution2.py
{ "start": 0, "end": 284 }
class ____: def minAddToMakeValid(self, s: str) -> int: ans = cnt = 0 for c in s: if c == '(': cnt += 1 elif cnt: cnt -= 1 else: ans += 1 ans += cnt return ans
Solution
python
zarr-developers__zarr-python
src/zarr/core/dtype/common.py
{ "start": 6331, "end": 6513 }
class ____: """ A mix-in class for data types with an endianness attribute """ endianness: EndiannessStr = "little" @dataclass(frozen=True, kw_only=True)
HasEndianness
python
realpython__materials
python-iterators-iterables/async_iter.py
{ "start": 44, "end": 491 }
class ____: def __init__(self, stop): self.stop = stop self.index = 0 def __aiter__(self): return self async def __anext__(self): if self.index >= self.stop: raise StopAsyncIteration await asyncio.sleep(value := randint(1, 3)) self.index += 1 return value async def main(): async for num in AsyncIterable(4): print(num) asyncio.run(main())
AsyncIterable
python
getsentry__sentry
src/bitfield/apps.py
{ "start": 36, "end": 125 }
class ____(AppConfig): name = "bitfield" verbose_name = "Bit Field"
BitFieldAppConfig
python
plotly__plotly.py
plotly/graph_objs/parcoords/line/_colorbar.py
{ "start": 233, "end": 61634 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcoords.line" _path_str = "parcoords.line.colorbar" _valid_props = { "bgcolor", "bordercolor", "borderwidth", "dtick", "exponentformat", "labelalias", "len", "lenmode", "minexponent", "nticks", "orientation", "outlinecolor", "outlinewidth", "separatethousands", "showexponent", "showticklabels", "showtickprefix", "showticksuffix", "thickness", "thicknessmode", "tick0", "tickangle", "tickcolor", "tickfont", "tickformat", "tickformatstopdefaults", "tickformatstops", "ticklabeloverflow", "ticklabelposition", "ticklabelstep", "ticklen", "tickmode", "tickprefix", "ticks", "ticksuffix", "ticktext", "ticktextsrc", "tickvals", "tickvalssrc", "tickwidth", "title", "x", "xanchor", "xpad", "xref", "y", "yanchor", "ypad", "yref", } @property def bgcolor(self): """ Sets the color of padded area. The 'bgcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["bgcolor"] @bgcolor.setter def bgcolor(self, val): self["bgcolor"] = val @property def bordercolor(self): """ Sets the axis line color. The 'bordercolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["bordercolor"] @bordercolor.setter def bordercolor(self, val): self["bordercolor"] = val @property def borderwidth(self): """ Sets the width (in px) or the border enclosing this color bar. The 'borderwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["borderwidth"] @borderwidth.setter def borderwidth(self, val): self["borderwidth"] = val @property def dtick(self): """ Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" The 'dtick' property accepts values of any type Returns ------- Any """ return self["dtick"] @dtick.setter def dtick(self, val): self["dtick"] = val @property def exponentformat(self): """ Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. The 'exponentformat' property is an enumeration that may be specified as: - One of the following enumeration values: ['none', 'e', 'E', 'power', 'SI', 'B', 'SI extended'] Returns ------- Any """ return self["exponentformat"] @exponentformat.setter def exponentformat(self, val): self["exponentformat"] = val @property def labelalias(self): """ Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html- like tags or MathJax. The 'labelalias' property accepts values of any type Returns ------- Any """ return self["labelalias"] @labelalias.setter def labelalias(self, val): self["labelalias"] = val @property def len(self): """ Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. The 'len' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["len"] @len.setter def len(self, val): self["len"] = val @property def lenmode(self): """ Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. The 'lenmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["lenmode"] @lenmode.setter def lenmode(self, val): self["lenmode"] = val @property def minexponent(self): """ Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". The 'minexponent' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["minexponent"] @minexponent.setter def minexponent(self, val): self["minexponent"] = val @property def nticks(self): """ Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". The 'nticks' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [0, 9223372036854775807] Returns ------- int """ return self["nticks"] @nticks.setter def nticks(self, val): self["nticks"] = val @property def orientation(self): """ Sets the orientation of the colorbar. The 'orientation' property is an enumeration that may be specified as: - One of the following enumeration values: ['h', 'v'] Returns ------- Any """ return self["orientation"] @orientation.setter def orientation(self, val): self["orientation"] = val @property def outlinecolor(self): """ Sets the axis line color. The 'outlinecolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["outlinecolor"] @outlinecolor.setter def outlinecolor(self, val): self["outlinecolor"] = val @property def outlinewidth(self): """ Sets the width (in px) of the axis line. The 'outlinewidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["outlinewidth"] @outlinewidth.setter def outlinewidth(self, val): self["outlinewidth"] = val @property def separatethousands(self): """ If "true", even 4-digit integers are separated The 'separatethousands' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["separatethousands"] @separatethousands.setter def separatethousands(self, val): self["separatethousands"] = val @property def showexponent(self): """ If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. The 'showexponent' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showexponent"] @showexponent.setter def showexponent(self, val): self["showexponent"] = val @property def showticklabels(self): """ Determines whether or not the tick labels are drawn. The 'showticklabels' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showticklabels"] @showticklabels.setter def showticklabels(self, val): self["showticklabels"] = val @property def showtickprefix(self): """ If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. The 'showtickprefix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showtickprefix"] @showtickprefix.setter def showtickprefix(self, val): self["showtickprefix"] = val @property def showticksuffix(self): """ Same as `showtickprefix` but for tick suffixes. The 'showticksuffix' property is an enumeration that may be specified as: - One of the following enumeration values: ['all', 'first', 'last', 'none'] Returns ------- Any """ return self["showticksuffix"] @showticksuffix.setter def showticksuffix(self, val): self["showticksuffix"] = val @property def thickness(self): """ Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. The 'thickness' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["thickness"] @thickness.setter def thickness(self, val): self["thickness"] = val @property def thicknessmode(self): """ Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. The 'thicknessmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['fraction', 'pixels'] Returns ------- Any """ return self["thicknessmode"] @thicknessmode.setter def thicknessmode(self, val): self["thicknessmode"] = val @property def tick0(self): """ Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. The 'tick0' property accepts values of any type Returns ------- Any """ return self["tick0"] @tick0.setter def tick0(self, val): self["tick0"] = val @property def tickangle(self): """ Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. The 'tickangle' property is a angle (in degrees) that may be specified as a number between -180 and 180. Numeric values outside this range are converted to the equivalent value (e.g. 270 is converted to -90). Returns ------- int|float """ return self["tickangle"] @tickangle.setter def tickangle(self, val): self["tickangle"] = val @property def tickcolor(self): """ Sets the tick color. The 'tickcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list Returns ------- str """ return self["tickcolor"] @tickcolor.setter def tickcolor(self, val): self["tickcolor"] = val @property def tickfont(self): """ Sets the color bar's tick label font The 'tickfont' property is an instance of Tickfont that may be specified as: - An instance of :class:`plotly.graph_objs.parcoords.line.colorbar.Tickfont` - A dict of string/value properties that will be passed to the Tickfont constructor Returns ------- plotly.graph_objs.parcoords.line.colorbar.Tickfont """ return self["tickfont"] @tickfont.setter def tickfont(self, val): self["tickfont"] = val @property def tickformat(self): """ Sets the tick label formatting rule using d3 formatting mini- languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" The 'tickformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickformat"] @tickformat.setter def tickformat(self, val): self["tickformat"] = val @property def tickformatstops(self): """ The 'tickformatstops' property is a tuple of instances of Tickformatstop that may be specified as: - A list or tuple of instances of plotly.graph_objs.parcoords.line.colorbar.Tickformatstop - A list or tuple of dicts of string/value properties that will be passed to the Tickformatstop constructor Returns ------- tuple[plotly.graph_objs.parcoords.line.colorbar.Tickformatstop] """ return self["tickformatstops"] @tickformatstops.setter def tickformatstops(self, val): self["tickformatstops"] = val @property def tickformatstopdefaults(self): """ When used in a template (as layout.template.data.parcoords.line .colorbar.tickformatstopdefaults), sets the default property values to use for elements of parcoords.line.colorbar.tickformatstops The 'tickformatstopdefaults' property is an instance of Tickformatstop that may be specified as: - An instance of :class:`plotly.graph_objs.parcoords.line.colorbar.Tickformatstop` - A dict of string/value properties that will be passed to the Tickformatstop constructor Returns ------- plotly.graph_objs.parcoords.line.colorbar.Tickformatstop """ return self["tickformatstopdefaults"] @tickformatstopdefaults.setter def tickformatstopdefaults(self, val): self["tickformatstopdefaults"] = val @property def ticklabeloverflow(self): """ Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. The 'ticklabeloverflow' property is an enumeration that may be specified as: - One of the following enumeration values: ['allow', 'hide past div', 'hide past domain'] Returns ------- Any """ return self["ticklabeloverflow"] @ticklabeloverflow.setter def ticklabeloverflow(self, val): self["ticklabeloverflow"] = val @property def ticklabelposition(self): """ Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". The 'ticklabelposition' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', 'outside top', 'inside top', 'outside left', 'inside left', 'outside right', 'inside right', 'outside bottom', 'inside bottom'] Returns ------- Any """ return self["ticklabelposition"] @ticklabelposition.setter def ticklabelposition(self, val): self["ticklabelposition"] = val @property def ticklabelstep(self): """ Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". The 'ticklabelstep' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["ticklabelstep"] @ticklabelstep.setter def ticklabelstep(self, val): self["ticklabelstep"] = val @property def ticklen(self): """ Sets the tick length (in px). The 'ticklen' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ticklen"] @ticklen.setter def ticklen(self, val): self["ticklen"] = val @property def tickmode(self): """ Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). The 'tickmode' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'linear', 'array'] Returns ------- Any """ return self["tickmode"] @tickmode.setter def tickmode(self, val): self["tickmode"] = val @property def tickprefix(self): """ Sets a tick label prefix. The 'tickprefix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["tickprefix"] @tickprefix.setter def tickprefix(self, val): self["tickprefix"] = val @property def ticks(self): """ Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. The 'ticks' property is an enumeration that may be specified as: - One of the following enumeration values: ['outside', 'inside', ''] Returns ------- Any """ return self["ticks"] @ticks.setter def ticks(self, val): self["ticks"] = val @property def ticksuffix(self): """ Sets a tick label suffix. The 'ticksuffix' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["ticksuffix"] @ticksuffix.setter def ticksuffix(self, val): self["ticksuffix"] = val @property def ticktext(self): """ Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. The 'ticktext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ticktext"] @ticktext.setter def ticktext(self, val): self["ticktext"] = val @property def ticktextsrc(self): """ Sets the source reference on Chart Studio Cloud for `ticktext`. The 'ticktextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ticktextsrc"] @ticktextsrc.setter def ticktextsrc(self, val): self["ticktextsrc"] = val @property def tickvals(self): """ Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. The 'tickvals' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["tickvals"] @tickvals.setter def tickvals(self, val): self["tickvals"] = val @property def tickvalssrc(self): """ Sets the source reference on Chart Studio Cloud for `tickvals`. The 'tickvalssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["tickvalssrc"] @tickvalssrc.setter def tickvalssrc(self, val): self["tickvalssrc"] = val @property def tickwidth(self): """ Sets the tick width (in px). The 'tickwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["tickwidth"] @tickwidth.setter def tickwidth(self, val): self["tickwidth"] = val @property def title(self): """ The 'title' property is an instance of Title that may be specified as: - An instance of :class:`plotly.graph_objs.parcoords.line.colorbar.Title` - A dict of string/value properties that will be passed to the Title constructor Returns ------- plotly.graph_objs.parcoords.line.colorbar.Title """ return self["title"] @title.setter def title(self, val): self["title"] = val @property def x(self): """ Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". The 'x' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val @property def xanchor(self): """ Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['left', 'center', 'right'] Returns ------- Any """ return self["xanchor"] @xanchor.setter def xanchor(self, val): self["xanchor"] = val @property def xpad(self): """ Sets the amount of padding (in px) along the x direction. The 'xpad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["xpad"] @xpad.setter def xpad(self, val): self["xpad"] = val @property def xref(self): """ Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. The 'xref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["xref"] @xref.setter def xref(self, val): self["xref"] = val @property def y(self): """ Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". The 'y' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val @property def yanchor(self): """ Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"] @yanchor.setter def yanchor(self, val): self["yanchor"] = val @property def ypad(self): """ Sets the amount of padding (in px) along the y direction. The 'ypad' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["ypad"] @ypad.setter def ypad(self, val): self["ypad"] = val @property def yref(self): """ Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. The 'yref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["yref"] @yref.setter def yref(self, val): self["yref"] = val @property def _prop_descriptions(self): return """\ bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.parcoords.line. colorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.parcoo rds.line.colorbar.tickformatstopdefaults), sets the default property values to use for elements of parcoords.line.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.parcoords.line.colorbar.Ti tle` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. """ def __init__( self, arg=None, bgcolor=None, bordercolor=None, borderwidth=None, dtick=None, exponentformat=None, labelalias=None, len=None, lenmode=None, minexponent=None, nticks=None, orientation=None, outlinecolor=None, outlinewidth=None, separatethousands=None, showexponent=None, showticklabels=None, showtickprefix=None, showticksuffix=None, thickness=None, thicknessmode=None, tick0=None, tickangle=None, tickcolor=None, tickfont=None, tickformat=None, tickformatstops=None, tickformatstopdefaults=None, ticklabeloverflow=None, ticklabelposition=None, ticklabelstep=None, ticklen=None, tickmode=None, tickprefix=None, ticks=None, ticksuffix=None, ticktext=None, ticktextsrc=None, tickvals=None, tickvalssrc=None, tickwidth=None, title=None, x=None, xanchor=None, xpad=None, xref=None, y=None, yanchor=None, ypad=None, yref=None, **kwargs, ): """ Construct a new ColorBar object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcoords.line.ColorBar` bgcolor Sets the color of padded area. bordercolor Sets the axis line color. borderwidth Sets the width (in px) or the border enclosing this color bar. dtick Sets the step in-between ticks on this axis. Use with `tick0`. Must be a positive number, or special strings available to "log" and "date" axes. If the axis `type` is "log", then ticks are set every 10^(n*dtick) where n is the tick number. For example, to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433. "log" has several special values; "L<f>", where `f` is a positive number, gives ticks linearly spaced in value (but not position). For example `tick0` = 0.1, `dtick` = "L0.5" will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small digits between, use "D1" (all digits) or "D2" (only 2 and 5). `tick0` is ignored for "D1" and "D2". If the axis `type` is "date", then you must convert the time to milliseconds. For example, to set the interval between ticks to one day, set `dtick` to 86400000.0. "date" also has special values "M<n>" gives ticks spaced by a number of months. `n` must be a positive integer. To set ticks on the 15th of every third month, set `tick0` to "2000-01-15" and `dtick` to "M3". To set ticks every 4 years, set `dtick` to "M48" exponentformat Determines a formatting rule for the tick exponents. For example, consider the number 1,000,000,000. If "none", it appears as 1,000,000,000. If "e", 1e+9. If "E", 1E+9. If "power", 1x10^9 (with 9 in a super script). If "SI", 1G. If "B", 1B. "SI" uses prefixes from "femto" f (10^-15) to "tera" T (10^12). *SI extended* covers instead the full SI range from "quecto" q (10^-30) to "quetta" Q (10^30). If "SI" or *SI extended* is used and the exponent is beyond the above ranges, the formatting rule will automatically be switched to the power notation. labelalias Replacement text for specific tick or hover labels. For example using {US: 'USA', CA: 'Canada'} changes US to USA and CA to Canada. The labels we would have shown must match the keys exactly, after adding any tickprefix or ticksuffix. For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash. That means you need to use −1 instead of -1. labelalias can be used with any axis type, and both keys (if needed) and values (if desired) can include html-like tags or MathJax. len Sets the length of the color bar This measure excludes the padding of both ends. That is, the color bar length is this length minus the padding on both ends. lenmode Determines whether this color bar's length (i.e. the measure in the color variation direction) is set in units of plot "fraction" or in *pixels. Use `len` to set the value. minexponent Hide SI prefix for 10^n if |n| is below this number. This only has an effect when `tickformat` is "SI" or "B". nticks Specifies the maximum number of ticks for the particular axis. The actual number of ticks will be chosen automatically to be less than or equal to `nticks`. Has an effect only if `tickmode` is set to "auto". orientation Sets the orientation of the colorbar. outlinecolor Sets the axis line color. outlinewidth Sets the width (in px) of the axis line. separatethousands If "true", even 4-digit integers are separated showexponent If "all", all exponents are shown besides their significands. If "first", only the exponent of the first tick is shown. If "last", only the exponent of the last tick is shown. If "none", no exponents appear. showticklabels Determines whether or not the tick labels are drawn. showtickprefix If "all", all tick labels are displayed with a prefix. If "first", only the first tick is displayed with a prefix. If "last", only the last tick is displayed with a suffix. If "none", tick prefixes are hidden. showticksuffix Same as `showtickprefix` but for tick suffixes. thickness Sets the thickness of the color bar This measure excludes the size of the padding, ticks and labels. thicknessmode Determines whether this color bar's thickness (i.e. the measure in the constant color direction) is set in units of plot "fraction" or in "pixels". Use `thickness` to set the value. tick0 Sets the placement of the first tick on this axis. Use with `dtick`. If the axis `type` is "log", then you must take the log of your starting tick (e.g. to set the starting tick to 100, set the `tick0` to 2) except when `dtick`=*L<f>* (see `dtick` for more info). If the axis `type` is "date", it should be a date string, like date data. If the axis `type` is "category", it should be a number, using the scale where each category is assigned a serial number from zero in the order it appears. tickangle Sets the angle of the tick labels with respect to the horizontal. For example, a `tickangle` of -90 draws the tick labels vertically. tickcolor Sets the tick color. tickfont Sets the color bar's tick label font tickformat Sets the tick label formatting rule using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display "09~15~23.46" tickformatstops A tuple of :class:`plotly.graph_objects.parcoords.line. colorbar.Tickformatstop` instances or dicts with compatible properties tickformatstopdefaults When used in a template (as layout.template.data.parcoo rds.line.colorbar.tickformatstopdefaults), sets the default property values to use for elements of parcoords.line.colorbar.tickformatstops ticklabeloverflow Determines how we handle tick labels that would overflow either the graph div or the domain of the axis. The default value for inside tick labels is *hide past domain*. In other cases the default is *hide past div*. ticklabelposition Determines where tick labels are drawn relative to the ticks. Left and right options are used when `orientation` is "h", top and bottom when `orientation` is "v". ticklabelstep Sets the spacing between tick labels as compared to the spacing between ticks. A value of 1 (default) means each tick gets a label. A value of 2 means shows every 2nd label. A larger value n means only every nth tick is labeled. `tick0` determines which labels are shown. Not implemented for axes with `type` "log" or "multicategory", or when `tickmode` is "array". ticklen Sets the tick length (in px). tickmode Sets the tick mode for this axis. If "auto", the number of ticks is set via `nticks`. If "linear", the placement of the ticks is determined by a starting position `tick0` and a tick step `dtick` ("linear" is the default value if `tick0` and `dtick` are provided). If "array", the placement of the ticks is set via `tickvals` and the tick text is `ticktext`. ("array" is the default value if `tickvals` is provided). tickprefix Sets a tick label prefix. ticks Determines whether ticks are drawn or not. If "", this axis' ticks are not drawn. If "outside" ("inside"), this axis' are drawn outside (inside) the axis lines. ticksuffix Sets a tick label suffix. ticktext Sets the text displayed at the ticks position via `tickvals`. Only has an effect if `tickmode` is set to "array". Used with `tickvals`. ticktextsrc Sets the source reference on Chart Studio Cloud for `ticktext`. tickvals Sets the values at which ticks on this axis appear. Only has an effect if `tickmode` is set to "array". Used with `ticktext`. tickvalssrc Sets the source reference on Chart Studio Cloud for `tickvals`. tickwidth Sets the tick width (in px). title :class:`plotly.graph_objects.parcoords.line.colorbar.Ti tle` instance or dict with compatible properties x Sets the x position with respect to `xref` of the color bar (in plot fraction). When `xref` is "paper", defaults to 1.02 when `orientation` is "v" and 0.5 when `orientation` is "h". When `xref` is "container", defaults to 1 when `orientation` is "v" and 0.5 when `orientation` is "h". Must be between 0 and 1 if `xref` is "container" and between "-2" and 3 if `xref` is "paper". xanchor Sets this color bar's horizontal position anchor. This anchor binds the `x` position to the "left", "center" or "right" of the color bar. Defaults to "left" when `orientation` is "v" and "center" when `orientation` is "h". xpad Sets the amount of padding (in px) along the x direction. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` of the color bar (in plot fraction). When `yref` is "paper", defaults to 0.5 when `orientation` is "v" and 1.02 when `orientation` is "h". When `yref` is "container", defaults to 0.5 when `orientation` is "v" and 1 when `orientation` is "h". Must be between 0 and 1 if `yref` is "container" and between "-2" and 3 if `yref` is "paper". yanchor Sets this color bar's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the color bar. Defaults to "middle" when `orientation` is "v" and "bottom" when `orientation` is "h". ypad Sets the amount of padding (in px) along the y direction. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. Returns ------- ColorBar """ super().__init__("colorbar") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.parcoords.line.ColorBar constructor must be a dict or an instance of :class:`plotly.graph_objs.parcoords.line.ColorBar`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("bgcolor", arg, bgcolor) self._set_property("bordercolor", arg, bordercolor) self._set_property("borderwidth", arg, borderwidth) self._set_property("dtick", arg, dtick) self._set_property("exponentformat", arg, exponentformat) self._set_property("labelalias", arg, labelalias) self._set_property("len", arg, len) self._set_property("lenmode", arg, lenmode) self._set_property("minexponent", arg, minexponent) self._set_property("nticks", arg, nticks) self._set_property("orientation", arg, orientation) self._set_property("outlinecolor", arg, outlinecolor) self._set_property("outlinewidth", arg, outlinewidth) self._set_property("separatethousands", arg, separatethousands) self._set_property("showexponent", arg, showexponent) self._set_property("showticklabels", arg, showticklabels) self._set_property("showtickprefix", arg, showtickprefix) self._set_property("showticksuffix", arg, showticksuffix) self._set_property("thickness", arg, thickness) self._set_property("thicknessmode", arg, thicknessmode) self._set_property("tick0", arg, tick0) self._set_property("tickangle", arg, tickangle) self._set_property("tickcolor", arg, tickcolor) self._set_property("tickfont", arg, tickfont) self._set_property("tickformat", arg, tickformat) self._set_property("tickformatstops", arg, tickformatstops) self._set_property("tickformatstopdefaults", arg, tickformatstopdefaults) self._set_property("ticklabeloverflow", arg, ticklabeloverflow) self._set_property("ticklabelposition", arg, ticklabelposition) self._set_property("ticklabelstep", arg, ticklabelstep) self._set_property("ticklen", arg, ticklen) self._set_property("tickmode", arg, tickmode) self._set_property("tickprefix", arg, tickprefix) self._set_property("ticks", arg, ticks) self._set_property("ticksuffix", arg, ticksuffix) self._set_property("ticktext", arg, ticktext) self._set_property("ticktextsrc", arg, ticktextsrc) self._set_property("tickvals", arg, tickvals) self._set_property("tickvalssrc", arg, tickvalssrc) self._set_property("tickwidth", arg, tickwidth) self._set_property("title", arg, title) self._set_property("x", arg, x) self._set_property("xanchor", arg, xanchor) self._set_property("xpad", arg, xpad) self._set_property("xref", arg, xref) self._set_property("y", arg, y) self._set_property("yanchor", arg, yanchor) self._set_property("ypad", arg, ypad) self._set_property("yref", arg, yref) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
ColorBar
python
getsentry__sentry
src/sentry/api/endpoints/organization_sdk_deprecations.py
{ "start": 1087, "end": 4159 }
class ____(OrganizationEndpoint): owner = ApiOwner.PROFILING publish_status = { "GET": ApiPublishStatus.PRIVATE, } def get(self, request: Request, organization: Organization) -> Response: serializer = SDKDeprecationsSerializer(data=request.GET) if not serializer.is_valid(): return Response(serializer.errors, status=400) projects = self.get_projects(request, organization) event_types = get_event_types(serializer.data["event_type"]) project_sdks = ProjectSDK.objects.filter( project__in=projects, event_type__in=[event_type.value for event_type in event_types], ) sdk_deprecations_by_project: DefaultDict[Project, list[SDKDeprecation]] = defaultdict(list) projects_with_up_to_date_sdk: set[Project] = set() for project_sdk in project_sdks: deprecation = get_deprecation_status(project_sdk) if deprecation is None: projects_with_up_to_date_sdk.add(project_sdk.project) else: sdk_deprecations_by_project[project_sdk.project].append(deprecation) deprecations: list[SDKDeprecation] = [] for project, sdk_deprecations in sdk_deprecations_by_project.items(): if project in projects_with_up_to_date_sdk: # It's possible that a single project contains data from different SDKs. # Here we just want 1 up to date SDK sending data to this project. # # If we require all SDKs sending data to this project to be up to date, # we risk checking against SDKs that may no longer be sending data. # We would have to track a last seen timestamp to be more sure which # is an expensive operation that we're not doing right now. continue deprecations.extend(sdk_deprecations) result: SDKDeprecationsResult = {"data": deprecations} return Response(result, status=200) def get_event_types(raw_event_type: str) -> list[EventType]: if raw_event_type == "profile": return [EventType.PROFILE_CHUNK] raise ValueError(f"Unknown event type: {raw_event_type}") def get_deprecation_status(project_sdk: ProjectSDK) -> SDKDeprecation | None: try: sdk_version = parse_version(project_sdk.sdk_version) except InvalidVersion as e: sentry_sdk.capture_exception(e) return None minimum_sdk_version = get_minimum_sdk_version( project_sdk.event_type, project_sdk.sdk_name, hard_limit=False, ) # no minimum sdk version was specified if minimum_sdk_version is None: return None # satisfies the minimum sdk version if sdk_version >= minimum_sdk_version: return None return { "projectId": str(project_sdk.project_id), "minimumVersion": str(minimum_sdk_version), "sdkName": project_sdk.sdk_name, "sdkVersion": str(sdk_version), }
OrganizationSdkDeprecationsEndpoint
python
apache__airflow
providers/openlineage/src/airflow/providers/openlineage/plugins/adapter.py
{ "start": 2561, "end": 23065 }
class ____(LoggingMixin): """Translate Airflow metadata to OpenLineage events instead of creating them from Airflow code.""" def __init__(self, client: OpenLineageClient | None = None, secrets_masker: SecretsMasker | None = None): super().__init__() self._client = client if not secrets_masker: secrets_masker = _secrets_masker() self._redacter = OpenLineageRedactor.from_masker(secrets_masker) def get_or_create_openlineage_client(self) -> OpenLineageClient: if not self._client: # If not already set explicitly - propagate airflow logging level to OpenLineage client airflow_core_log_level = airflow_conf.get("logging", "logging_level", fallback="INFO") if not os.getenv("OPENLINEAGE_CLIENT_LOGGING") and airflow_core_log_level != "INFO": os.environ["OPENLINEAGE_CLIENT_LOGGING"] = airflow_core_log_level config = self.get_openlineage_config() if config: self.log.debug( "OpenLineage configuration found. Transport type: `%s`", config.get("transport", {}).get("type", "no type provided"), ) self._client = OpenLineageClient(config=config) else: self.log.debug( "OpenLineage configuration not found directly in Airflow. " "Looking for legacy environment configuration. " ) self._client = OpenLineageClient() return self._client def get_openlineage_config(self) -> dict | None: # First, try to read from YAML file openlineage_config_path = conf.config_path(check_legacy_env_var=False) if openlineage_config_path: config = self._read_yaml_config(openlineage_config_path) return config self.log.debug("OpenLineage config_path configuration not found.") # Second, try to get transport config transport_config = conf.transport() if not transport_config: self.log.debug("OpenLineage transport configuration not found.") return None return {"transport": transport_config} @staticmethod def _read_yaml_config(path: str) -> dict | None: with open(path) as config_file: return yaml.safe_load(config_file) @staticmethod def build_dag_run_id(dag_id: str, logical_date: datetime, clear_number: int) -> str: return str( generate_static_uuid( instant=logical_date, data=f"{conf.namespace()}.{dag_id}.{clear_number}".encode(), ) ) @staticmethod def build_task_instance_run_id( dag_id: str, task_id: str, try_number: int, logical_date: datetime, map_index: int, ): return str( generate_static_uuid( instant=logical_date, data=f"{conf.namespace()}.{dag_id}.{task_id}.{try_number}.{map_index}".encode(), ) ) def emit(self, event: RunEvent): """ Emit OpenLineage event. :param event: Event to be emitted. :return: Redacted Event. """ if not self._client: self._client = self.get_or_create_openlineage_client() redacted_event: RunEvent = self._redacter.redact(event, max_depth=20) # type: ignore[assignment] event_type = event.eventType.value.lower() if event.eventType else "" transport_type = f"{self._client.transport.kind}".lower() try: with ExitStack() as stack: stack.enter_context(Stats.timer(f"ol.emit.attempts.{event_type}.{transport_type}")) stack.enter_context(Stats.timer("ol.emit.attempts")) self._client.emit(redacted_event) self.log.info( "Successfully emitted OpenLineage `%s` event of id `%s`", event_type.upper(), event.run.runId, ) except Exception as e: Stats.incr("ol.emit.failed") self.log.warning( "Failed to emit OpenLineage `%s` event of id `%s` with the following exception: `%s`", event_type.upper(), event.run.runId, e, ) self.log.debug("OpenLineage emission failure details:", exc_info=True) return redacted_event def start_task( self, run_id: str, job_name: str, event_time: str, job_description: str | None, nominal_start_time: str | None, nominal_end_time: str | None, owners: list[str] | None, tags: list[str] | None, task: OperatorLineage | None, job_description_type: str | None = None, run_facets: dict[str, RunFacet] | None = None, ) -> RunEvent: """ Emit openlineage event of type START. :param run_id: globally unique identifier of task in dag run :param job_name: globally unique identifier of task in dag :param job_description: description of the job :param job_description_type: MIME type of the description arg content :param event_time: :param nominal_start_time: scheduled time of dag run :param nominal_end_time: following schedule of dag run :param owners: list of owners :param tags: list of tags :param task: metadata container with information extracted from operator :param run_facets: custom run facets """ run_facets = run_facets or {} if task: run_facets = {**task.run_facets, **run_facets} event = RunEvent( eventType=RunState.START, eventTime=event_time, run=self._build_run( run_id=run_id, nominal_start_time=nominal_start_time, nominal_end_time=nominal_end_time, run_facets=run_facets, ), job=self._build_job( job_name=job_name, job_type=_JOB_TYPE_TASK, job_description=job_description, job_description_type=job_description_type, job_owners=owners, job_tags=tags, job_facets=task.job_facets if task else None, ), inputs=task.inputs if task else [], outputs=task.outputs if task else [], producer=_PRODUCER, ) return self.emit(event) def complete_task( self, run_id: str, job_name: str, end_time: str, task: OperatorLineage, nominal_start_time: str | None, nominal_end_time: str | None, owners: list[str] | None, tags: list[str] | None, job_description: str | None, job_description_type: str | None = None, run_facets: dict[str, RunFacet] | None = None, ) -> RunEvent: """ Emit openlineage event of type COMPLETE. :param run_id: globally unique identifier of task in dag run :param job_name: globally unique identifier of task between dags :param end_time: time of task completion :param job_description: description of the job :param job_description_type: MIME type of the description arg content :param tags: list of tags :param nominal_start_time: scheduled time of dag run :param nominal_end_time: following schedule of dag run :param task: metadata container with information extracted from operator :param owners: list of owners :param run_facets: additional run facets """ run_facets = run_facets or {} if task: run_facets = {**task.run_facets, **run_facets} event = RunEvent( eventType=RunState.COMPLETE, eventTime=end_time, run=self._build_run( run_id=run_id, nominal_start_time=nominal_start_time, nominal_end_time=nominal_end_time, run_facets=run_facets, ), job=self._build_job( job_name, job_type=_JOB_TYPE_TASK, job_facets=task.job_facets, job_owners=owners, job_tags=tags, job_description=job_description, job_description_type=job_description_type, ), inputs=task.inputs, outputs=task.outputs, producer=_PRODUCER, ) return self.emit(event) def fail_task( self, run_id: str, job_name: str, end_time: str, task: OperatorLineage, nominal_start_time: str | None, nominal_end_time: str | None, owners: list[str] | None, tags: list[str] | None, job_description: str | None, job_description_type: str | None = None, error: str | BaseException | None = None, run_facets: dict[str, RunFacet] | None = None, ) -> RunEvent: """ Emit openlineage event of type FAIL. :param run_id: globally unique identifier of task in dag run :param job_name: globally unique identifier of task between dags :param end_time: time of task completion :param task: metadata container with information extracted from operator :param job_description: description of the job :param job_description_type: MIME type of the description arg content :param run_facets: custom run facets :param tags: list of tags :param nominal_start_time: scheduled time of dag run :param nominal_end_time: following schedule of dag run :param owners: list of owners :param error: error :param run_facets: additional run facets """ run_facets = run_facets or {} if task: run_facets = {**task.run_facets, **run_facets} if error: stack_trace = None if isinstance(error, BaseException) and error.__traceback__: import traceback stack_trace = "".join(traceback.format_exception(type(error), error, error.__traceback__)) run_facets["errorMessage"] = error_message_run.ErrorMessageRunFacet( message=str(error), programmingLanguage="python", stackTrace=stack_trace ) event = RunEvent( eventType=RunState.FAIL, eventTime=end_time, run=self._build_run( run_id=run_id, nominal_start_time=nominal_start_time, nominal_end_time=nominal_end_time, run_facets=run_facets, ), job=self._build_job( job_name, job_type=_JOB_TYPE_TASK, job_facets=task.job_facets, job_owners=owners, job_tags=tags, job_description=job_description, job_description_type=job_description_type, ), inputs=task.inputs, outputs=task.outputs, producer=_PRODUCER, ) return self.emit(event) def dag_started( self, dag_id: str, logical_date: datetime, start_date: datetime, nominal_start_time: str | None, nominal_end_time: str | None, owners: list[str] | None, tags: list[str], run_facets: dict[str, RunFacet], clear_number: int, job_description: str | None, job_description_type: str | None = None, job_facets: dict[str, JobFacet] | None = None, # Custom job facets ): try: event = RunEvent( eventType=RunState.START, eventTime=start_date.isoformat(), job=self._build_job( job_name=dag_id, job_type=_JOB_TYPE_DAG, job_description=job_description, job_description_type=job_description_type, job_owners=owners, job_facets=job_facets, job_tags=tags, ), run=self._build_run( run_id=self.build_dag_run_id( dag_id=dag_id, logical_date=logical_date, clear_number=clear_number ), nominal_start_time=nominal_start_time, nominal_end_time=nominal_end_time, run_facets={**run_facets, **get_airflow_debug_facet()}, ), inputs=[], outputs=[], producer=_PRODUCER, ) self.emit(event) except BaseException: # Catch all exceptions to prevent ProcessPoolExecutor from silently swallowing them. # This ensures that any unexpected exceptions are logged for debugging purposes. # This part cannot be wrapped to deduplicate code, otherwise the method cannot be pickled in multiprocessing. self.log.warning("Failed to emit OpenLineage DAG started event: \n %s", traceback.format_exc()) def dag_success( self, dag_id: str, run_id: str, end_date: datetime, logical_date: datetime, nominal_start_time: str | None, nominal_end_time: str | None, tags: list[str] | None, clear_number: int, dag_run_state: DagRunState, task_ids: list[str], owners: list[str] | None, run_facets: dict[str, RunFacet], job_description: str | None, job_description_type: str | None = None, ): try: event = RunEvent( eventType=RunState.COMPLETE, eventTime=end_date.isoformat(), job=self._build_job( job_name=dag_id, job_type=_JOB_TYPE_DAG, job_owners=owners, job_tags=tags, job_description=job_description, job_description_type=job_description_type, ), run=self._build_run( run_id=self.build_dag_run_id( dag_id=dag_id, logical_date=logical_date, clear_number=clear_number ), nominal_start_time=nominal_start_time, nominal_end_time=nominal_end_time, run_facets={ **get_airflow_state_run_facet(dag_id, run_id, task_ids, dag_run_state), **get_airflow_debug_facet(), **run_facets, }, ), inputs=[], outputs=[], producer=_PRODUCER, ) self.emit(event) except BaseException: # Catch all exceptions to prevent ProcessPoolExecutor from silently swallowing them. # This ensures that any unexpected exceptions are logged for debugging purposes. # This part cannot be wrapped to deduplicate code, otherwise the method cannot be pickled in multiprocessing. self.log.warning("Failed to emit OpenLineage DAG success event: \n %s", traceback.format_exc()) def dag_failed( self, dag_id: str, run_id: str, end_date: datetime, logical_date: datetime, nominal_start_time: str | None, nominal_end_time: str | None, tags: list[str] | None, clear_number: int, dag_run_state: DagRunState, task_ids: list[str], owners: list[str] | None, msg: str, run_facets: dict[str, RunFacet], job_description: str | None, job_description_type: str | None = None, ): try: event = RunEvent( eventType=RunState.FAIL, eventTime=end_date.isoformat(), job=self._build_job( job_name=dag_id, job_type=_JOB_TYPE_DAG, job_owners=owners, job_tags=tags, job_description=job_description, job_description_type=job_description_type, ), run=self._build_run( run_id=self.build_dag_run_id( dag_id=dag_id, logical_date=logical_date, clear_number=clear_number ), nominal_start_time=nominal_start_time, nominal_end_time=nominal_end_time, run_facets={ "errorMessage": error_message_run.ErrorMessageRunFacet( message=msg, programmingLanguage="python" ), **get_airflow_state_run_facet(dag_id, run_id, task_ids, dag_run_state), **get_airflow_debug_facet(), **run_facets, }, ), inputs=[], outputs=[], producer=_PRODUCER, ) self.emit(event) except BaseException: # Catch all exceptions to prevent ProcessPoolExecutor from silently swallowing them. # This ensures that any unexpected exceptions are logged for debugging purposes. # This part cannot be wrapped to deduplicate code, otherwise the method cannot be pickled in multiprocessing. self.log.warning("Failed to emit OpenLineage DAG failed event: \n %s", traceback.format_exc()) @staticmethod def _build_run( run_id: str, nominal_start_time: str | None = None, nominal_end_time: str | None = None, run_facets: dict[str, RunFacet] | None = None, ) -> Run: facets: dict[str, RunFacet] = {} if run_facets: facets.update(run_facets) if nominal_start_time: facets.update( { "nominalTime": nominal_time_run.NominalTimeRunFacet( nominalStartTime=nominal_start_time, nominalEndTime=nominal_end_time, producer=_PRODUCER, ) } ) facets.update(get_processing_engine_facet()) return Run(run_id, facets) @staticmethod def _build_job( job_name: str, job_type: Literal["DAG", "TASK"], job_description: str | None = None, job_description_type: str | None = None, job_owners: list[str] | None = None, job_tags: list[str] | None = None, job_facets: dict[str, JobFacet] | None = None, ): facets: dict[str, JobFacet] = {} if job_facets: facets.update(job_facets) if job_description: facets.update( { "documentation": documentation_job.DocumentationJobFacet( description=job_description, contentType=job_description_type, producer=_PRODUCER ) } ) if job_owners: facets.update( { "ownership": ownership_job.OwnershipJobFacet( owners=[ownership_job.Owner(name=owner) for owner in sorted(job_owners)], producer=_PRODUCER, ) } ) if job_tags: facets.update( { "tags": tags_job.TagsJobFacet( tags=[ tags_job.TagsJobFacetFields( key=tag, value=tag, source="AIRFLOW", ) for tag in sorted(job_tags) ], producer=_PRODUCER, ) } ) facets.update( { "jobType": job_type_job.JobTypeJobFacet( jobType=job_type, integration="AIRFLOW", processingType="BATCH", producer=_PRODUCER ) } ) return Job(namespace=conf.namespace(), name=job_name, facets=facets)
OpenLineageAdapter
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 34975, "end": 35563 }
class ____(TestCase): def test_empty(self): it = [] actual = list(mi.transpose(it)) expected = [] self.assertEqual(actual, expected) def test_basic(self): it = [(10, 11, 12), (20, 21, 22), (30, 31, 32)] actual = list(mi.transpose(it)) expected = [(10, 20, 30), (11, 21, 31), (12, 22, 32)] self.assertEqual(actual, expected) def test_incompatible_error(self): it = [(10, 11, 12, 13), (20, 21, 22), (30, 31, 32)] with self.assertRaises(ValueError): list(mi.transpose(it))
TransposeTests
python
spack__spack
lib/spack/spack/vendor/jinja2/nodes.py
{ "start": 27223, "end": 27975 }
class ____(Expr): """Compares an expression with some other expressions. `ops` must be a list of :class:`Operand`\\s. """ fields = ("expr", "ops") expr: Expr ops: t.List["Operand"] def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any: eval_ctx = get_eval_context(self, eval_ctx) result = value = self.expr.as_const(eval_ctx) try: for op in self.ops: new_value = op.expr.as_const(eval_ctx) result = _cmpop_to_func[op.op](value, new_value) if not result: return False value = new_value except Exception as e: raise Impossible() from e return result
Compare
python
viewflow__viewflow
tests/fsm/test_fsm__model.py
{ "start": 131, "end": 236 }
class ____(models.Model): text = models.TextField() stage = models.CharField(max_length=150)
Report
python
PyCQA__pyflakes
pyflakes/checker.py
{ "start": 12020, "end": 12325 }
class ____(ImportationFrom): """ A binding created by a from `__future__` import statement. `__future__` imports are implicitly used. """ def __init__(self, name, source, scope): super().__init__(name, source, '__future__') self.used = (scope, source)
FutureImportation
python
Netflix__metaflow
test/core/tests/basic_foreach.py
{ "start": 67, "end": 1100 }
class ____(MetaflowTest): PRIORITY = 0 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] @steps(0, ["foreach-split"], required=True) def split(self): self.my_index = None self.arr = range(32) @steps(0, ["foreach-inner"], required=True) def inner(self): # index must stay constant over multiple steps inside foreach if self.my_index is None: self.my_index = self.index assert_equals(self.my_index, self.index) assert_equals(self.input, self.arr[self.index]) self.my_input = self.input @steps(0, ["foreach-join"], required=True) def join(self, inputs): got = sorted([inp.my_input for inp in inputs]) assert_equals(list(range(32)), got) @steps(1, ["all"]) def step_all(self): pass
BasicForeachTest
python
openai__openai-python
src/openai/types/fine_tuning/reinforcement_method.py
{ "start": 708, "end": 958 }
class ____(BaseModel): grader: Grader """The grader used for the fine-tuning job.""" hyperparameters: Optional[ReinforcementHyperparameters] = None """The hyperparameters used for the reinforcement fine-tuning job."""
ReinforcementMethod
python
python-poetry__poetry
src/poetry/console/commands/debug/resolve.py
{ "start": 467, "end": 4700 }
class ____(InitCommand): name = "debug resolve" description = "Debugs dependency resolution." arguments: ClassVar[list[Argument]] = [ argument("package", "The packages to resolve.", optional=True, multiple=True) ] options: ClassVar[list[Option]] = [ option( "extras", "E", "Extras to activate for the dependency.", flag=False, multiple=True, ), option("python", None, "Python version(s) to use for resolution.", flag=False), option("tree", None, "Display the dependency tree."), option("install", None, "Show what would be installed for the current system."), ] loggers: ClassVar[list[str]] = [ "poetry.repositories.pypi_repository", "poetry.inspection.info", ] def handle(self) -> int: from cleo.io.null_io import NullIO from poetry.core.packages.project_package import ProjectPackage from poetry.factory import Factory from poetry.puzzle.solver import Solver from poetry.repositories.repository import Repository from poetry.repositories.repository_pool import RepositoryPool from poetry.utils.env import EnvManager packages = self.argument("package") if not packages: package = self.poetry.package else: # Using current pool for determine_requirements() self._pool = self.poetry.pool package = ProjectPackage( self.poetry.package.name, self.poetry.package.version ) # Silencing output verbosity = self.io.output.verbosity self.io.output.set_verbosity(Verbosity.QUIET) requirements = self._determine_requirements(packages) self.io.output.set_verbosity(verbosity) for constraint in requirements: name = constraint.pop("name") assert isinstance(name, str) extras = [] for extra in self.option("extras"): extras += extra.split() constraint["extras"] = extras package.add_dependency(Factory.create_dependency(name, constraint)) package.python_versions = self.option("python") or ( self.poetry.package.python_versions ) pool = self.poetry.pool solver = Solver(package, pool, [], [], self.io) ops = solver.solve().calculate_operations() self.line("") self.line("Resolution results:") self.line("") if self.option("tree"): show_command = self.get_application().find("show") assert isinstance(show_command, ShowCommand) show_command.init_styles(self.io) packages = [op.package for op in ops] requires = package.all_requires for pkg in packages: for require in requires: if pkg.name == require.name: show_command.display_package_tree(self.io, pkg, packages) break return 0 table = self.table(style="compact") table.style.set_vertical_border_chars("", " ") rows: Rows = [] if self.option("install"): env = EnvManager(self.poetry).get() pool = RepositoryPool(config=self.poetry.config) locked_repository = Repository("poetry-locked") for op in ops: locked_repository.add_package(op.package) pool.add_repository(locked_repository) solver = Solver(package, pool, [], [], NullIO()) with solver.use_environment(env): ops = solver.solve().calculate_operations() for op in ops: if self.option("install") and op.skipped: continue pkg = op.package row = [ f"<c1>{pkg.complete_name}</c1>", f"<b>{pkg.version}</b>", ] if not pkg.marker.is_any(): row[2] = str(pkg.marker) rows.append(row) table.set_rows(rows) table.render() return 0
DebugResolveCommand
python
pytest-dev__pytest
src/_pytest/raises.py
{ "start": 58024, "end": 58101 }
class ____: """Singleton for unchecked values in ResultHolder"""
NotChecked
python
Lightning-AI__lightning
src/lightning/fabric/utilities/throughput.py
{ "start": 12091, "end": 27249 }
class ____(Throughput): r"""Computes throughput. This class will automatically keep a count of the number of log calls (``step``). But that can be modified as desired. For manual logging, using :class:`Throughput` directly might be desired. Example:: logger = ... fabric = Fabric(logger=logger) throughput = ThroughputMonitor(fabric) t0 = time() for i in range(1, 100): do_work() if torch.cuda.is_available(): torch.cuda.synchronize() # required or else time() won't be correct throughput.update(time=time() - t0, batches=i, samples=i) if i % 10 == 0: throughput.compute_and_log(step=i) Args: fabric: The Fabric object. \**kwargs: See available parameters in :class:`Throughput` """ def __init__(self, fabric: "Fabric", **kwargs: Any) -> None: fabric._validate_launched() # otherwise world_size might be incorrect dtype = _plugin_to_compute_dtype(fabric.strategy.precision) available_flops = get_available_flops(fabric.device, dtype) super().__init__(available_flops=available_flops, world_size=fabric.world_size, **kwargs) self._fabric = fabric self.step = -1 self.update = rank_zero_only(self.update) # type: ignore[method-assign] self.compute = rank_zero_only(self.compute, default={}) # type: ignore[method-assign] self.compute_and_log = rank_zero_only(self.compute_and_log, default={}) # type: ignore[method-assign] self.reset = rank_zero_only(self.reset) # type: ignore[method-assign] def compute_and_log(self, step: Optional[int] = None, **kwargs: Any) -> _THROUGHPUT_METRICS: r"""See :meth:`Throughput.compute` Args: step: Can be used to override the logging step. \**kwargs: See available parameters in :meth:`Throughput.compute` """ self.step = (self.step + 1) if step is None else step metrics = self.compute(**kwargs) self._fabric.log_dict(metrics=metrics, step=self.step) return metrics def measure_flops( model: torch.nn.Module, forward_fn: Callable[[], torch.Tensor], loss_fn: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, ) -> int: """Utility to compute the total number of FLOPs used by a module during training or during inference. It's recommended to create a meta-device model for this: Example:: with torch.device("meta"): model = MyModel() x = torch.randn(2, 32) model_fwd = lambda: model(x) fwd_flops = measure_flops(model, model_fwd) model_loss = lambda y: y.sum() fwd_and_bwd_flops = measure_flops(model, model_fwd, model_loss) Args: model: The model whose FLOPs should be measured. forward_fn: A function that runs ``forward`` on the model and returns the result. loss_fn: A function that computes the loss given the ``forward_fn`` output. If provided, the loss and `backward` FLOPs will be included in the result. """ from torch.utils.flop_counter import FlopCounterMode flop_counter = FlopCounterMode(display=False) with flop_counter: if loss_fn is None: forward_fn() else: loss_fn(forward_fn()).backward() return flop_counter.get_total_flops() _CUDA_FLOPS: dict[str, dict[Union[str, torch.dtype], float]] = { # Hopper # source: https://nvdam.widen.net/s/nb5zzzsjdf/hpc-datasheet-sc23-h200-datasheet-3002446 "h200 sxm1": { torch.float64: 3.4e13, torch.float32: 6.7e13, "tfloat32": 9.9e14, torch.bfloat16: 2.0e15, torch.float16: 2.0e15, torch.int8: 4.0e15, }, "h200 nvl1": { torch.float64: 3.0e13, torch.float32: 6.0e13, "tfloat32": 8.4e14, torch.bfloat16: 1.7e15, torch.float16: 1.7e15, torch.int8: 3.3e15, }, # source: https://resources.nvidia.com/en-us-tensor-core "h100 nvl": { torch.float64: 67e12, torch.float32: 133.8e12, "tfloat32": 989.4e12, torch.bfloat16: 1978.8e12, torch.float16: 1978.8e12, torch.int8: 3957.8e12, }, "h100 sxm": { torch.float64: 33.5e12, torch.float32: 66.9e12, "tfloat32": 494.7e12, torch.bfloat16: 989.4e12, torch.float16: 989.4e12, torch.int8: 1978.9e12, }, "h100 pcie": { torch.float64: 25.6e12, torch.float32: 51.2e12, "tfloat32": 378e12, torch.bfloat16: 756e12, torch.float16: 756e12, torch.int8: 1513e12, }, # Ada # source: https://images.nvidia.com/aem-dam/Solutions/Data-Center/l4/nvidia-ada-gpu-architecture-whitepaper-v2.1.pdf "rtx 4090": { torch.float32: 82.6e12, "tfloat32": 82.6e12, torch.bfloat16: 82.6e12, torch.float16: 82.6e12, torch.int8: 660.6e12, "int4": 1321.2e12, }, "rtx 4080": { torch.float32: 48.7e12, "tfloat32": 48.7e12, torch.bfloat16: 48.7e12, torch.float16: 48.7e12, torch.int8: 389.9e12, "int4": 779.8e12, }, "rtx 4080 super": { torch.float32: 52.2e12, "tfloat32": 52.2e12, torch.bfloat16: 52.2e12, torch.float16: 52.2e12, torch.int8: 417.6e12, "int4": 835.2e12, }, "l4": { torch.float32: 30.3e12, "tfloat32": 60e12, torch.bfloat16: 121e12, torch.float16: 121e12, torch.int8: 242e12, "int4": 484e12, }, "l40": { torch.float32: 90.5e12, "tfloat32": 90.5e12, torch.bfloat16: 181e12, torch.float16: 181e12, torch.int8: 362e12, "int4": 724e12, }, # Ampere # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf # sxm and pcie have same flop counts "a100": { torch.float64: 9.7e12, torch.float32: 19.5e12, "tfloat32": 156e12, torch.bfloat16: 312e12, torch.float16: 312e12, torch.int8: 624e12, }, "a6000": { torch.float32: 38.7e12, "tfloat32": 77.4e12, torch.bfloat16: 38.7e12, torch.float16: 38.7e12, torch.int8: 309.7e12, "int4": 619.3e12, }, "a40": { torch.float32: 37.4e12, "tfloat32": 74.8e12, torch.bfloat16: 37.4e12, torch.float16: 37.4e12, torch.int8: 299.3e12, "int4": 598.7e12, }, # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a10/pdf/a10-datasheet.pdf "a10g": { torch.float32: 31.2e12, "tfloat32": 62.5e12, torch.bfloat16: 125e12, torch.float16: 125e12, torch.int8: 250e12, "int4": 500e12, }, "rtx 3090 ti": { torch.float32: 40e12, "tfloat32": 40e12, torch.bfloat16: 40e12, torch.float16: 40e12, torch.int8: 320e12, "int4": 640e12, }, "rtx 3090": { torch.float32: 35.6e12, "tfloat32": 35.6e12, torch.bfloat16: 35.6e12, torch.float16: 35.6e12, torch.int8: 284e12, "int4": 568e12, }, "rtx 3080 ti": { torch.float32: 34.1e12, "tfloat32": 34.1e12, torch.bfloat16: 34.1e12, torch.float16: 34.1e12, torch.int8: 272.8e12, "int4": 546.6e12, }, "rtx 3080": { torch.float32: 29.8e12, "tfloat32": 29.8e12, torch.bfloat16: 29.8e12, torch.float16: 29.8e12, torch.int8: 238e12, "int4": 476e12, }, "rtx 3070": { torch.float32: 20.3e12, "tfloat32": 20.3e12, torch.bfloat16: 20.3e12, torch.float16: 20.3e12, torch.int8: 162.6e12, "int4": 325.2e12, }, # Turing # source: https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/tesla-t4/t4-tensor-core-datasheet-951643.pdf # sxm and pcie have same flop counts "t4": { torch.float32: 8.1e12, torch.float16: 65e12, torch.int8: 130e12, "int4": 260e12, }, # https://www.nvidia.com/content/dam/en-zz/Solutions/design-visualization/quadro-product-literature/quadro-rtx-5000-data-sheet-us-nvidia-704120-r4-web.pdf "quadro rtx 5000": { torch.float32: 11.2e12, torch.float16: 89.2e12, }, "rtx 2080 super": { torch.float32: 11.2e12, torch.float16: 22.3e12, torch.int8: 178.4e12, "int4": 356.8e12, }, "rtx 2080 ti": { torch.float32: 14.2e12, torch.float16: 28.5e12, torch.int8: 227.7e12, "int4": 455.4e12, }, "rtx 2080": { torch.float32: 10.6e12, torch.float16: 21.2e12, torch.int8: 169.6e12, "int4": 339.1e12, }, # https://www.nvidia.com/content/PDF/nvidia-ampere-ga-102-gpu-architecture-whitepaper-v2.pdf "rtx 2070 super": { torch.float32: 9.1e12, torch.float16: 18.1e12, torch.int8: 145e12, "int4": 290e12, }, "titan rtx": { torch.float32: 16.3e12, torch.float16: 32.6e12, torch.int8: 261e12, "int4": 522e12, }, # Volta # source: https://images.nvidia.com/content/technologies/volta/pdf/volta-v100-datasheet-update-us-1165301-r5.pdf "v100 sxm": { torch.float64: 7.8e12, torch.float32: 15.7e12, torch.float16: 125e12, }, "v100 pcie": { torch.float64: 7e12, torch.float32: 14e12, torch.float16: 112e12, }, "v100s pcie": { torch.float64: 8.2e12, torch.float32: 16.4e12, torch.float16: 130e12, }, } _TPU_FLOPS = { # flop count for each TPU generation is the same for all precisions # since bfloat16 precision is always used for performing matrix operations # for more info: https://cloud.google.com/tpu/docs/bfloat16#choosing_bfloat16 # source: https://arxiv.org/pdf/1907.10701.pdf "v2": 45e12, # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v3 "v3": 123e12, # source: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm#tpu_v4 "v4": 275e12, # source: https://cloud.google.com/tpu/docs/v5e-training "v5litepod": 197e12, } def get_available_flops(device: torch.device, dtype: Union[torch.dtype, str]) -> Optional[int]: """Returns the available theoretical FLOPs. This is an optimistic upper limit that could only be achievable if only thick matmuls were run in a benchmark environment. """ if device.type == "cuda": device_name = torch.cuda.get_device_name(device) chip = device_name.lower() if "h200" in chip: if "sxm1" in chip: chip = "h200 sxm1" elif "nvl1" in chip: chip = "h200 nvl1" elif "h100" in chip: if "hbm3" in chip: chip = "h100 sxm" elif "nvl" in chip: chip = "h100 nvl" elif "pcie" in chip or "hbm2e" in chip: chip = "h100 pcie" elif "l4" in chip: chip = "l40" if "tesla" in chip else "l4" elif "geforce rtx" in chip: number = chip.split(" ")[3] extra = "" if "super" in chip: extra = " super" elif "ti" in chip: extra = " ti" chip = f"rtx {number}{extra}" elif "a6000" in chip: chip = "a6000" elif "a100" in chip: chip = "a100" elif "a40" in chip: chip = "a40" elif "a10g" in chip: chip = "a10g" elif "t4" in chip: chip = "t4" elif "quadro rtx 5000" in chip: chip = "quadro rtx 5000" elif "titan rtx" in chip: chip = "titan rtx" elif "v100-sxm" in chip: chip = "v100 sxm" elif "v100-pcie" in chip: chip = "v100 pcie" elif "v100s-pcie" in chip: chip = "v100s pcie" else: # the flops list is not exhaustive, return with a warning rank_zero_warn(f"FLOPs not found for {device_name!r}") return None if chip not in _CUDA_FLOPS: # parsing is implemented but we don't have the stats rank_zero_warn(f"FLOPs not found for {device_name!r}, chip is {chip!r}") return None dtype_to_flops = _CUDA_FLOPS[chip] if dtype is torch.float32: from lightning.fabric.accelerators.cuda import _is_ampere_or_later if _is_ampere_or_later() and torch.get_float32_matmul_precision() != "highest": dtype = "tfloat32" if dtype not in dtype_to_flops: # for example, T4 doesn't support bfloat16. it might also be that we are missing this dtype from the list rank_zero_warn(f"{device_name!r} does not support {dtype}") return None return int(dtype_to_flops[dtype]) if device.type == "xla": from lightning.fabric.accelerators.xla import _XLA_GREATER_EQUAL_2_1 if _XLA_GREATER_EQUAL_2_1: from torch_xla._internal import tpu else: from torch_xla.experimental import tpu tpu_env = tpu.get_tpu_env() # not all TPU generations define the "TYPE" envar. example: TYPE="V4", ACCELERATOR_TYPE="v4-8" device_name = tpu_env.get("TYPE") or tpu_env["ACCELERATOR_TYPE"].split("-")[0] chip = device_name.lower() assert isinstance(device_name, str) if chip not in _TPU_FLOPS: rank_zero_warn(f"FLOPs not found for TPU {device_name!r} with {dtype}") return None return int(_TPU_FLOPS[chip]) def _plugin_to_compute_dtype(plugin: "Precision") -> torch.dtype: # TODO: integrate this into the precision plugins from lightning.fabric.plugins import ( BitsandbytesPrecision, DeepSpeedPrecision, DoublePrecision, FSDPPrecision, HalfPrecision, MixedPrecision, Precision, TransformerEnginePrecision, XLAPrecision, ) if not isinstance(plugin, Precision): raise RuntimeError(f"Expected a precision plugin, got {plugin}") if isinstance(plugin, BitsandbytesPrecision): return plugin.dtype if isinstance(plugin, (HalfPrecision, MixedPrecision)): return plugin._desired_input_dtype if isinstance(plugin, DoublePrecision): return torch.double if isinstance(plugin, (XLAPrecision, DeepSpeedPrecision)): return plugin._desired_dtype if isinstance(plugin, TransformerEnginePrecision): return torch.int8 if isinstance(plugin, FSDPPrecision): return plugin.mixed_precision_config.reduce_dtype or torch.float32 if isinstance(plugin, Precision): return torch.float32 raise NotImplementedError(plugin) T = TypeVar("T", bound=float)
ThroughputMonitor
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 562157, "end": 562518 }
class ____(sgqlc.types.Type): """Autogenerated return type of DeleteTeamDiscussionComment""" __schema__ = github_schema __field_names__ = ("client_mutation_id",) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
DeleteTeamDiscussionCommentPayload
python
apache__airflow
scripts/ci/prek/significant_newsfragments_checker.py
{ "start": 1591, "end": 9428 }
class ____(docutils.nodes.NodeVisitor): """Visitor to collect significant newsfragement content.""" TYPES_OF_CHANGE_TITLE = "Types of change" EXPECTED_TYPE_OF_CHANGES = { "Dag changes", "Config changes", "API changes", "CLI changes", "Behaviour changes", "Plugin changes", "Dependency changes", "Code interface changes", } MIGRATION_RULE_TITLE = "Migration rules needed" CONFIG_RULE_TITLE = "airflow config lint" RUFF_RULE_TITLE = "ruff" def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.types_of_change: dict[str, bool] = {} self.ruff_rules: dict[str, list[tuple[bool, str]]] = {} self.config_rules: list[tuple[bool, str]] = [] def visit_list_item(self, node: docutils.nodes.list_item) -> None: list_title = node[0].astext() for title, extract_func in ( (self.TYPES_OF_CHANGE_TITLE, self._extract_type_of_changes), (self.MIGRATION_RULE_TITLE, self._extract_migration_rules), ): if list_title == title: list_content = node[1] if not isinstance(list_content, docutils.nodes.bullet_list): raise ValueError(f"Incorrect format {list_content.astext()}") extract_func(list_content) break def _extract_type_of_changes(self, node: docutils.nodes.bullet_list) -> None: for change in node: checked, change_type = self._extract_check_list_item(change) self.types_of_change[change_type] = checked change_types = set(self.types_of_change.keys()) missing_keys = self.EXPECTED_TYPE_OF_CHANGES - change_types if missing_keys: raise ValueError(f"Missing type of changes: {missing_keys}") unexpected_keys = change_types - self.EXPECTED_TYPE_OF_CHANGES if unexpected_keys: raise ValueError(f"Unexpected type of changes: {unexpected_keys}") def _extract_migration_rules(self, node: docutils.nodes.bullet_list) -> None: for sub_node in node: if not isinstance(sub_node, docutils.nodes.list_item): raise ValueError(f"Incorrect format {sub_node.astext()}") list_title = sub_node[0].astext() list_content = sub_node[1] if list_title == self.CONFIG_RULE_TITLE: if not isinstance(list_content, docutils.nodes.bullet_list): raise ValueError(f"Incorrect format {list_content.astext()}") self.config_rules = [self._extract_check_list_item(item) for item in list_content] elif list_title == self.RUFF_RULE_TITLE: if not isinstance(list_content, docutils.nodes.bullet_list): raise ValueError("Incorrect format") self._extract_ruff_rules(list_content) def _extract_ruff_rules(self, node: docutils.nodes.bullet_list) -> None: for ruff_node in node: if not isinstance(ruff_node, docutils.nodes.list_item): raise ValueError(f"Incorrect format {ruff_node.astext()}") ruff_rule_id = ruff_node[0].astext() rules_node = ruff_node[1] if not isinstance(rules_node, docutils.nodes.bullet_list): raise ValueError(f"Incorrect format {rules_node.astext()}") self.ruff_rules[ruff_rule_id] = [self._extract_check_list_item(rule) for rule in rules_node] def unknown_visit(self, node: docutils.nodes.Node) -> None: """Handle other nodes.""" @staticmethod def _extract_check_list_item(node: docutils.nodes.Node) -> tuple[bool, str]: if not isinstance(node, docutils.nodes.list_item): raise ValueError(f"Incorrect format {node.astext()}") text = node.astext() if text[0] != "[" or text[2] != "]": raise ValueError( f"{text} should be a checklist (e.g., * [ ] ``logging.dag_processor_manager_log_location``)" ) return text[:3] == "[x]", text[4:] @property def formatted_ruff_rules(self) -> str: str_repr = "" for rule_id, rules in self.ruff_rules.items(): str_repr += f"**{rule_id}**\n" + "\n".join(f"* {content}" for _, content in rules) return str_repr @property def formatted_config_rules(self) -> str: return "\n".join(f"* {content}" for _, content in self.config_rules) @property def undone_ruff_rules(self) -> dict[str, list[str]]: undone_ruff_rules = {} for rule_id, rules in self.ruff_rules.items(): undone_rules = [rule for checked, rule in rules if checked is False] if undone_rules: undone_ruff_rules[rule_id] = undone_rules return undone_ruff_rules @property def undone_config_rules(self) -> list[str]: return [rule[1] for rule in self.config_rules if rule[0] is False] @property def has_undone_rules(self) -> bool: return bool(self.undone_ruff_rules) or bool(self.undone_config_rules) def parse_significant_newsfragment(source: str) -> SignificantNewsFragmentVisitor: document = publish_doctree(source) visitor = SignificantNewsFragmentVisitor(document) document.walk(visitor) return visitor def parse_newsfragment_file(filename: str, *, export: bool, list_todo: bool) -> None: content = newsfragment_file.read() description = content.split("* Types of change")[0] title = description.split("\n")[0] visitor = parse_significant_newsfragment(content) if not len(visitor.types_of_change): raise ValueError("Missing type of changes") if export: newsfragment_details.append( { "AIP or PR name": aip_pr_name, "Title": title, "Description": description, } | visitor.types_of_change | { "Ruff rules": visitor.formatted_ruff_rules, "Config rules": visitor.formatted_config_rules, } ) if list_todo and visitor.has_undone_rules: jinja_loader = Environment(loader=BaseLoader(), autoescape=True) undone_msg = jinja_loader.from_string(UNDONE_LIST_TEMPLATE).render( filename=filename, undone_ruff_rules=visitor.undone_ruff_rules, undone_config_rules=visitor.undone_config_rules, ) print(undone_msg) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Summarize Significant Newsfragments") parser.add_argument("--list-todo", help="List undone migration rules", action="store_true") parser.add_argument("--export", help="Export the summarization to provided output path in csv format") args = parser.parse_args() newsfragment_details: list[dict] = [] for filename in glob.glob("airflow-core/newsfragments/*.significant.rst"): if filename == "airflow-core/newsfragments/template.significant.rst": continue match = re.search(r"airflow-core/newsfragments/(.*)\.significant\.rst", filename) if not match: raise ValueError() aip_pr_name = match.group(1) with open(filename) as newsfragment_file: try: parse_newsfragment_file(filename, export=args.export, list_todo=args.list_todo) except ValueError as e: print(f'Error found in "{filename}"') raise e if args.export: with open(args.export, "w") as summary_file: writer = csv.DictWriter(summary_file, fieldnames=newsfragment_details[0].keys()) writer.writeheader() writer.writerows(newsfragment_details)
SignificantNewsFragmentVisitor
python
gevent__gevent
src/gevent/testing/flaky.py
{ "start": 1247, "end": 1455 }
class ____(AssertionError): "Re-raised so that we know it's a known-flaky test." # The next exceptions allow us to raise them in a highly # greppable way so that we can debug them later.
FlakyAssertionError
python
facelessuser__soupsieve
tests/test_level4/test_dir.py
{ "start": 77, "end": 5331 }
class ____(util.TestCase): """Test direction selectors.""" MARKUP = """ <html id="0"> <head></head> <body> <div id="1" dir="rtl"> <span id="2">test1</span> <div id="3" dir="ltr">test2 <div id="4" dir="auto"><!-- comment -->עִבְרִית<span id="5" dir="auto">()</span></div> <div id="6" dir="auto"><script></script><b> </b><span id="7"><!-- comment -->עִבְרִית</span></div> <span id="8" dir="auto">test3</span> </div> <input id="9" type="tel" value="333-444-5555" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"> <input id="10" type="tel" dir="auto" value="333-444-5555" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"> <input id="11" type="email" dir="auto" value="test@mail.com"> <input id="12" type="search" dir="auto" value="()"> <input id="13" type="url" dir="auto" value="https://test.com"> <input id="14" type="search" dir="auto" value="עִבְרִית"> <input id="15" type="search" dir="auto" value=""> <input id="16" type="search" dir="auto"> <textarea id="17" dir="auto">עִבְרִית</textarea> <textarea id="18" dir="auto"></textarea> </div> </body> </html> """ def test_dir_rtl(self): """Test general direction right to left.""" self.assert_selector( self.MARKUP, "div:dir(rtl)", ["1", "4", "6"], flags=util.HTML ) def test_dir_ltr(self): """Test general direction left to right.""" self.assert_selector( self.MARKUP, "div:dir(ltr)", ["3"], flags=util.HTML ) def test_dir_conflict(self): """Test conflicting direction.""" self.assert_selector( self.MARKUP, "div:dir(ltr):dir(rtl)", [], flags=util.HTML ) def test_dir_xml(self): """Test direction with XML (not supported).""" self.assert_selector( self.MARKUP, "div:dir(ltr)", [], flags=util.XML ) def test_dir_bidi_detect(self): """Test bidirectional detection.""" self.assert_selector( self.MARKUP, "span:dir(rtl)", ['2', '5', '7'], flags=util.HTML ) self.assert_selector( self.MARKUP, "span:dir(ltr)", ['8'], flags=util.HTML ) def test_dir_on_input(self): """Test input direction rules.""" self.assert_selector( self.MARKUP, ":is(input, textarea):dir(ltr)", ['9', '10', '11', '12', '13'], flags=util.HTML5 ) def test_dir_on_root(self): """Test that the root is assumed left to right if not explicitly defined.""" self.assert_selector( self.MARKUP, "html:dir(ltr)", ['0'], flags=util.HTML ) def test_dir_auto_root(self): """Test that the root is assumed left to right if auto used.""" markup = """ <html id="0" dir="auto"> <head></head> <body> </body> </html> """ self.assert_selector( markup, "html:dir(ltr)", ['0'], flags=util.HTML ) def test_dir_on_input_root(self): """Test input direction when input is the root.""" markup = """<input id="1" type="text" dir="auto">""" # Input is root for parser in util.available_parsers('html.parser', 'lxml', 'html5lib'): soup = self.soup(markup, parser) fragment = soup.input.extract() self.assertTrue(sv.match(":root:dir(ltr)", fragment, flags=sv.DEBUG)) def test_iframe(self): """Test direction in `iframe`.""" markup = """ <html> <head></head> <body> <div id="1" dir="auto"> <iframe> <html> <body> <div id="2" dir="auto"> <!-- comment -->עִבְרִית <span id="5" dir="auto">()</span></div> </div> </body> </html> </iframe> </body> </html> """ self.assert_selector( markup, "div:dir(ltr)", ['1'], flags=util.PYHTML ) self.assert_selector( markup, "div:dir(rtl)", ['2'], flags=util.PYHTML ) def test_xml_in_html(self): """Test cases for when we have XML in HTML.""" markup = """ <html> <head></head> <body> <div id="1" dir="auto"> <math> <!-- comment -->עִבְרִית </math> other text </div> </body> </html> """ self.assert_selector( markup, "div:dir(ltr)", ['1'], flags=util.HTML5 ) self.assert_selector( markup, "div:dir(rtl)", [], flags=util.HTML5 ) self.assert_selector( markup, "math:dir(rtl)", [], flags=util.HTML5 )
TestDir
python
tensorflow__tensorflow
tensorflow/python/util/deprecation_test.py
{ "start": 3254, "end": 17448 }
class ____(test.TestCase): @test.mock.patch.object(logging, "warning", autospec=True) def test_deprecated_once(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions, warn_once=True) def _fn(): pass _fn() self.assertEqual(1, mock_warning.call_count) _fn() self.assertEqual(1, mock_warning.call_count) @test.mock.patch.object(logging, "warning", autospec=True) def test_deprecated_init_class(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions, warn_once=True) class MyClass(): """A test class.""" def __init__(self, a): pass MyClass("") self.assertEqual(1, mock_warning.call_count) MyClass("") self.assertEqual(1, mock_warning.call_count) self.assertIn("IS DEPRECATED", MyClass.__doc__) @test.mock.patch.object(logging, "warning", autospec=True) def test_deprecated_new_class(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions, warn_once=True) class MyStr(str): def __new__(cls, value): return str.__new__(cls, value) MyStr("abc") self.assertEqual(1, mock_warning.call_count) MyStr("abc") self.assertEqual(1, mock_warning.call_count) self.assertIn("IS DEPRECATED", MyStr.__doc__) @test.mock.patch.object(logging, "warning", autospec=True) def test_deprecated_enum(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions, warn_once=True) class MyEnum(enum.Enum): a = 1 b = 2 self.assertIs(MyEnum(1), MyEnum.a) self.assertEqual(1, mock_warning.call_count) self.assertIs(MyEnum(2), MyEnum.b) self.assertEqual(1, mock_warning.call_count) self.assertIn("IS DEPRECATED", MyEnum.__doc__) @test.mock.patch.object(logging, "warning", autospec=True) def test_deprecated_namedtuple(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." mytuple = deprecation.deprecated( date, instructions, warn_once=True)( collections.namedtuple("my_tuple", ["field1", "field2"])) mytuple(1, 2) self.assertEqual(1, mock_warning.call_count) mytuple(3, 4) self.assertEqual(1, mock_warning.call_count) self.assertIn("IS DEPRECATED", mytuple.__doc__) @test.mock.patch.object(logging, "warning", autospec=True) def test_silence(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions, warn_once=False) def _fn(): pass _fn() self.assertEqual(1, mock_warning.call_count) with deprecation.silence(): _fn() self.assertEqual(1, mock_warning.call_count) _fn() self.assertEqual(2, mock_warning.call_count) def test_strict_mode_deprecation(self): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions, warn_once=True) def _fn(): pass strict_mode.enable_strict_mode() with self.assertRaises(RuntimeError): _fn() def _assert_subset(self, expected_subset, actual_set): self.assertTrue( actual_set.issuperset(expected_subset), msg="%s is not a superset of %s." % (actual_set, expected_subset)) def test_deprecated_illegal_args(self): instructions = "This is how you update..." with self.assertRaisesRegex(ValueError, "YYYY-MM-DD"): deprecation.deprecated("", instructions) with self.assertRaisesRegex(ValueError, "YYYY-MM-DD"): deprecation.deprecated("07-04-2016", instructions) date = "2016-07-04" with self.assertRaisesRegex(ValueError, "instructions"): deprecation.deprecated(date, None) with self.assertRaisesRegex(ValueError, "instructions"): deprecation.deprecated(date, "") @test.mock.patch.object(logging, "warning", autospec=True) def test_no_date(self, mock_warning): date = None instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. Returns: Sum of args. """ return arg0 + arg1 self.assertEqual( "fn doc. (deprecated)" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. " "It will be removed in a future version." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n" "\nReturns:" "\n Sum of args." % instructions, _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["in a future version", instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) @test_util.run_deprecated_v1 def test_static_fn_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. Returns: Sum of args. """ return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated)" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n" "\nReturns:" "\n Sum of args." % (date, instructions), _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) @test_util.run_deprecated_v1 def test_static_fn_with_one_line_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): """fn doc.""" return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "fn doc. (deprecated)" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) @test_util.run_deprecated_v1 def test_static_fn_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." @deprecation.deprecated(date, instructions) def _fn(arg0, arg1): return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual("_fn", _fn.__name__) self.assertEqual( "DEPRECATED FUNCTION" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), _fn.__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_instance_fn_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @deprecation.deprecated(date, instructions) def _fn(self, arg0, arg1): """fn doc. Args: arg0: Arg 0. arg1: Arg 1. Returns: Sum of args. """ return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual( "fn doc. (deprecated)" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" "\n" "\nArgs:" "\n arg0: Arg 0." "\n arg1: Arg 1." "\n" "\nReturns:" "\n Sum of args." % (date, instructions), getattr(_Object, "_fn").__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _Object()._fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_instance_fn_with_one_line_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @deprecation.deprecated(date, instructions) def _fn(self, arg0, arg1): """fn doc.""" return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual( "fn doc. (deprecated)" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:\n%s" % (date, instructions), getattr(_Object, "_fn").__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _Object()._fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_instance_fn_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @deprecation.deprecated(date, instructions) def _fn(self, arg0, arg1): return arg0 + arg1 # Assert function docs are properly updated. self.assertEqual( "DEPRECATED FUNCTION" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), getattr(_Object, "_fn").__doc__) # Assert calling new fn issues log warning. self.assertEqual(3, _Object()._fn(1, 2)) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) def test_prop_wrong_order(self): with self.assertRaisesRegex( ValueError, "make sure @property appears before @deprecated in your source code"): # pylint: disable=unused-variable class _Object(object): def __init(self): pass @deprecation.deprecated("2016-07-04", "Instructions.") @property def _prop(self): return "prop_wrong_order" @test.mock.patch.object(logging, "warning", autospec=True) def test_prop_with_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @property @deprecation.deprecated(date, instructions) def _prop(self): """prop doc. Returns: String. """ return "prop_with_doc" # Assert function docs are properly updated. self.assertEqual( "prop doc. (deprecated)" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" "\n" "\nReturns:" "\n String." % (date, instructions), getattr(_Object, "_prop").__doc__) # Assert calling new fn issues log warning. self.assertEqual("prop_with_doc", _Object()._prop) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:])) @test.mock.patch.object(logging, "warning", autospec=True) def test_prop_no_doc(self, mock_warning): date = "2016-07-04" instructions = "This is how you update..." class _Object(object): def __init(self): pass @property @deprecation.deprecated(date, instructions) def _prop(self): return "prop_no_doc" # Assert function docs are properly updated. self.assertEqual( "DEPRECATED FUNCTION" "\n" "\nDeprecated: THIS FUNCTION IS DEPRECATED. It will be removed after %s." "\nInstructions for updating:" "\n%s" % (date, instructions), getattr(_Object, "_prop").__doc__) # Assert calling new fn issues log warning. self.assertEqual("prop_no_doc", _Object()._prop) self.assertEqual(1, mock_warning.call_count) (args, _) = mock_warning.call_args self.assertRegex(args[0], r"deprecated and will be removed") self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
DeprecationTest
python
econchick__interrogate
tests/functional/sample/partial.py
{ "start": 108, "end": 1533 }
class ____: """Foo class""" def __init__(self): """init method of Foo class""" self.foo = None def __str__(self): """a documented magic method.""" pass def __repr__(self): pass def _semiprivate_documented(self): """a documented semipriate method""" pass def _semiprivate_undocumented(self): pass def __private(self): pass def method_foo(self): pass def get(self): pass async def get(self): pass @property def a_prop(self): pass @a_prop.setter def a_prop(self, x): pass @a_prop.deleter def a_prop(self): """A documented del property decorator""" @typing.overload def module_overload(a: None) -> None: ... @typing.overload def module_overload(a: int) -> int: ... def module_overload(a): """overloaded method implementation""" pass @overload def simple_overload(a: None) -> None: ... @overload def simple_overload(a: int) -> int: ... def simple_overload(a): """overloaded method implementation""" pass def documented_top_level_func(): """A documented top level function""" def documented_inner_func(): """A documented inner function""" pass def undocumented_top_level_func(): def undocumented_inner_func(): pass
Foo
python
SmileyChris__easy-thumbnails
easy_thumbnails/options.py
{ "start": 44, "end": 1648 }
class ____(dict): def __init__(self, *args, **kwargs): self._prepared_options = None super().__init__(*args, **kwargs) if settings.THUMBNAIL_DEFAULT_OPTIONS: for key, value in settings.THUMBNAIL_DEFAULT_OPTIONS.items(): self.setdefault(key, value) self.setdefault('quality', settings.THUMBNAIL_QUALITY) self.setdefault('subsampling', 2) def prepared_options(self): prepared_opts = ['{size[0]}x{size[1]}'.format(**self)] opts_text = '' if 'quality' in self: opts_text += 'q{quality}'.format(**self) if 'subsampling' in self and str(self['subsampling']) != '2': opts_text += 'ss{subsampling}'.format(**self) prepared_opts.append(opts_text) for key, value in sorted(self.items()): if key == key.upper(): # Uppercase options aren't used by prepared options (a primary # use of prepared options is to generate the filename -- these # options don't alter the filename). continue if not value or key in ['size', 'quality', 'subsampling']: continue if value is True: prepared_opts.append(key) continue if not isinstance(value, str): try: value = ','.join([str(item) for item in value]) except TypeError: value = str(value) prepared_opts.append('{0}-{1}'.format(key, value)) return prepared_opts
ThumbnailOptions
python
cython__cython
Cython/Plex/Regexps.py
{ "start": 10606, "end": 14669 }
class ____(RE): """ SwitchCase(re, nocase) is an RE which matches the same strings as RE, but treating upper and lower case letters according to |nocase|. If |nocase| is true, case is ignored, otherwise it is not. """ re = None nocase = None def __init__(self, re, nocase): self.re = re self.nocase = nocase self.nullable = re.nullable self.match_nl = re.match_nl def build_machine(self, m, initial_state, final_state, match_bol, nocase): self.re.build_machine(m, initial_state, final_state, match_bol, self.nocase) def calc_str(self): if self.nocase: name = "NoCase" else: name = "Case" return "%s(%s)" % (name, self.re) # # Composite RE constructors # ------------------------- # # These REs are defined in terms of the primitive REs. # Empty = Seq() Empty.__doc__ = \ """ Empty is an RE which matches the empty string. """ Empty.str = "Empty" def Str1(s): """ Str1(s) is an RE which matches the literal string |s|. """ result = Seq(*tuple(map(Char, s))) result.str = "Str(%s)" % repr(s) return result def Str(*strs): """ Str(s) is an RE which matches the literal string |s|. Str(s1, s2, s3, ...) is an RE which matches any of |s1| or |s2| or |s3|... """ if len(strs) == 1: return Str1(strs[0]) else: result = Alt(*tuple(map(Str1, strs))) result.str = "Str(%s)" % ','.join(map(repr, strs)) return result def Any(s): """ Any(s) is an RE which matches any character in the string |s|. """ result = CodeRanges(chars_to_ranges(s)) result.str = "Any(%s)" % repr(s) return result def AnyBut(s): """ AnyBut(s) is an RE which matches any character (including newline) which is not in the string |s|. """ ranges = chars_to_ranges(s) ranges.insert(0, -maxint) ranges.append(maxint) result = CodeRanges(ranges) result.str = "AnyBut(%s)" % repr(s) return result AnyChar = AnyBut("") AnyChar.__doc__ = \ """ AnyChar is an RE which matches any single character (including a newline). """ AnyChar.str = "AnyChar" def Range(s1, s2=None): """ Range(c1, c2) is an RE which matches any single character in the range |c1| to |c2| inclusive. Range(s) where |s| is a string of even length is an RE which matches any single character in the ranges |s[0]| to |s[1]|, |s[2]| to |s[3]|,... """ if s2: result = CodeRange(ord(s1), ord(s2) + 1) result.str = "Range(%s,%s)" % (s1, s2) else: ranges = [] for i in range(0, len(s1), 2): ranges.append(CodeRange(ord(s1[i]), ord(s1[i + 1]) + 1)) result = Alt(*ranges) result.str = "Range(%s)" % repr(s1) return result def Opt(re): """ Opt(re) is an RE which matches either |re| or the empty string. """ result = Alt(re, Empty) result.str = "Opt(%s)" % re return result def Rep(re): """ Rep(re) is an RE which matches zero or more repetitions of |re|. """ result = Opt(Rep1(re)) result.str = "Rep(%s)" % re return result def NoCase(re): """ NoCase(re) is an RE which matches the same strings as RE, but treating upper and lower case letters as equivalent. """ return SwitchCase(re, nocase=1) def Case(re): """ Case(re) is an RE which matches the same strings as RE, but treating upper and lower case letters as distinct, i.e. it cancels the effect of any enclosing NoCase(). """ return SwitchCase(re, nocase=0) # # RE Constants # Bol = Char(BOL) Bol.__doc__ = \ """ Bol is an RE which matches the beginning of a line. """ Bol.str = "Bol" Eol = Char(EOL) Eol.__doc__ = \ """ Eol is an RE which matches the end of a line. """ Eol.str = "Eol" Eof = Char(EOF) Eof.__doc__ = \ """ Eof is an RE which matches the end of the file. """ Eof.str = "Eof"
SwitchCase
python
django__django
tests/user_commands/tests.py
{ "start": 18180, "end": 20672 }
class ____(AdminScriptTestCase): """ Tests that need to run by simulating the command line, not by call_command. """ def test_script_prefix_set_in_commands(self): self.write_settings( "settings.py", apps=["user_commands"], sdict={ "ROOT_URLCONF": '"user_commands.urls"', "FORCE_SCRIPT_NAME": '"/PREFIX/"', }, ) out, err = self.run_manage(["reverse_url"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "/PREFIX/some/url/") def test_disallowed_abbreviated_options(self): """ To avoid conflicts with custom options, commands don't allow abbreviated forms of the --setting and --pythonpath options. """ self.write_settings("settings.py", apps=["user_commands"]) out, err = self.run_manage(["set_option", "--set", "foo"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "Set foo") def test_skip_checks(self): self.write_settings( "settings.py", apps=["django.contrib.staticfiles", "user_commands"], sdict={ # (staticfiles.E001) The STATICFILES_DIRS setting is not a # tuple or list. "STATICFILES_DIRS": '"foo"', }, ) out, err = self.run_manage(["set_option", "--skip-checks", "--set", "foo"]) self.assertNoOutput(err) self.assertEqual(out.strip(), "Set foo") def test_subparser_error_formatting(self): self.write_settings("settings.py", apps=["user_commands"]) out, err = self.run_manage(["subparser", "foo", "twelve"]) self.maxDiff = None self.assertNoOutput(out) err_lines = err.splitlines() self.assertEqual(len(err_lines), 2) self.assertEqual( err_lines[1], "manage.py subparser foo: error: argument bar: invalid int value: 'twelve'", ) def test_subparser_non_django_error_formatting(self): self.write_settings("settings.py", apps=["user_commands"]) out, err = self.run_manage(["subparser_vanilla", "foo", "seven"]) self.assertNoOutput(out) err_lines = err.splitlines() self.assertEqual(len(err_lines), 2) self.assertEqual( err_lines[1], "manage.py subparser_vanilla foo: error: argument bar: invalid int value: " "'seven'", )
CommandRunTests
python
plotly__plotly.py
plotly/graph_objs/_deprecations.py
{ "start": 18432, "end": 19267 }
class ____(dict): """ plotly.graph_objs.YBins is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.histogram.YBins - plotly.graph_objs.histogram2d.YBins """ def __init__(self, *args, **kwargs): """ plotly.graph_objs.YBins is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.histogram.YBins - plotly.graph_objs.histogram2d.YBins """ warnings.warn( """plotly.graph_objs.YBins is deprecated. Please replace it with one of the following more specific types - plotly.graph_objs.histogram.YBins - plotly.graph_objs.histogram2d.YBins """, DeprecationWarning, ) super().__init__(*args, **kwargs)
YBins
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/matrix_inverse_op_test.py
{ "start": 1327, "end": 6295 }
class ____(test.TestCase): def _high_precision_matmul(self, a, b, adjoint_b): """Do a higher-precision matmul, casting either to float32 or float64.""" if a.dtype == dtypes.float16: a = math_ops.cast(a, dtypes.float32) b = math_ops.cast(b, dtypes.float32) ret = test_util.matmul_without_tf32(a, b, adjoint_b=adjoint_b) return math_ops.cast(ret, a.dtype) def _verifyInverse(self, x, np_type): for adjoint in False, True: y = x.astype(np_type) with self.cached_session(use_gpu=test_util.is_gpu_available()): # Verify that x^{-1} * x == Identity matrix. inv = linalg_ops.matrix_inverse(y, adjoint=adjoint) tf_ans = self._high_precision_matmul(inv, y, adjoint_b=adjoint) np_ans = np.identity(y.shape[-1]).astype(np_type) if x.ndim > 2: tiling = list(y.shape) tiling[-2:] = [1, 1] np_ans = np.tile(np_ans, tiling) out = self.evaluate(tf_ans) self.assertAllCloseAccordingToType( np_ans, out, atol=0.001, half_atol=0.1) self.assertShapeEqual(y, tf_ans) def _verifyInverseReal(self, x): for np_type in [np.float16, np.float32, np.float64]: self._verifyInverse(x, np_type) def _verifyInverseComplex(self, x): for np_type in [np.complex64, np.complex128]: self._verifyInverse(x, np_type) def _makeBatch(self, matrix1, matrix2): matrix_batch = np.concatenate( [np.expand_dims(matrix1, 0), np.expand_dims(matrix2, 0)]) matrix_batch = np.tile(matrix_batch, [2, 3, 1, 1]) return matrix_batch def testNonsymmetric(self): # 2x2 matrices matrix1 = np.array([[1., 2.], [3., 4.]]) matrix2 = np.array([[1., 3.], [3., 5.]]) self._verifyInverseReal(matrix1) self._verifyInverseReal(matrix2) # A multidimensional batch of 2x2 matrices self._verifyInverseReal(self._makeBatch(matrix1, matrix2)) matrix1 = matrix1.astype(np.complex64) matrix1 += 1j * matrix1 matrix2 = matrix2.astype(np.complex64) matrix2 += 1j * matrix2 self._verifyInverseComplex(matrix1) self._verifyInverseComplex(matrix2) # Complex batch self._verifyInverseComplex(self._makeBatch(matrix1, matrix2)) def testSymmetricPositiveDefinite(self): # 2x2 matrices matrix1 = np.array([[2., 1.], [1., 2.]]) matrix2 = np.array([[3., -1.], [-1., 3.]]) self._verifyInverseReal(matrix1) self._verifyInverseReal(matrix2) # A multidimensional batch of 2x2 matrices self._verifyInverseReal(self._makeBatch(matrix1, matrix2)) matrix1 = matrix1.astype(np.complex64) matrix1 += 1j * matrix1 matrix2 = matrix2.astype(np.complex64) matrix2 += 1j * matrix2 self._verifyInverseComplex(matrix1) self._verifyInverseComplex(matrix2) # Complex batch self._verifyInverseComplex(self._makeBatch(matrix1, matrix2)) @test_util.deprecated_graph_mode_only def testNonSquareMatrix(self): # When the inverse of a non-square matrix is attempted we should return # an error with self.assertRaises(ValueError): linalg_ops.matrix_inverse(np.array([[1., 2., 3.], [3., 4., 5.]])) @test_util.deprecated_graph_mode_only def testWrongDimensions(self): # The input to the inverse should be at least a 2-dimensional tensor. tensor3 = constant_op.constant([1., 2.]) with self.assertRaises(ValueError): linalg_ops.matrix_inverse(tensor3) def testNotInvertible(self): # The input should be invertible. with self.cached_session(): with self.assertRaisesOpError("Input is not invertible."): # All rows of the matrix below add to zero. tensor3 = constant_op.constant([[1., 0., -1.], [-1., 1., 0.], [0., -1., 1.]]) linalg_ops.matrix_inverse(tensor3).eval() def testEmpty(self): self._verifyInverseReal(np.empty([0, 2, 2])) self._verifyInverseReal(np.empty([2, 0, 0])) def testRandomSmallAndLarge(self): np.random.seed(42) for dtype in np.float32, np.float64, np.complex64, np.complex128: for batch_dims in [(), (1,), (3,), (2, 2)]: for size in 8, 31, 32: shape = batch_dims + (size, size) matrix = np.random.uniform( low=-1.0, high=1.0, size=np.prod(shape)).reshape(shape).astype(dtype) self._verifyInverseReal(matrix) @test_util.deprecated_graph_mode_only def testConcurrentExecutesWithoutError(self): with self.session() as sess: all_ops = [] for adjoint_ in True, False: matrix1 = random_ops.random_normal([5, 5], seed=42) matrix2 = random_ops.random_normal([5, 5], seed=42) inv1 = linalg_ops.matrix_inverse(matrix1, adjoint=adjoint_) inv2 = linalg_ops.matrix_inverse(matrix2, adjoint=adjoint_) all_ops += [inv1, inv2] inv = self.evaluate(all_ops) self.assertAllEqual(inv[0], inv[1]) self.assertAllEqual(inv[2], inv[3])
InverseOpTest
python
davidhalter__jedi
jedi/api/__init__.py
{ "start": 1967, "end": 28824 }
class ____: """ A Script is the base for completions, goto or whatever you want to do with Jedi. The counter part of this class is :class:`Interpreter`, which works with actual dictionaries and can work with a REPL. This class should be used when a user edits code in an editor. You can either use the ``code`` parameter or ``path`` to read a file. Usually you're going to want to use both of them (in an editor). The Script's ``sys.path`` is very customizable: - If `project` is provided with a ``sys_path``, that is going to be used. - If `environment` is provided, its ``sys.path`` will be used (see :func:`Environment.get_sys_path <jedi.api.environment.Environment.get_sys_path>`); - Otherwise ``sys.path`` will match that of the default environment of Jedi, which typically matches the sys path that was used at the time when Jedi was imported. Most methods have a ``line`` and a ``column`` parameter. Lines in Jedi are always 1-based and columns are always zero based. To avoid repetition they are not always documented. You can omit both line and column. Jedi will then just do whatever action you are calling at the end of the file. If you provide only the line, just will complete at the end of that line. .. warning:: By default :attr:`jedi.settings.fast_parser` is enabled, which means that parso reuses modules (i.e. they are not immutable). With this setting Jedi is **not thread safe** and it is also not safe to use multiple :class:`.Script` instances and its definitions at the same time. If you are a normal plugin developer this should not be an issue. It is an issue for people that do more complex stuff with Jedi. This is purely a performance optimization and works pretty well for all typical usages, however consider to turn the setting off if it causes you problems. See also `this discussion <https://github.com/davidhalter/jedi/issues/1240>`_. :param code: The source code of the current file, separated by newlines. :type code: str :param path: The path of the file in the file system, or ``''`` if it hasn't been saved yet. :type path: str or pathlib.Path or None :param Environment environment: Provide a predefined :ref:`Environment <environments>` to work with a specific Python version or virtualenv. :param Project project: Provide a :class:`.Project` to make sure finding references works well, because the right folder is searched. There are also ways to modify the sys path and other things. """ def __init__(self, code=None, *, path=None, environment=None, project=None): self._orig_path = path if isinstance(path, str): path = Path(path) self.path = path.absolute() if path else None if code is None: if path is None: raise ValueError("Must provide at least one of code or path") # TODO add a better warning than the traceback! with open(path, 'rb') as f: code = f.read() if project is None: # Load the Python grammar of the current interpreter. project = get_default_project(None if self.path is None else self.path.parent) self._inference_state = InferenceState( project, environment=environment, script_path=self.path ) debug.speed('init') self._module_node, code = self._inference_state.parse_and_get_code( code=code, path=self.path, use_latest_grammar=path and path.suffix == '.pyi', cache=False, # No disk cache, because the current script often changes. diff_cache=settings.fast_parser, cache_path=settings.cache_directory, ) debug.speed('parsed') self._code_lines = parso.split_lines(code, keepends=True) self._code = code cache.clear_time_caches() debug.reset_time() # Cache the module, this is mostly useful for testing, since this shouldn't # be called multiple times. @cache.memoize_method def _get_module(self): names = None is_package = False if self.path is not None: import_names, is_p = transform_path_to_dotted( self._inference_state.get_sys_path(add_parent_paths=False), self.path ) if import_names is not None: names = import_names is_package = is_p if self.path is None: file_io = None else: file_io = KnownContentFileIO(self.path, self._code) if self.path is not None and self.path.suffix == '.pyi': # We are in a stub file. Try to load the stub properly. stub_module = load_proper_stub_module( self._inference_state, self._inference_state.latest_grammar, file_io, names, self._module_node ) if stub_module is not None: return stub_module if names is None: names = ('__main__',) module = ModuleValue( self._inference_state, self._module_node, file_io=file_io, string_names=names, code_lines=self._code_lines, is_package=is_package, ) if names[0] not in ('builtins', 'typing'): # These modules are essential for Jedi, so don't overwrite them. self._inference_state.module_cache.add(names, ValueSet([module])) return module def _get_module_context(self): return self._get_module().as_context() def __repr__(self): return '<%s: %s %r>' % ( self.__class__.__name__, repr(self._orig_path), self._inference_state.environment, ) @validate_line_column def complete(self, line=None, column=None, *, fuzzy=False): """ Completes objects under the cursor. Those objects contain information about the completions, more than just names. :param fuzzy: Default False. Will return fuzzy completions, which means that e.g. ``ooa`` will match ``foobar``. :return: Completion objects, sorted by name. Normal names appear before "private" names that start with ``_`` and those appear before magic methods and name mangled names that start with ``__``. :rtype: list of :class:`.Completion` """ self._inference_state.reset_recursion_limitations() with debug.increase_indent_cm('complete'): completion = Completion( self._inference_state, self._get_module_context(), self._code_lines, (line, column), self.get_signatures, fuzzy=fuzzy, ) return completion.complete() @validate_line_column def infer(self, line=None, column=None, *, only_stubs=False, prefer_stubs=False): """ Return the definitions of under the cursor. It is basically a wrapper around Jedi's type inference. This method follows complicated paths and returns the end, not the first definition. The big difference between :meth:`goto` and :meth:`infer` is that :meth:`goto` doesn't follow imports and statements. Multiple objects may be returned, because depending on an option you can have two different versions of a function. :param only_stubs: Only return stubs for this method. :param prefer_stubs: Prefer stubs to Python objects for this method. :rtype: list of :class:`.Name` """ self._inference_state.reset_recursion_limitations() pos = line, column leaf = self._module_node.get_name_of_position(pos) if leaf is None: leaf = self._module_node.get_leaf_for_position(pos) if leaf is None or leaf.type == 'string': return [] if leaf.end_pos == (line, column) and leaf.type == 'operator': next_ = leaf.get_next_leaf() if next_.start_pos == leaf.end_pos \ and next_.type in ('number', 'string', 'keyword'): leaf = next_ context = self._get_module_context().create_context(leaf) values = helpers.infer(self._inference_state, context, leaf) values = convert_values( values, only_stubs=only_stubs, prefer_stubs=prefer_stubs, ) defs = [classes.Name(self._inference_state, c.name) for c in values] # The additional set here allows the definitions to become unique in an # API sense. In the internals we want to separate more things than in # the API. return helpers.sorted_definitions(set(defs)) @validate_line_column def goto(self, line=None, column=None, *, follow_imports=False, follow_builtin_imports=False, only_stubs=False, prefer_stubs=False): """ Goes to the name that defined the object under the cursor. Optionally you can follow imports. Multiple objects may be returned, depending on an if you can have two different versions of a function. :param follow_imports: The method will follow imports. :param follow_builtin_imports: If ``follow_imports`` is True will try to look up names in builtins (i.e. compiled or extension modules). :param only_stubs: Only return stubs for this method. :param prefer_stubs: Prefer stubs to Python objects for this method. :rtype: list of :class:`.Name` """ self._inference_state.reset_recursion_limitations() tree_name = self._module_node.get_name_of_position((line, column)) if tree_name is None: # Without a name we really just want to jump to the result e.g. # executed by `foo()`, if we the cursor is after `)`. return self.infer(line, column, only_stubs=only_stubs, prefer_stubs=prefer_stubs) name = self._get_module_context().create_name(tree_name) # Make it possible to goto the super class function/attribute # definitions, when they are overwritten. names = [] if name.tree_name.is_definition() and name.parent_context.is_class(): class_node = name.parent_context.tree_node class_value = self._get_module_context().create_value(class_node) mro = class_value.py__mro__() next(mro) # Ignore the first entry, because it's the class itself. for cls in mro: names = cls.goto(tree_name.value) if names: break if not names: names = list(name.goto()) if follow_imports: names = helpers.filter_follow_imports(names, follow_builtin_imports) names = convert_names( names, only_stubs=only_stubs, prefer_stubs=prefer_stubs, ) defs = [classes.Name(self._inference_state, d) for d in set(names)] # Avoid duplicates return list(set(helpers.sorted_definitions(defs))) def search(self, string, *, all_scopes=False): """ Searches a name in the current file. For a description of how the search string should look like, please have a look at :meth:`.Project.search`. :param bool all_scopes: Default False; searches not only for definitions on the top level of a module level, but also in functions and classes. :yields: :class:`.Name` """ return self._search_func(string, all_scopes=all_scopes) @to_list def _search_func(self, string, all_scopes=False, complete=False, fuzzy=False): names = self._names(all_scopes=all_scopes) wanted_type, wanted_names = helpers.split_search_string(string) return search_in_module( self._inference_state, self._get_module_context(), names=names, wanted_type=wanted_type, wanted_names=wanted_names, complete=complete, fuzzy=fuzzy, ) def complete_search(self, string, **kwargs): """ Like :meth:`.Script.search`, but completes that string. If you want to have all possible definitions in a file you can also provide an empty string. :param bool all_scopes: Default False; searches not only for definitions on the top level of a module level, but also in functions and classes. :param fuzzy: Default False. Will return fuzzy completions, which means that e.g. ``ooa`` will match ``foobar``. :yields: :class:`.Completion` """ return self._search_func(string, complete=True, **kwargs) @validate_line_column def help(self, line=None, column=None): """ Used to display a help window to users. Uses :meth:`.Script.goto` and returns additional definitions for keywords and operators. Typically you will want to display :meth:`.BaseName.docstring` to the user for all the returned definitions. The additional definitions are ``Name(...).type == 'keyword'``. These definitions do not have a lot of value apart from their docstring attribute, which contains the output of Python's :func:`help` function. :rtype: list of :class:`.Name` """ self._inference_state.reset_recursion_limitations() definitions = self.goto(line, column, follow_imports=True) if definitions: return definitions leaf = self._module_node.get_leaf_for_position((line, column)) if leaf is not None and leaf.end_pos == (line, column) and leaf.type == 'newline': next_ = leaf.get_next_leaf() if next_ is not None and next_.start_pos == leaf.end_pos: leaf = next_ if leaf is not None and leaf.type in ('keyword', 'operator', 'error_leaf'): def need_pydoc(): if leaf.value in ('(', ')', '[', ']'): if leaf.parent.type == 'trailer': return False if leaf.parent.type == 'atom': return False grammar = self._inference_state.grammar # This parso stuff is not public, but since I control it, this # is fine :-) ~dave reserved = grammar._pgen_grammar.reserved_syntax_strings.keys() return leaf.value in reserved if need_pydoc(): name = KeywordName(self._inference_state, leaf.value) return [classes.Name(self._inference_state, name)] return [] @validate_line_column def get_references(self, line=None, column=None, **kwargs): """ Lists all references of a variable in a project. Since this can be quite hard to do for Jedi, if it is too complicated, Jedi will stop searching. :param include_builtins: Default ``True``. If ``False``, checks if a definition is a builtin (e.g. ``sys``) and in that case does not return it. :param scope: Default ``'project'``. If ``'file'``, include references in the current module only. :rtype: list of :class:`.Name` """ self._inference_state.reset_recursion_limitations() def _references(include_builtins=True, scope='project'): if scope not in ('project', 'file'): raise ValueError('Only the scopes "file" and "project" are allowed') tree_name = self._module_node.get_name_of_position((line, column)) if tree_name is None: # Must be syntax return [] names = find_references(self._get_module_context(), tree_name, scope == 'file') definitions = [classes.Name(self._inference_state, n) for n in names] if not include_builtins or scope == 'file': definitions = [d for d in definitions if not d.in_builtin_module()] return helpers.sorted_definitions(definitions) return _references(**kwargs) @validate_line_column def get_signatures(self, line=None, column=None): """ Return the function object of the call under the cursor. E.g. if the cursor is here:: abs(# <-- cursor is here This would return the ``abs`` function. On the other hand:: abs()# <-- cursor is here This would return an empty list.. :rtype: list of :class:`.Signature` """ self._inference_state.reset_recursion_limitations() pos = line, column call_details = helpers.get_signature_details(self._module_node, pos) if call_details is None: return [] context = self._get_module_context().create_context(call_details.bracket_leaf) definitions = helpers.cache_signatures( self._inference_state, context, call_details.bracket_leaf, self._code_lines, pos ) debug.speed('func_call followed') # TODO here we use stubs instead of the actual values. We should use # the signatures from stubs, but the actual values, probably?! return [classes.Signature(self._inference_state, signature, call_details) for signature in definitions.get_signatures()] @validate_line_column def get_context(self, line=None, column=None): """ Returns the scope context under the cursor. This basically means the function, class or module where the cursor is at. :rtype: :class:`.Name` """ pos = (line, column) leaf = self._module_node.get_leaf_for_position(pos, include_prefixes=True) if leaf.start_pos > pos or leaf.type == 'endmarker': previous_leaf = leaf.get_previous_leaf() if previous_leaf is not None: leaf = previous_leaf module_context = self._get_module_context() n = tree.search_ancestor(leaf, 'funcdef', 'classdef') if n is not None and n.start_pos < pos <= n.children[-1].start_pos: # This is a bit of a special case. The context of a function/class # name/param/keyword is always it's parent context, not the # function itself. Catch all the cases here where we are before the # suite object, but still in the function. context = module_context.create_value(n).as_context() else: context = module_context.create_context(leaf) while context.name is None: context = context.parent_context # comprehensions definition = classes.Name(self._inference_state, context.name) while definition.type != 'module': name = definition._name # TODO private access tree_name = name.tree_name if tree_name is not None: # Happens with lambdas. scope = tree_name.get_definition() if scope.start_pos[1] < column: break definition = definition.parent() return definition def _analysis(self): self._inference_state.is_analysis = True self._inference_state.analysis_modules = [self._module_node] module = self._get_module_context() try: for node in get_executable_nodes(self._module_node): context = module.create_context(node) if node.type in ('funcdef', 'classdef'): # Resolve the decorators. tree_name_to_values(self._inference_state, context, node.children[1]) elif isinstance(node, tree.Import): import_names = set(node.get_defined_names()) if node.is_nested(): import_names |= set(path[-1] for path in node.get_paths()) for n in import_names: imports.infer_import(context, n) elif node.type == 'expr_stmt': types = context.infer_node(node) for testlist in node.children[:-1:2]: # Iterate tuples. unpack_tuple_to_dict(context, types, testlist) else: if node.type == 'name': defs = self._inference_state.infer(context, node) else: defs = infer_call_of_leaf(context, node) try_iter_content(defs) self._inference_state.reset_recursion_limitations() ana = [a for a in self._inference_state.analysis if self.path == a.path] return sorted(set(ana), key=lambda x: x.line) finally: self._inference_state.is_analysis = False def get_names(self, **kwargs): """ Returns names defined in the current file. :param all_scopes: If True lists the names of all scopes instead of only the module namespace. :param definitions: If True lists the names that have been defined by a class, function or a statement (``a = b`` returns ``a``). :param references: If True lists all the names that are not listed by ``definitions=True``. E.g. ``a = b`` returns ``b``. :rtype: list of :class:`.Name` """ names = self._names(**kwargs) return [classes.Name(self._inference_state, n) for n in names] def get_syntax_errors(self): """ Lists all syntax errors in the current file. :rtype: list of :class:`.SyntaxError` """ return parso_to_jedi_errors(self._inference_state.grammar, self._module_node) def _names(self, all_scopes=False, definitions=True, references=False): self._inference_state.reset_recursion_limitations() # Set line/column to a random position, because they don't matter. module_context = self._get_module_context() defs = [ module_context.create_name(name) for name in helpers.get_module_names( self._module_node, all_scopes=all_scopes, definitions=definitions, references=references, ) ] return sorted(defs, key=lambda x: x.start_pos) def rename(self, line=None, column=None, *, new_name): """ Renames all references of the variable under the cursor. :param new_name: The variable under the cursor will be renamed to this string. :raises: :exc:`.RefactoringError` :rtype: :class:`.Refactoring` """ definitions = self.get_references(line, column, include_builtins=False) return refactoring.rename(self._inference_state, definitions, new_name) @validate_line_column def extract_variable(self, line, column, *, new_name, until_line=None, until_column=None): """ Moves an expression to a new statement. For example if you have the cursor on ``foo`` and provide a ``new_name`` called ``bar``:: foo = 3.1 x = int(foo + 1) the code above will become:: foo = 3.1 bar = foo + 1 x = int(bar) :param new_name: The expression under the cursor will be renamed to this string. :param int until_line: The the selection range ends at this line, when omitted, Jedi will be clever and try to define the range itself. :param int until_column: The the selection range ends at this column, when omitted, Jedi will be clever and try to define the range itself. :raises: :exc:`.RefactoringError` :rtype: :class:`.Refactoring` """ if until_line is None and until_column is None: until_pos = None else: if until_line is None: until_line = line if until_column is None: until_column = len(self._code_lines[until_line - 1]) until_pos = until_line, until_column return extract_variable( self._inference_state, self.path, self._module_node, new_name, (line, column), until_pos ) @validate_line_column def extract_function(self, line, column, *, new_name, until_line=None, until_column=None): """ Moves an expression to a new function. For example if you have the cursor on ``foo`` and provide a ``new_name`` called ``bar``:: global_var = 3 def x(): foo = 3.1 x = int(foo + 1 + global_var) the code above will become:: global_var = 3 def bar(foo): return int(foo + 1 + global_var) def x(): foo = 3.1 x = bar(foo) :param new_name: The expression under the cursor will be replaced with a function with this name. :param int until_line: The the selection range ends at this line, when omitted, Jedi will be clever and try to define the range itself. :param int until_column: The the selection range ends at this column, when omitted, Jedi will be clever and try to define the range itself. :raises: :exc:`.RefactoringError` :rtype: :class:`.Refactoring` """ if until_line is None and until_column is None: until_pos = None else: if until_line is None: until_line = line if until_column is None: until_column = len(self._code_lines[until_line - 1]) until_pos = until_line, until_column return extract_function( self._inference_state, self.path, self._get_module_context(), new_name, (line, column), until_pos ) def inline(self, line=None, column=None): """ Inlines a variable under the cursor. This is basically the opposite of extracting a variable. For example with the cursor on bar:: foo = 3.1 bar = foo + 1 x = int(bar) the code above will become:: foo = 3.1 x = int(foo + 1) :raises: :exc:`.RefactoringError` :rtype: :class:`.Refactoring` """ names = [d._name for d in self.get_references(line, column, include_builtins=True)] return refactoring.inline(self._inference_state, names)
Script
python
pyca__cryptography
src/cryptography/hazmat/primitives/twofactor/totp.py
{ "start": 505, "end": 1652 }
class ____: def __init__( self, key: Buffer, length: int, algorithm: HOTPHashTypes, time_step: int, backend: typing.Any = None, enforce_key_length: bool = True, ): self._time_step = time_step self._hotp = HOTP( key, length, algorithm, enforce_key_length=enforce_key_length ) def generate(self, time: int | float) -> bytes: if not isinstance(time, (int, float)): raise TypeError( "Time parameter must be an integer type or float type." ) counter = int(time / self._time_step) return self._hotp.generate(counter) def verify(self, totp: bytes, time: int) -> None: if not constant_time.bytes_eq(self.generate(time), totp): raise InvalidToken("Supplied TOTP value does not match.") def get_provisioning_uri( self, account_name: str, issuer: str | None ) -> str: return _generate_uri( self._hotp, "totp", account_name, issuer, [("period", int(self._time_step))], )
TOTP
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v2/adamax.py
{ "start": 1226, "end": 7695 }
class ____(optimizer_v2.OptimizerV2): """Optimizer that implements the Adamax algorithm. It is a variant of Adam based on the infinity norm. Default parameters follow those provided in the paper. Adamax is sometimes superior to adam, specially in models with embeddings. Initialization: ```python m = 0 # Initialize initial 1st moment vector v = 0 # Initialize the exponentially weighted infinity norm t = 0 # Initialize timestep ``` The update rule for parameter `w` with gradient `g` is described at the end of section 7.1 of the paper: ```python t += 1 m = beta1 * m + (1 - beta) * g v = max(beta2 * v, abs(g)) current_lr = learning_rate / (1 - beta1 ** t) w = w - current_lr * m / (v + epsilon) ``` Similarly to `Adam`, the epsilon is added for numerical stability (especially to get rid of division by zero when `v_t == 0`). In contrast to `Adam`, the sparse implementation of this algorithm (used when the gradient is an IndexedSlices object, typically because of `tf.gather` or an embedding lookup in the forward pass) only updates variable slices and corresponding `m_t`, `v_t` terms when that part of the variable was used in the forward pass. This means that the sparse behavior is contrast to the dense behavior (similar to some momentum implementations which ignore momentum unless a variable slice was actually used). Args: learning_rate: A `Tensor`, floating point value, or a schedule that is a `tf.keras.optimizers.schedules.LearningRateSchedule`. The learning rate. beta_1: A float value or a constant float tensor. The exponential decay rate for the 1st moment estimates. beta_2: A float value or a constant float tensor. The exponential decay rate for the exponentially weighted infinity norm. epsilon: A small constant for numerical stability. name: Optional name for the operations created when applying gradients. Defaults to `"Adamax"`. **kwargs: Keyword arguments. Allowed to be one of `"clipnorm"` or `"clipvalue"`. `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips gradients by value. Reference: - [Kingma et al., 2014](http://arxiv.org/abs/1412.6980) """ _HAS_AGGREGATE_GRAD = True def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-7, name='Adamax', **kwargs): super(Adamax, self).__init__(name, **kwargs) self._set_hyper('learning_rate', kwargs.get('lr', learning_rate)) self._set_hyper('decay', self._initial_decay) self._set_hyper('beta_1', beta_1) self._set_hyper('beta_2', beta_2) self.epsilon = epsilon or backend_config.epsilon() def _create_slots(self, var_list): # Separate for-loops to respect the ordering of slot variables from v1. for var in var_list: self.add_slot(var, 'm') # Create slots for the first moments. for var in var_list: self.add_slot(var, 'v') # Create slots for the second moments. def _prepare_local(self, var_device, var_dtype, apply_state): super(Adamax, self)._prepare_local(var_device, var_dtype, apply_state) local_step = math_ops.cast(self.iterations + 1, var_dtype) beta_1_t = array_ops.identity(self._get_hyper('beta_1', var_dtype)) beta_2_t = array_ops.identity(self._get_hyper('beta_2', var_dtype)) beta_1_power = math_ops.pow(beta_1_t, local_step) lr_t = apply_state[(var_device, var_dtype)]['lr_t'] apply_state[(var_device, var_dtype)].update( dict( neg_scaled_lr=-lr_t / (1 - beta_1_power), epsilon=tensor_conversion.convert_to_tensor_v2_with_dispatch( self.epsilon, var_dtype ), beta_1_t=beta_1_t, beta_1_power=beta_1_power, one_minus_beta_1_t=1 - beta_1_t, beta_2_t=beta_2_t, zero=array_ops.zeros((), dtype=dtypes.int64), ) ) def _resource_apply_dense(self, grad, var, apply_state=None): var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = ((apply_state or {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) m = self.get_slot(var, 'm') v = self.get_slot(var, 'v') return gen_training_ops.ResourceApplyAdaMax( var=var.handle, m=m.handle, v=v.handle, beta1_power=coefficients['beta_1_power'], lr=coefficients['lr_t'], beta1=coefficients['beta_1_t'], beta2=coefficients['beta_2_t'], epsilon=coefficients['epsilon'], grad=grad, use_locking=self._use_locking) def _resource_apply_sparse(self, grad, var, indices, apply_state=None): var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = ((apply_state or {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) # m_t = beta1 * m + (1 - beta1) * g_t m = self.get_slot(var, 'm') m_slice = array_ops.gather(m, indices, axis=coefficients['zero']) m_t_slice = (m_slice * coefficients['beta_1_t'] + grad * coefficients['one_minus_beta_1_t']) with ops.control_dependencies([m_t_slice]): m_t = self._resource_scatter_update(m, indices, m_t_slice) # u_t = max(beta2 * u, abs(g_t)) v = self.get_slot(var, 'v') v_slice = array_ops.gather(v, indices, axis=coefficients['zero']) v_t_slice = math_ops.maximum(v_slice * coefficients['beta_2_t'], math_ops.abs(grad)) with ops.control_dependencies([v_t_slice]): v_t = self._resource_scatter_update(v, indices, v_t_slice) # theta_t = theta - lr / (1 - beta1^t) * m_t / u_t var_slice = coefficients['neg_scaled_lr'] * ( m_t_slice / (v_t_slice + coefficients['epsilon'])) with ops.control_dependencies([var_slice]): var_update = self._resource_scatter_add(var, indices, var_slice) return control_flow_ops.group(*[var_update, m_t, v_t]) def get_config(self): config = super(Adamax, self).get_config() config.update({ 'learning_rate': self._serialize_hyperparameter('learning_rate'), 'decay': self._initial_decay, 'beta_1': self._serialize_hyperparameter('beta_1'), 'beta_2': self._serialize_hyperparameter('beta_2'), 'epsilon': self.epsilon, }) return config
Adamax
python
pytorch__pytorch
torch/_inductor/subgraph_lowering.py
{ "start": 4729, "end": 4802 }
class ____: dtype: torch.dtype device: torch.device
InputDescriptor
python
huggingface__transformers
src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py
{ "start": 61288, "end": 62116 }
class ____(ModelOutput): r""" intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`): Stacked intermediate hidden states (output of each layer of the decoder). intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`): Stacked intermediate reference points (reference points of each layer of the decoder). """ last_hidden_state: Optional[torch.FloatTensor] = None intermediate_hidden_states: Optional[torch.FloatTensor] = None intermediate_reference_points: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor]] = None attentions: Optional[tuple[tuple[torch.FloatTensor]]] = None
MMGroundingDinoDecoderOutput
python
fluentpython__example-code-2e
24-class-metaprog/slots/slots_timing.py
{ "start": 261, "end": 472 }
class ____(type): def __new__(meta_cls, cls_name, bases, cls_dict): cls_dict['__slots__'] = ('x', 'y') return super().__new__( meta_cls, cls_name, bases, cls_dict)
Correct1
python
cython__cython
Cython/Tests/TestTestUtils.py
{ "start": 149, "end": 2898 }
class ____(unittest.TestCase): def setUp(self): super().setUp() self.temp_dir = tempfile.mkdtemp() def tearDown(self): if self.temp_dir and os.path.isdir(self.temp_dir): shutil.rmtree(self.temp_dir) super().tearDown() def _test_path(self, filename): return os.path.join(self.temp_dir, filename) def _test_write_file(self, content, expected, **kwargs): file_path = self._test_path("abcfile") write_file(file_path, content, **kwargs) assert os.path.isfile(file_path) with open(file_path, 'rb') as f: found = f.read() assert found == expected, (repr(expected), repr(found)) def test_write_file_text(self): text = "abcüöä" self._test_write_file(text, text.encode('utf8')) def test_write_file_dedent(self): text = """ A horse is a horse, of course, of course, And no one can talk to a horse of course """ self._test_write_file(text, textwrap.dedent(text).encode('utf8'), dedent=True) def test_write_file_bytes(self): self._test_write_file(b"ab\0c", b"ab\0c") def test_write_newer_file(self): file_path_1 = self._test_path("abcfile1.txt") file_path_2 = self._test_path("abcfile2.txt") write_file(file_path_1, "abc") assert os.path.isfile(file_path_1) write_newer_file(file_path_2, file_path_1, "xyz") assert os.path.isfile(file_path_2) assert os.path.getmtime(file_path_2) > os.path.getmtime(file_path_1) def test_write_newer_file_same(self): file_path = self._test_path("abcfile.txt") write_file(file_path, "abc") mtime = os.path.getmtime(file_path) write_newer_file(file_path, file_path, "xyz") assert os.path.getmtime(file_path) > mtime def test_write_newer_file_fresh(self): file_path = self._test_path("abcfile.txt") assert not os.path.exists(file_path) write_newer_file(file_path, file_path, "xyz") assert os.path.isfile(file_path) def test_parse_pattern(self): self.assertEqual( _parse_pattern("pattern"), (None, None, 'pattern') ) self.assertEqual( _parse_pattern("/start/:pattern"), ('start', None, 'pattern') ) self.assertEqual( _parse_pattern(":/end/ pattern"), (None, 'end', 'pattern') ) self.assertEqual( _parse_pattern("/start/:/end/ pattern"), ('start', 'end', 'pattern') ) self.assertEqual( _parse_pattern("/start/:/end/pattern"), ('start', 'end', 'pattern') )
TestTestUtils
python
wandb__wandb
wandb/vendor/pygments/lexers/scripting.py
{ "start": 25282, "end": 45809 }
class ____(RegexLexer): """ For `AppleScript source code <http://developer.apple.com/documentation/AppleScript/ Conceptual/AppleScriptLangGuide>`_, including `AppleScript Studio <http://developer.apple.com/documentation/AppleScript/ Reference/StudioReference>`_. Contributed by Andreas Amann <aamann@mac.com>. .. versionadded:: 1.0 """ name = 'AppleScript' aliases = ['applescript'] filenames = ['*.applescript'] flags = re.MULTILINE | re.DOTALL Identifiers = r'[a-zA-Z]\w*' # XXX: use words() for all of these Literals = ('AppleScript', 'current application', 'false', 'linefeed', 'missing value', 'pi', 'quote', 'result', 'return', 'space', 'tab', 'text item delimiters', 'true', 'version') Classes = ('alias ', 'application ', 'boolean ', 'class ', 'constant ', 'date ', 'file ', 'integer ', 'list ', 'number ', 'POSIX file ', 'real ', 'record ', 'reference ', 'RGB color ', 'script ', 'text ', 'unit types', '(?:Unicode )?text', 'string') BuiltIn = ('attachment', 'attribute run', 'character', 'day', 'month', 'paragraph', 'word', 'year') HandlerParams = ('about', 'above', 'against', 'apart from', 'around', 'aside from', 'at', 'below', 'beneath', 'beside', 'between', 'for', 'given', 'instead of', 'on', 'onto', 'out of', 'over', 'since') Commands = ('ASCII (character|number)', 'activate', 'beep', 'choose URL', 'choose application', 'choose color', 'choose file( name)?', 'choose folder', 'choose from list', 'choose remote application', 'clipboard info', 'close( access)?', 'copy', 'count', 'current date', 'delay', 'delete', 'display (alert|dialog)', 'do shell script', 'duplicate', 'exists', 'get eof', 'get volume settings', 'info for', 'launch', 'list (disks|folder)', 'load script', 'log', 'make', 'mount volume', 'new', 'offset', 'open( (for access|location))?', 'path to', 'print', 'quit', 'random number', 'read', 'round', 'run( script)?', 'say', 'scripting components', 'set (eof|the clipboard to|volume)', 'store script', 'summarize', 'system attribute', 'system info', 'the clipboard', 'time to GMT', 'write', 'quoted form') References = ('(in )?back of', '(in )?front of', '[0-9]+(st|nd|rd|th)', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'after', 'back', 'before', 'behind', 'every', 'front', 'index', 'last', 'middle', 'some', 'that', 'through', 'thru', 'where', 'whose') Operators = ("and", "or", "is equal", "equals", "(is )?equal to", "is not", "isn't", "isn't equal( to)?", "is not equal( to)?", "doesn't equal", "does not equal", "(is )?greater than", "comes after", "is not less than or equal( to)?", "isn't less than or equal( to)?", "(is )?less than", "comes before", "is not greater than or equal( to)?", "isn't greater than or equal( to)?", "(is )?greater than or equal( to)?", "is not less than", "isn't less than", "does not come before", "doesn't come before", "(is )?less than or equal( to)?", "is not greater than", "isn't greater than", "does not come after", "doesn't come after", "starts? with", "begins? with", "ends? with", "contains?", "does not contain", "doesn't contain", "is in", "is contained by", "is not in", "is not contained by", "isn't contained by", "div", "mod", "not", "(a )?(ref( to)?|reference to)", "is", "does") Control = ('considering', 'else', 'error', 'exit', 'from', 'if', 'ignoring', 'in', 'repeat', 'tell', 'then', 'times', 'to', 'try', 'until', 'using terms from', 'while', 'whith', 'with timeout( of)?', 'with transaction', 'by', 'continue', 'end', 'its?', 'me', 'my', 'return', 'of', 'as') Declarations = ('global', 'local', 'prop(erty)?', 'set', 'get') Reserved = ('but', 'put', 'returning', 'the') StudioClasses = ('action cell', 'alert reply', 'application', 'box', 'browser( cell)?', 'bundle', 'button( cell)?', 'cell', 'clip view', 'color well', 'color-panel', 'combo box( item)?', 'control', 'data( (cell|column|item|row|source))?', 'default entry', 'dialog reply', 'document', 'drag info', 'drawer', 'event', 'font(-panel)?', 'formatter', 'image( (cell|view))?', 'matrix', 'menu( item)?', 'item', 'movie( view)?', 'open-panel', 'outline view', 'panel', 'pasteboard', 'plugin', 'popup button', 'progress indicator', 'responder', 'save-panel', 'scroll view', 'secure text field( cell)?', 'slider', 'sound', 'split view', 'stepper', 'tab view( item)?', 'table( (column|header cell|header view|view))', 'text( (field( cell)?|view))?', 'toolbar( item)?', 'user-defaults', 'view', 'window') StudioEvents = ('accept outline drop', 'accept table drop', 'action', 'activated', 'alert ended', 'awake from nib', 'became key', 'became main', 'begin editing', 'bounds changed', 'cell value', 'cell value changed', 'change cell value', 'change item value', 'changed', 'child of item', 'choose menu item', 'clicked', 'clicked toolbar item', 'closed', 'column clicked', 'column moved', 'column resized', 'conclude drop', 'data representation', 'deminiaturized', 'dialog ended', 'document nib name', 'double clicked', 'drag( (entered|exited|updated))?', 'drop', 'end editing', 'exposed', 'idle', 'item expandable', 'item value', 'item value changed', 'items changed', 'keyboard down', 'keyboard up', 'launched', 'load data representation', 'miniaturized', 'mouse down', 'mouse dragged', 'mouse entered', 'mouse exited', 'mouse moved', 'mouse up', 'moved', 'number of browser rows', 'number of items', 'number of rows', 'open untitled', 'opened', 'panel ended', 'parameters updated', 'plugin loaded', 'prepare drop', 'prepare outline drag', 'prepare outline drop', 'prepare table drag', 'prepare table drop', 'read from file', 'resigned active', 'resigned key', 'resigned main', 'resized( sub views)?', 'right mouse down', 'right mouse dragged', 'right mouse up', 'rows changed', 'scroll wheel', 'selected tab view item', 'selection changed', 'selection changing', 'should begin editing', 'should close', 'should collapse item', 'should end editing', 'should expand item', 'should open( untitled)?', 'should quit( after last window closed)?', 'should select column', 'should select item', 'should select row', 'should select tab view item', 'should selection change', 'should zoom', 'shown', 'update menu item', 'update parameters', 'update toolbar item', 'was hidden', 'was miniaturized', 'will become active', 'will close', 'will dismiss', 'will display browser cell', 'will display cell', 'will display item cell', 'will display outline cell', 'will finish launching', 'will hide', 'will miniaturize', 'will move', 'will open', 'will pop up', 'will quit', 'will resign active', 'will resize( sub views)?', 'will select tab view item', 'will show', 'will zoom', 'write to file', 'zoomed') StudioCommands = ('animate', 'append', 'call method', 'center', 'close drawer', 'close panel', 'display', 'display alert', 'display dialog', 'display panel', 'go', 'hide', 'highlight', 'increment', 'item for', 'load image', 'load movie', 'load nib', 'load panel', 'load sound', 'localized string', 'lock focus', 'log', 'open drawer', 'path for', 'pause', 'perform action', 'play', 'register', 'resume', 'scroll', 'select( all)?', 'show', 'size to fit', 'start', 'step back', 'step forward', 'stop', 'synchronize', 'unlock focus', 'update') StudioProperties = ('accepts arrow key', 'action method', 'active', 'alignment', 'allowed identifiers', 'allows branch selection', 'allows column reordering', 'allows column resizing', 'allows column selection', 'allows customization', 'allows editing text attributes', 'allows empty selection', 'allows mixed state', 'allows multiple selection', 'allows reordering', 'allows undo', 'alpha( value)?', 'alternate image', 'alternate increment value', 'alternate title', 'animation delay', 'associated file name', 'associated object', 'auto completes', 'auto display', 'auto enables items', 'auto repeat', 'auto resizes( outline column)?', 'auto save expanded items', 'auto save name', 'auto save table columns', 'auto saves configuration', 'auto scroll', 'auto sizes all columns to fit', 'auto sizes cells', 'background color', 'bezel state', 'bezel style', 'bezeled', 'border rect', 'border type', 'bordered', 'bounds( rotation)?', 'box type', 'button returned', 'button type', 'can choose directories', 'can choose files', 'can draw', 'can hide', 'cell( (background color|size|type))?', 'characters', 'class', 'click count', 'clicked( data)? column', 'clicked data item', 'clicked( data)? row', 'closeable', 'collating', 'color( (mode|panel))', 'command key down', 'configuration', 'content(s| (size|view( margins)?))?', 'context', 'continuous', 'control key down', 'control size', 'control tint', 'control view', 'controller visible', 'coordinate system', 'copies( on scroll)?', 'corner view', 'current cell', 'current column', 'current( field)? editor', 'current( menu)? item', 'current row', 'current tab view item', 'data source', 'default identifiers', 'delta (x|y|z)', 'destination window', 'directory', 'display mode', 'displayed cell', 'document( (edited|rect|view))?', 'double value', 'dragged column', 'dragged distance', 'dragged items', 'draws( cell)? background', 'draws grid', 'dynamically scrolls', 'echos bullets', 'edge', 'editable', 'edited( data)? column', 'edited data item', 'edited( data)? row', 'enabled', 'enclosing scroll view', 'ending page', 'error handling', 'event number', 'event type', 'excluded from windows menu', 'executable path', 'expanded', 'fax number', 'field editor', 'file kind', 'file name', 'file type', 'first responder', 'first visible column', 'flipped', 'floating', 'font( panel)?', 'formatter', 'frameworks path', 'frontmost', 'gave up', 'grid color', 'has data items', 'has horizontal ruler', 'has horizontal scroller', 'has parent data item', 'has resize indicator', 'has shadow', 'has sub menu', 'has vertical ruler', 'has vertical scroller', 'header cell', 'header view', 'hidden', 'hides when deactivated', 'highlights by', 'horizontal line scroll', 'horizontal page scroll', 'horizontal ruler view', 'horizontally resizable', 'icon image', 'id', 'identifier', 'ignores multiple clicks', 'image( (alignment|dims when disabled|frame style|scaling))?', 'imports graphics', 'increment value', 'indentation per level', 'indeterminate', 'index', 'integer value', 'intercell spacing', 'item height', 'key( (code|equivalent( modifier)?|window))?', 'knob thickness', 'label', 'last( visible)? column', 'leading offset', 'leaf', 'level', 'line scroll', 'loaded', 'localized sort', 'location', 'loop mode', 'main( (bunde|menu|window))?', 'marker follows cell', 'matrix mode', 'maximum( content)? size', 'maximum visible columns', 'menu( form representation)?', 'miniaturizable', 'miniaturized', 'minimized image', 'minimized title', 'minimum column width', 'minimum( content)? size', 'modal', 'modified', 'mouse down state', 'movie( (controller|file|rect))?', 'muted', 'name', 'needs display', 'next state', 'next text', 'number of tick marks', 'only tick mark values', 'opaque', 'open panel', 'option key down', 'outline table column', 'page scroll', 'pages across', 'pages down', 'palette label', 'pane splitter', 'parent data item', 'parent window', 'pasteboard', 'path( (names|separator))?', 'playing', 'plays every frame', 'plays selection only', 'position', 'preferred edge', 'preferred type', 'pressure', 'previous text', 'prompt', 'properties', 'prototype cell', 'pulls down', 'rate', 'released when closed', 'repeated', 'requested print time', 'required file type', 'resizable', 'resized column', 'resource path', 'returns records', 'reuses columns', 'rich text', 'roll over', 'row height', 'rulers visible', 'save panel', 'scripts path', 'scrollable', 'selectable( identifiers)?', 'selected cell', 'selected( data)? columns?', 'selected data items?', 'selected( data)? rows?', 'selected item identifier', 'selection by rect', 'send action on arrow key', 'sends action when done editing', 'separates columns', 'separator item', 'sequence number', 'services menu', 'shared frameworks path', 'shared support path', 'sheet', 'shift key down', 'shows alpha', 'shows state by', 'size( mode)?', 'smart insert delete enabled', 'sort case sensitivity', 'sort column', 'sort order', 'sort type', 'sorted( data rows)?', 'sound', 'source( mask)?', 'spell checking enabled', 'starting page', 'state', 'string value', 'sub menu', 'super menu', 'super view', 'tab key traverses cells', 'tab state', 'tab type', 'tab view', 'table view', 'tag', 'target( printer)?', 'text color', 'text container insert', 'text container origin', 'text returned', 'tick mark position', 'time stamp', 'title(d| (cell|font|height|position|rect))?', 'tool tip', 'toolbar', 'trailing offset', 'transparent', 'treat packages as directories', 'truncated labels', 'types', 'unmodified characters', 'update views', 'use sort indicator', 'user defaults', 'uses data source', 'uses ruler', 'uses threaded animation', 'uses title from previous column', 'value wraps', 'version', 'vertical( (line scroll|page scroll|ruler view))?', 'vertically resizable', 'view', 'visible( document rect)?', 'volume', 'width', 'window', 'windows menu', 'wraps', 'zoomable', 'zoomed') tokens = { 'root': [ (r'\s+', Text), (u'¬\\n', String.Escape), (r"'s\s+", Text), # This is a possessive, consider moving (r'(--|#).*?$', Comment), (r'\(\*', Comment.Multiline, 'comment'), (r'[(){}!,.:]', Punctuation), (u'(«)([^»]+)(»)', bygroups(Text, Name.Builtin, Text)), (r'\b((?:considering|ignoring)\s*)' r'(application responses|case|diacriticals|hyphens|' r'numeric strings|punctuation|white space)', bygroups(Keyword, Name.Builtin)), (u'(-|\\*|\\+|&|≠|>=?|<=?|=|≥|≤|/|÷|\\^)', Operator), (r"\b(%s)\b" % '|'.join(Operators), Operator.Word), (r'^(\s*(?:on|end)\s+)' r'(%s)' % '|'.join(StudioEvents[::-1]), bygroups(Keyword, Name.Function)), (r'^(\s*)(in|on|script|to)(\s+)', bygroups(Text, Keyword, Text)), (r'\b(as )(%s)\b' % '|'.join(Classes), bygroups(Keyword, Name.Class)), (r'\b(%s)\b' % '|'.join(Literals), Name.Constant), (r'\b(%s)\b' % '|'.join(Commands), Name.Builtin), (r'\b(%s)\b' % '|'.join(Control), Keyword), (r'\b(%s)\b' % '|'.join(Declarations), Keyword), (r'\b(%s)\b' % '|'.join(Reserved), Name.Builtin), (r'\b(%s)s?\b' % '|'.join(BuiltIn), Name.Builtin), (r'\b(%s)\b' % '|'.join(HandlerParams), Name.Builtin), (r'\b(%s)\b' % '|'.join(StudioProperties), Name.Attribute), (r'\b(%s)s?\b' % '|'.join(StudioClasses), Name.Builtin), (r'\b(%s)\b' % '|'.join(StudioCommands), Name.Builtin), (r'\b(%s)\b' % '|'.join(References), Name.Builtin), (r'"(\\\\|\\"|[^"])*"', String.Double), (r'\b(%s)\b' % Identifiers, Name.Variable), (r'[-+]?(\d+\.\d*|\d*\.\d+)(E[-+][0-9]+)?', Number.Float), (r'[-+]?\d+', Number.Integer), ], 'comment': [ ('\(\*', Comment.Multiline, '#push'), ('\*\)', Comment.Multiline, '#pop'), ('[^*(]+', Comment.Multiline), ('[*(]', Comment.Multiline), ], }
AppleScriptLexer
python
astropy__astropy
astropy/modeling/tests/test_quantities_evaluation.py
{ "start": 2834, "end": 2993 }
class ____(Model): n_inputs = 2 n_outputs = 1 def evaluate(self, a, b): print("a", a) print("b", b) return a * b
MyTestModel
python
davidhalter__jedi
jedi/inference/gradual/type_var.py
{ "start": 1451, "end": 3882 }
class ____(BaseTypingValue): def __init__(self, parent_context, tree_name, var_name, unpacked_args): super().__init__(parent_context, tree_name) self._var_name = var_name self._constraints_lazy_values = [] self._bound_lazy_value = None self._covariant_lazy_value = None self._contravariant_lazy_value = None for key, lazy_value in unpacked_args: if key is None: self._constraints_lazy_values.append(lazy_value) else: if key == 'bound': self._bound_lazy_value = lazy_value elif key == 'covariant': self._covariant_lazy_value = lazy_value elif key == 'contravariant': self._contra_variant_lazy_value = lazy_value else: debug.warning('Invalid TypeVar param name %s', key) def py__name__(self): return self._var_name def get_filters(self, *args, **kwargs): return iter([]) def _get_classes(self): if self._bound_lazy_value is not None: return self._bound_lazy_value.infer() if self._constraints_lazy_values: return self.constraints debug.warning('Tried to infer the TypeVar %s without a given type', self._var_name) return NO_VALUES def is_same_class(self, other): # Everything can match an undefined type var. return True @property def constraints(self): return ValueSet.from_sets( lazy.infer() for lazy in self._constraints_lazy_values ) def define_generics(self, type_var_dict): try: found = type_var_dict[self.py__name__()] except KeyError: pass else: if found: return found return ValueSet({self}) def execute_annotation(self): return self._get_classes().execute_annotation() def infer_type_vars(self, value_set): def iterate(): for v in value_set: cls = v.py__class__() if v.is_function() or v.is_class(): cls = TypeWrapper(cls, v) yield cls annotation_name = self.py__name__() return {annotation_name: ValueSet(iterate())} def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self.py__name__())
TypeVar
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/linalg/sparse/csr_sparse_matrix_dense_mat_mul_grad_test.py
{ "start": 1525, "end": 5337 }
class ____(test.TestCase): @classmethod def setUpClass(cls): super(CSRSparseMatrixDenseMatMulGradTest, cls).setUpClass() cls._gpu_available = test_util.is_gpu_available() # TODO(penporn): Make these tests runnable on eager mode. # (tf.gradients and gradient_checker only run in graph mode.) @test_util.run_deprecated_v1 def _testLargeBatchSparseMatrixMatMulGrad( self, datatype, transpose_a, transpose_b, adjoint_a, adjoint_b, transpose_output, conjugate_output, batched_inputs, ): if batched_inputs: a_shape = (3, 5, 11) b_shape = (3, 11, 13) transpose = lambda x: np.transpose(x, (0, 2, 1)) else: a_shape = (5, 11) b_shape = (11, 13) transpose = np.transpose sparsify = lambda m: m * (m > 0) a_mats_val = sparsify( np.random.randn(*a_shape) + 1.j * np.random.randn(*a_shape)).astype(datatype) if transpose_a or adjoint_a: a_mats_val = transpose(a_mats_val) if adjoint_a: a_mats_val = np.conj(a_mats_val) b_mats_val = (np.random.randn(*b_shape) + 1.j * np.random.randn(*b_shape)).astype(datatype) if transpose_b or adjoint_b: b_mats_val = transpose(b_mats_val) if adjoint_b: b_mats_val = np.conj(b_mats_val) with self.test_session(): a_mats = ops.convert_to_tensor(a_mats_val, dtype=datatype) b_mats = ops.convert_to_tensor(b_mats_val, dtype=datatype) locs = array_ops.where(abs(a_mats_val) > 0) a_sm = sparse_csr_matrix_ops.dense_to_csr_sparse_matrix(a_mats, locs) c_mats = sparse_csr_matrix_ops.sparse_matrix_mat_mul( a_sm, b_mats, transpose_a=transpose_a, transpose_b=transpose_b, adjoint_a=adjoint_a, adjoint_b=adjoint_b, transpose_output=transpose_output, conjugate_output=conjugate_output) for [ten, val, nn] in [[a_mats, a_mats_val, "a"], [b_mats, b_mats_val, "b"]]: tf_logging.info("Testing gradients for %s" % nn) theoretical, numerical = gradient_checker.compute_gradient( ten, ten.get_shape().as_list(), c_mats, c_mats.get_shape().as_list(), x_init_value=val, delta=1e-3) self.assertAllClose(theoretical, numerical, atol=1e-3, rtol=1e-3) # These tests are refactored from sparse_csr_matrix_grad_test to keep its size # "medium". dtypes_to_test = [np.float32, np.complex64] for dtype in dtypes_to_test: for (t_a, t_b, adj_a, adj_b, t_out, conj_out, batched) in itertools.product(*(([False, True],) * 7)): def create_mat_mul_test_fn(dtype_, t_a_, t_b_, adj_a_, adj_b_, t_out_, conj_out_, batched_): # Skip invalid cases. if (t_a_ and adj_a_) or (t_b_ and adj_b_): return # Skip cases where we conjugate real matrices. if dtype_ == np.float32 and (adj_a_ or adj_b_ or conj_out_): return def test_fn(self): self._testLargeBatchSparseMatrixMatMulGrad(dtype_, t_a_, t_b_, adj_a_, adj_b_, t_out_, conj_out_, batched_) return test_fn name = ( "_testLargeBatchSparseMatrixMatMulGrad_dtype_%s_t_a_%s_t_b_%s_adj_a_%s_" "adj_b_%s_t_out_%s_conj_out_%s_batched_%s" % (dtype.__name__, t_a, t_b, adj_a, adj_b, t_out, conj_out, batched)) _add_test( CSRSparseMatrixDenseMatMulGradTest, "CSRSparseMatrixGradTest", name, create_mat_mul_test_fn(dtype, t_a, t_b, adj_a, adj_b, t_out, conj_out, batched)) if __name__ == "__main__": test.main()
CSRSparseMatrixDenseMatMulGradTest
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/links/test_datasync.py
{ "start": 1273, "end": 2121 }
class ____(BaseAwsLinksTestCase): link_class = DataSyncTaskLink def test_extra_link(self, mock_supervisor_comms): task_id = TASK_ID if AIRFLOW_V_3_0_PLUS and mock_supervisor_comms: mock_supervisor_comms.send.return_value = XComResult( key=self.link_class.key, value={ "region_name": "us-east-1", "aws_domain": self.link_class.get_aws_domain("aws"), "aws_partition": "aws", "task_id": task_id, }, ) self.assert_extra_link_url( expected_url=(f"https://console.aws.amazon.com/datasync/home?region=us-east-1#/tasks/{TASK_ID}"), region_name="us-east-1", aws_partition="aws", task_id=task_id, )
TestDataSyncTaskLink
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_asset.py
{ "start": 16581, "end": 17863 }
class ____: @pytest.mark.parametrize(("subcls", "group"), ((Model, "model"), (Dataset, "dataset"))) def test_only_name(self, subcls, group): obj = subcls(name="foobar") assert obj.name == "foobar" assert obj.uri == "foobar" assert obj.group == group @pytest.mark.parametrize(("subcls", "group"), ((Model, "model"), (Dataset, "dataset"))) def test_only_uri(self, subcls, group): obj = subcls(uri="s3://bucket/key/path") assert obj.name == "s3://bucket/key/path" assert obj.uri == "s3://bucket/key/path" assert obj.group == group @pytest.mark.parametrize(("subcls", "group"), ((Model, "model"), (Dataset, "dataset"))) def test_both_name_and_uri(self, subcls, group): obj = subcls("foobar", "s3://bucket/key/path") assert obj.name == "foobar" assert obj.uri == "s3://bucket/key/path" assert obj.group == group @pytest.mark.parametrize("arg", ["foobar", "s3://bucket/key/path"]) @pytest.mark.parametrize(("subcls", "group"), ((Model, "model"), (Dataset, "dataset"))) def test_only_posarg(self, subcls, group, arg): obj = subcls(arg) assert obj.name == arg assert obj.uri == arg assert obj.group == group
TestAssetSubclasses
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
{ "start": 56553, "end": 60158 }
class ____(test_util.TensorFlowTestCase): def testExceptions(self): with self.cached_session(): with self.assertRaisesRegex(ValueError, "`maxlen` must be scalar"): array_ops.sequence_mask([10, 20], [10, 20]) def testOneDimensionalWithMaxlen(self): res = array_ops.sequence_mask(constant_op.constant([1, 3, 2]), 5) self.assertAllEqual(res.get_shape(), [3, 5]) self.assertAllEqual( res, [[True, False, False, False, False], [True, True, True, False, False], [True, True, False, False, False]]) def testOneDimensionalDtypeWithoutMaxlen(self): # test dtype and default maxlen: res = array_ops.sequence_mask( constant_op.constant([0, 1, 4]), dtype=dtypes.float32) self.assertAllEqual(res.get_shape().as_list(), [3, 4]) self.assertAllEqual( res, [[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0]]) def testOneDimensionalWithoutMaxlen(self): res = array_ops.sequence_mask(constant_op.constant([0, 1, 4])) self.assertAllEqual(res.get_shape().as_list(), [3, 4]) self.assertAllEqual(res, [[False, False, False, False], [True, False, False, False], [True, True, True, True]]) def testTwoDimensional(self): res = array_ops.sequence_mask(constant_op.constant([[1, 3, 2]]), 5) self.assertAllEqual(res.get_shape(), [1, 3, 5]) self.assertAllEqual( res, [[[True, False, False, False, False], [True, True, True, False, False], [True, True, False, False, False]]]) # test dtype and default maxlen: res = array_ops.sequence_mask( constant_op.constant([[0, 1, 4], [1, 2, 3]]), dtype=dtypes.float32) self.assertAllEqual(res.get_shape().as_list(), [2, 3, 4]) self.assertAllEqual( res, [[[0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0]], [[1.0, 0.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 1.0, 0.0]]]) def testDtypes(self): def check_dtypes(lengths_dtype, maxlen_dtype): res = array_ops.sequence_mask( constant_op.constant([1, 3, 2], dtype=lengths_dtype), constant_op.constant(5, dtype=maxlen_dtype)) self.assertAllEqual(res.get_shape(), [3, 5]) self.assertAllEqual( res, [[True, False, False, False, False], [True, True, True, False, False], [True, True, False, False, False]]) check_dtypes(dtypes.int32, dtypes.int32) check_dtypes(dtypes.int32, dtypes.int64) check_dtypes(dtypes.int64, dtypes.int32) check_dtypes(dtypes.int64, dtypes.int64) def testOutputDtype(self): def check_output_dtype(output_dtype): res = self.evaluate( array_ops.sequence_mask( constant_op.constant([1, 3, 2], dtype=dtypes.int32), constant_op.constant(5, dtype=dtypes.int32), dtype=output_dtype)) self.assertAllEqual( res, self.evaluate( math_ops.cast([[True, False, False, False, False], [True, True, True, False, False], [True, True, False, False, False]], output_dtype))) check_output_dtype(dtypes.bool) check_output_dtype("bool") check_output_dtype(np.bool_) check_output_dtype(dtypes.int32) check_output_dtype("int32") check_output_dtype(np.int32) check_output_dtype(dtypes.float32) check_output_dtype("float32") check_output_dtype(np.float32) check_output_dtype(dtypes.int64) check_output_dtype("float64") check_output_dtype(np.float64)
SequenceMaskTest
python
ray-project__ray
python/ray/util/state/common.py
{ "start": 19874, "end": 21302 }
class ____(StateSchema): """PlacementGroup State""" #: The id of the placement group. placement_group_id: str = state_column(filterable=True) #: The name of the placement group if it is given by the name argument. name: str = state_column(filterable=True) #: The job id of the placement group. creator_job_id: str = state_column(filterable=True) #: The state of the placement group. #: #: - PENDING: The placement group creation is pending scheduling. #: It could be because there's not enough resources, some of creation #: stage has failed (e.g., failed to commit placement gropus because #: the node is dead). #: - CREATED: The placement group is created. #: - REMOVED: The placement group is removed. #: - RESCHEDULING: The placement group is rescheduling because some of #: bundles are dead because they were on dead nodes. state: TypePlacementGroupStatus = state_column(filterable=True) #: The bundle specification of the placement group. bundles: Optional[List[dict]] = state_column(filterable=False, detail=True) #: True if the placement group is detached. False otherwise. is_detached: Optional[bool] = state_column(filterable=True, detail=True) #: The scheduling stats of the placement group. stats: Optional[dict] = state_column(filterable=False, detail=True) @dataclass(init=not IS_PYDANTIC_2)
PlacementGroupState
python
sqlalchemy__sqlalchemy
test/orm/test_froms.py
{ "start": 116742, "end": 125450 }
class ____(QueryTest): """test mappers with SQL-expressions added as column properties.""" run_setup_mappers = None def test_external_columns_bad(self): users, User = self.tables.users, self.classes.User assert_raises_message( sa_exc.ArgumentError, "not represented in the mapper's table", self.mapper_registry.map_imperatively, User, users, properties={"concat": (users.c.id * 2)}, ) clear_mappers() def test_external_columns(self): """test querying mappings that reference external columns or selectables.""" users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={ "concat": column_property(users.c.id * 2), "count": column_property( select(func.count(addresses.c.id)) .where( users.c.id == addresses.c.user_id, ) .correlate(users) .scalar_subquery() ), }, ) self.mapper_registry.map_imperatively( Address, addresses, properties={ "user": relationship( User, ) }, ) sess = fixture_session() sess.query(Address).options(joinedload(Address.user)).all() eq_( sess.query(User).all(), [ User(id=7, concat=14, count=1), User(id=8, concat=16, count=3), User(id=9, concat=18, count=1), User(id=10, concat=20, count=0), ], ) address_result = [ Address(id=1, user=User(id=7, concat=14, count=1)), Address(id=2, user=User(id=8, concat=16, count=3)), Address(id=3, user=User(id=8, concat=16, count=3)), Address(id=4, user=User(id=8, concat=16, count=3)), Address(id=5, user=User(id=9, concat=18, count=1)), ] eq_(sess.query(Address).all(), address_result) # run the eager version twice to test caching of aliased clauses for x in range(2): sess.expunge_all() def go(): eq_( sess.query(Address) .options(joinedload(Address.user)) .order_by(Address.id) .all(), address_result, ) self.assert_sql_count(testing.db, go, 1) ualias = aliased(User) eq_( sess.query(Address, ualias).join(ualias, Address.user).all(), [(address, address.user) for address in address_result], ) ualias2 = aliased(User) eq_( sess.query(Address, ualias.count) .join(ualias, Address.user) .join(ualias2, Address.user) .order_by(Address.id) .all(), [ (Address(id=1), 1), (Address(id=2), 3), (Address(id=3), 3), (Address(id=4), 3), (Address(id=5), 1), ], ) eq_( sess.query(Address, ualias.concat, ualias.count) .join(Address.user.of_type(ualias)) .join(Address.user.of_type(ualias2)) .order_by(Address.id) .all(), [ (Address(id=1), 14, 1), (Address(id=2), 16, 3), (Address(id=3), 16, 3), (Address(id=4), 16, 3), (Address(id=5), 18, 1), ], ) ua = aliased(User) eq_( sess.query(Address, ua.concat, ua.count) .join(Address.user.of_type(ua)) .options(joinedload(Address.user)) .order_by(Address.id) .all(), [ (Address(id=1, user=User(id=7, concat=14, count=1)), 14, 1), (Address(id=2, user=User(id=8, concat=16, count=3)), 16, 3), (Address(id=3, user=User(id=8, concat=16, count=3)), 16, 3), (Address(id=4, user=User(id=8, concat=16, count=3)), 16, 3), (Address(id=5, user=User(id=9, concat=18, count=1)), 18, 1), ], ) eq_( list( sess.query(Address) .join(Address.user) .with_entities(Address.id, User.id, User.concat, User.count) ), [ (1, 7, 14, 1), (2, 8, 16, 3), (3, 8, 16, 3), (4, 8, 16, 3), (5, 9, 18, 1), ], ) eq_( list( sess.query(Address, ua) .join(Address.user.of_type(ua)) .with_entities(Address.id, ua.id, ua.concat, ua.count) ), [ (1, 7, 14, 1), (2, 8, 16, 3), (3, 8, 16, 3), (4, 8, 16, 3), (5, 9, 18, 1), ], ) def test_external_columns_joinedload(self): users, orders, User, Address, Order, addresses = ( self.tables.users, self.tables.orders, self.classes.User, self.classes.Address, self.classes.Order, self.tables.addresses, ) # in this test, we have a subquery on User that accesses "addresses", # underneath an joinedload for "addresses". So the "addresses" alias # adapter needs to *not* hit the "addresses" table within the "user" # subquery, but "user" still needs to be adapted. therefore the long # standing practice of eager adapters being "chained" has been removed # since its unnecessary and breaks this exact condition. self.mapper_registry.map_imperatively( User, users, properties={ "addresses": relationship( Address, backref="user", order_by=addresses.c.id ), "concat": column_property(users.c.id * 2), "count": column_property( select(func.count(addresses.c.id)) .where( users.c.id == addresses.c.user_id, ) .correlate(users) .scalar_subquery() ), }, ) self.mapper_registry.map_imperatively(Address, addresses) self.mapper_registry.map_imperatively( Order, orders, properties={"address": relationship(Address)} ) # m2o configure_mappers() sess = fixture_session() def go(): o1 = sess.get( Order, 1, options=[joinedload(Order.address).joinedload(Address.user)], ) eq_(o1.address.user.count, 1) self.assert_sql_count(testing.db, go, 1) sess = fixture_session() def go(): o1 = ( sess.query(Order) .options(joinedload(Order.address).joinedload(Address.user)) .first() ) eq_(o1.address.user.count, 1) self.assert_sql_count(testing.db, go, 1) def test_external_columns_compound(self): # see [ticket:2167] for background users, Address, addresses, User = ( self.tables.users, self.classes.Address, self.tables.addresses, self.classes.User, ) self.mapper_registry.map_imperatively( User, users, properties={"fullname": column_property(users.c.name.label("x"))}, ) self.mapper_registry.map_imperatively( Address, addresses, properties={ "username": column_property( select(User.fullname) .where(User.id == addresses.c.user_id) .label("y") ) }, ) sess = fixture_session() a1 = sess.query(Address).first() eq_(a1.username, "jack") sess = fixture_session() subq = sess.query(Address).subquery() aa = aliased(Address, subq) a1 = sess.query(aa).first() eq_(a1.username, "jack")
ExternalColumnsTest
python
scipy__scipy
scipy/sparse/_lil.py
{ "start": 486, "end": 16732 }
class ____(_spbase, IndexMixin): _format = 'lil' def __init__(self, arg1, shape=None, dtype=None, copy=False, *, maxprint=None): _spbase.__init__(self, arg1, maxprint=maxprint) self.dtype = getdtype(dtype, arg1, default=float) # First get the shape if issparse(arg1): if arg1.format == "lil" and copy: A = arg1.copy() else: A = arg1.tolil() if dtype is not None: newdtype = getdtype(dtype) A = A.astype(newdtype, copy=False) self._shape = check_shape(A.shape) self.dtype = A.dtype self.rows = A.rows self.data = A.data elif isinstance(arg1,tuple): if isshape(arg1): if shape is not None: raise ValueError('invalid use of shape parameter') M, N = arg1 self._shape = check_shape((M, N)) self.rows = np.empty((M,), dtype=object) self.data = np.empty((M,), dtype=object) for i in range(M): self.rows[i] = [] self.data[i] = [] else: raise TypeError('unrecognized lil_array constructor usage') else: # assume A is dense try: A = self._ascontainer(arg1) except TypeError as e: raise TypeError('unsupported matrix type') from e if isinstance(self, sparray) and A.ndim != 2: raise ValueError(f"LIL arrays don't support {A.ndim}D input. Use 2D") A = self._csr_container(A, dtype=dtype).tolil() self._shape = check_shape(A.shape) self.dtype = getdtype(A.dtype) self.rows = A.rows self.data = A.data def __iadd__(self,other): self[:,:] = self + other return self def __isub__(self,other): self[:,:] = self - other return self def __imul__(self,other): if isscalarlike(other): self[:,:] = self * other return self else: return NotImplemented def __itruediv__(self,other): if isscalarlike(other): self[:,:] = self / other return self else: return NotImplemented # Whenever the dimensions change, empty lists should be created for each # row def _getnnz(self, axis=None): if axis is None: return sum([len(rowvals) for rowvals in self.data]) if axis < 0: axis += 2 if axis == 0: out = np.zeros(self.shape[1], dtype=np.intp) for row in self.rows: out[row] += 1 return out elif axis == 1: return np.array([len(rowvals) for rowvals in self.data], dtype=np.intp) else: raise ValueError('axis out of bounds') _getnnz.__doc__ = _spbase._getnnz.__doc__ def count_nonzero(self, axis=None): if axis is None: return sum(np.count_nonzero(rowvals) for rowvals in self.data) if axis < 0: axis += 2 if axis == 0: out = np.zeros(self.shape[1], dtype=np.intp) for row, data in zip(self.rows, self.data): mask = [c for c, d in zip(row, data) if d != 0] out[mask] += 1 return out elif axis == 1: return np.array( [np.count_nonzero(rowvals) for rowvals in self.data], dtype=np.intp, ) else: raise ValueError('axis out of bounds') count_nonzero.__doc__ = _spbase.count_nonzero.__doc__ def getrowview(self, i): """Returns a view of the 'i'th row (without copying). """ new = self._lil_container((1, self.shape[1]), dtype=self.dtype) new.rows[0] = self.rows[i] new.data[0] = self.data[i] return new def getrow(self, i): """Returns a copy of the 'i'th row. """ M, N = self.shape if i < 0: i += M if i < 0 or i >= M: raise IndexError('row index out of bounds') new = self._lil_container((1, N), dtype=self.dtype) new.rows[0] = self.rows[i][:] new.data[0] = self.data[i][:] return new def __getitem__(self, key): # Fast path for simple (int, int) indexing. if (isinstance(key, tuple) and len(key) == 2 and isinstance(key[0], INT_TYPES) and isinstance(key[1], INT_TYPES)): # lil_get1 handles validation for us. return self._get_intXint(*key) # Everything else takes the normal path. return IndexMixin.__getitem__(self, key) def _get_intXint(self, row, col): v = _csparsetools.lil_get1(self.shape[0], self.shape[1], self.rows, self.data, row, col) return self.dtype.type(v) def _get_sliceXint(self, row, col): row = range(*row.indices(self.shape[0])) return self._get_row_ranges(row, slice(col, col+1)) def _get_arrayXint(self, row, col): res = self._get_row_ranges(row.ravel(), slice(col, col+1)) if row.ndim > 1: return res.reshape(row.shape) return res def _get_intXslice(self, row, col): return self._get_row_ranges((row,), col) def _get_sliceXslice(self, row, col): row = range(*row.indices(self.shape[0])) return self._get_row_ranges(row, col) def _get_arrayXslice(self, row, col): return self._get_row_ranges(row, col) def _get_intXarray(self, row, col): row = np.array(row, dtype=col.dtype, ndmin=1) return self._get_columnXarray(row, col) def _get_sliceXarray(self, row, col): row = np.arange(*row.indices(self.shape[0])) return self._get_columnXarray(row, col) def _get_columnXarray(self, row, col): # outer indexing row, col = _broadcast_arrays(row[:,None], col) return self._get_arrayXarray(row, col) def _get_arrayXarray(self, row, col): # inner indexing i, j = map(np.atleast_2d, _prepare_index_for_memoryview(row, col)) new = self._lil_container(i.shape, dtype=self.dtype) _csparsetools.lil_fancy_get(self.shape[0], self.shape[1], self.rows, self.data, new.rows, new.data, i, j) return new def _get_row_ranges(self, rows, col_slice): """ Fast path for indexing in the case where column index is slice. This gains performance improvement over brute force by more efficient skipping of zeros, by accessing the elements column-wise in order. Parameters ---------- rows : sequence or range Rows indexed. If range, must be within valid bounds. col_slice : slice Columns indexed """ j_start, j_stop, j_stride = col_slice.indices(self.shape[1]) col_range = range(j_start, j_stop, j_stride) nj = len(col_range) new = self._lil_container((len(rows), nj), dtype=self.dtype) _csparsetools.lil_get_row_ranges(self.shape[0], self.shape[1], self.rows, self.data, new.rows, new.data, rows, j_start, j_stop, j_stride, nj) return new def _set_intXint(self, row, col, x): _csparsetools.lil_insert(self.shape[0], self.shape[1], self.rows, self.data, row, col, x) def _set_arrayXarray(self, row, col, x): i, j, x = map(np.atleast_2d, _prepare_index_for_memoryview(row, col, x)) _csparsetools.lil_fancy_set(self.shape[0], self.shape[1], self.rows, self.data, i, j, x) def _set_arrayXarray_sparse(self, row, col, x): # Fall back to densifying x x = np.asarray(x.toarray(), dtype=self.dtype) x, _ = _broadcast_arrays(x, row) self._set_arrayXarray(row, col, x) def __setitem__(self, key, x): if isinstance(key, tuple) and len(key) == 2: row, col = key # Fast path for simple (int, int) indexing. if isinstance(row, INT_TYPES) and isinstance(col, INT_TYPES): if issparse(x): x = x.toarray() if isinstance(x, np.ndarray): x = x.item() x = self.dtype.type(x) if x.size > 1: raise ValueError("Trying to assign a sequence to an item") return self._set_intXint(row, col, x) # Fast path for full-matrix sparse assignment. if (isinstance(row, slice) and isinstance(col, slice) and row == slice(None) and col == slice(None) and issparse(x) and x.shape == self.shape): x = self._lil_container(x, dtype=self.dtype) self.rows = x.rows self.data = x.data return # Everything else takes the normal path. IndexMixin.__setitem__(self, key, x) def _mul_scalar(self, other): if other == 0: # Multiply by zero: return the zero matrix new = self._lil_container(self.shape, dtype=self.dtype) else: res_dtype = upcast_scalar(self.dtype, other) new = self.astype(res_dtype) # sure to make a copy # Multiply this scalar by every element. for j, rowvals in enumerate(new.data): new.data[j] = [val*other for val in rowvals] return new def __truediv__(self, other): # self / other if isscalarlike(other): new = self.copy() new.dtype = np.result_type(self, other) # Divide every element by this scalar for j, rowvals in enumerate(new.data): new.data[j] = [val/other for val in rowvals] return new else: return self.tocsr() / other def copy(self): M, N = self.shape new = self._lil_container(self.shape, dtype=self.dtype) # This is ~14x faster than calling deepcopy() on rows and data. _csparsetools.lil_get_row_ranges(M, N, self.rows, self.data, new.rows, new.data, range(M), 0, N, 1, N) return new copy.__doc__ = _spbase.copy.__doc__ def reshape(self, *args, **kwargs): shape = check_shape(args, self.shape) order, copy = check_reshape_kwargs(kwargs) # Return early if reshape is not required if shape == self.shape: if copy: return self.copy() else: return self new = self._lil_container(shape, dtype=self.dtype) if order == 'C': ncols = self.shape[1] for i, row in enumerate(self.rows): for col, j in enumerate(row): new_r, new_c = np.unravel_index(i * ncols + j, shape) new[new_r, new_c] = self[i, j] elif order == 'F': nrows = self.shape[0] for i, row in enumerate(self.rows): for col, j in enumerate(row): new_r, new_c = np.unravel_index(i + j * nrows, shape, order) new[new_r, new_c] = self[i, j] else: raise ValueError("'order' must be 'C' or 'F'") return new reshape.__doc__ = _spbase.reshape.__doc__ def resize(self, *shape): shape = check_shape(shape) new_M, new_N = shape M, N = self.shape if new_M < M: self.rows = self.rows[:new_M] self.data = self.data[:new_M] elif new_M > M: self.rows = np.resize(self.rows, new_M) self.data = np.resize(self.data, new_M) for i in range(M, new_M): self.rows[i] = [] self.data[i] = [] if new_N < N: for row, data in zip(self.rows, self.data): trunc = bisect_left(row, new_N) del row[trunc:] del data[trunc:] self._shape = shape resize.__doc__ = _spbase.resize.__doc__ def toarray(self, order=None, out=None): d = self._process_toarray_args(order, out) for i, row in enumerate(self.rows): for pos, j in enumerate(row): d[i, j] = self.data[i][pos] return d toarray.__doc__ = _spbase.toarray.__doc__ def transpose(self, axes=None, copy=False): return self.tocsr(copy=copy).transpose(axes=axes, copy=False).tolil(copy=False) transpose.__doc__ = _spbase.transpose.__doc__ def tolil(self, copy=False): if copy: return self.copy() else: return self tolil.__doc__ = _spbase.tolil.__doc__ def tocsr(self, copy=False): M, N = self.shape if M == 0 or N == 0: return self._csr_container((M, N), dtype=self.dtype) # construct indptr array if M*N <= np.iinfo(np.int32).max: # fast path: it is known that 64-bit indexing will not be needed. idx_dtype = np.int32 indptr = np.empty(M + 1, dtype=idx_dtype) indptr[0] = 0 _csparsetools.lil_get_lengths(self.rows, indptr[1:]) np.cumsum(indptr, out=indptr) nnz = indptr[-1] else: idx_dtype = self._get_index_dtype(maxval=N) lengths = np.empty(M, dtype=idx_dtype) _csparsetools.lil_get_lengths(self.rows, lengths) nnz = lengths.sum(dtype=np.int64) idx_dtype = self._get_index_dtype(maxval=max(N, nnz)) indptr = np.empty(M + 1, dtype=idx_dtype) indptr[0] = 0 np.cumsum(lengths, dtype=idx_dtype, out=indptr[1:]) indices = np.empty(nnz, dtype=idx_dtype) data = np.empty(nnz, dtype=self.dtype) _csparsetools.lil_flatten_to_array(self.rows, indices) _csparsetools.lil_flatten_to_array(self.data, data) # init csr matrix return self._csr_container((data, indices, indptr), shape=self.shape) tocsr.__doc__ = _spbase.tocsr.__doc__ def _prepare_index_for_memoryview(i, j, x=None): """ Convert index and data arrays to form suitable for passing to the Cython fancy getset routines. The conversions are necessary since to (i) ensure the integer index arrays are in one of the accepted types, and (ii) to ensure the arrays are writable so that Cython memoryview support doesn't choke on them. Parameters ---------- i, j Index arrays x : optional Data arrays Returns ------- i, j, x Re-formatted arrays (x is omitted, if input was None) """ if i.dtype > j.dtype: j = j.astype(i.dtype) elif i.dtype < j.dtype: i = i.astype(j.dtype) if not i.flags.writeable or i.dtype not in (np.int32, np.int64): i = i.astype(np.intp) if not j.flags.writeable or j.dtype not in (np.int32, np.int64): j = j.astype(np.intp) if x is not None: if not x.flags.writeable: x = x.copy() return i, j, x else: return i, j def isspmatrix_lil(x): """Is `x` of lil_matrix type? Parameters ---------- x object to check for being a lil matrix Returns ------- bool True if `x` is a lil matrix, False otherwise Examples -------- >>> from scipy.sparse import lil_array, lil_matrix, coo_matrix, isspmatrix_lil >>> isspmatrix_lil(lil_matrix([[5]])) True >>> isspmatrix_lil(lil_array([[5]])) False >>> isspmatrix_lil(coo_matrix([[5]])) False """ return isinstance(x, lil_matrix) # This namespace class separates array from matrix with isinstance
_lil_base
python
Textualize__rich
examples/attrs.py
{ "start": 184, "end": 257 }
class ____: x: float y: float z: float = 0 @attr.define
Point3D
python
pypa__virtualenv
src/virtualenv/create/via_global_ref/builtin/via_global_self_do.py
{ "start": 339, "end": 475 }
class ____(ViaGlobalRefMeta): def __init__(self) -> None: super().__init__() self.sources = []
BuiltinViaGlobalRefMeta
python
docker__docker-py
docker/types/services.py
{ "start": 20646, "end": 21230 }
class ____(dict): """ Indicates which driver to use, as well as its configuration. Can be used as ``log_driver`` in a :py:class:`~docker.types.ContainerSpec`, for the `driver_config` in a volume :py:class:`~docker.types.Mount`, or as the driver object in :py:meth:`create_secret`. Args: name (string): Name of the driver to use. options (dict): Driver-specific options. Default: ``None``. """ def __init__(self, name, options=None): self['Name'] = name if options: self['Options'] = options
DriverConfig
python
has2k1__plotnine
plotnine/iapi.py
{ "start": 4469, "end": 5324 }
class ____: """ Layout information """ panel_index: int panel: int row: int col: int scale_x: int scale_y: int axis_x: bool axis_y: bool variables: dict[str, Any] nrow: int ncol: int @property def is_left(self) -> bool: """ Return True if panel is on the left """ return self.col == 1 @property def is_right(self) -> bool: """ Return True if panel is on the right """ return self.col == self.ncol @property def is_top(self) -> bool: """ Return True if panel is at the top """ return self.row == 1 @property def is_bottom(self) -> bool: """ Return True if Panel is at the bottom """ return self.row == self.nrow @dataclass
layout_details
python
doocs__leetcode
solution/3500-3599/3527.Find the Most Common Response/Solution.py
{ "start": 0, "end": 362 }
class ____: def findCommonResponse(self, responses: List[List[str]]) -> str: cnt = Counter() for ws in responses: for w in set(ws): cnt[w] += 1 ans = responses[0][0] for w, x in cnt.items(): if cnt[ans] < x or (cnt[ans] == x and w < ans): ans = w return ans
Solution
python
allegroai__clearml
clearml/backend_api/session/client/client.py
{ "start": 8884, "end": 13551 }
class ____(object): """ Represent a server object. Enables calls like: >>> client = APIClient() >>> entity = client.service.get_by_id(entity_id) >>> entity.action(**kwargs) instead of: >>> client.service.action(id=entity_id, **kwargs) """ @property @abc.abstractmethod def entity_name(self) -> Text: """ Singular name of entity """ pass @property @abc.abstractmethod def get_by_id_request(self) -> Type[APIRequest]: """ get_by_id request class """ pass def __init__(self, service: "Service", data: Any) -> None: self._service = service self.data = getattr(data, self.entity_name, data) self.__doc__ = self.data.__doc__ def fetch(self) -> None: """ Update the entity data from the server. """ result = self._service.session.send(self.get_by_id_request(self.data.id)) self.data = getattr(result.response, self.entity_name) def _get_default_kwargs(self) -> Dict[Text, Any]: return {self.entity_name: self.data.id} def __getattr__(self, attr: Text) -> Any: """ Inject the entity's ID to the method call. All missing properties are assumed to be functions. """ try: return getattr(self.data, attr) except AttributeError: pass func = getattr(self._service, attr) if not callable(func): return func @wrap_request_class(func) def new_func(*args: Any, **kwargs: Any) -> Any: kwargs = dict(self._get_default_kwargs(), **kwargs) return func(*args, **kwargs) return new_func def __dir__(self) -> List[str]: """ Add ``self._service``'s methods to ``dir`` result. """ try: dir_ = super(Entity, self).__dir__ except AttributeError: base = self.__dict__ else: base = dir_() return list(set(base).union(dir(self._service), dir(self.data))) def __repr__(self) -> Text: """ Display entity type, ID, and - if available - name. """ parts = (type(self).__name__, ": ", "id={}".format(self.data.id)) try: parts += (", ", 'name="{}"'.format(self.data.name)) except AttributeError: pass return "<{}>".format("".join(parts)) def wrap_request_class(cls) -> Type: return wraps(cls, assigned=tuple(WRAPPER_ASSIGNMENTS) + ("from_dict",)) def make_action(service: "Service", request_cls: Type["APIRequest"]) -> Callable: # noinspection PyProtectedMember action = request_cls._action try: get_by_id_request = service.GetByIdRequest except AttributeError: get_by_id_request = None wrap = wrap_request_class(request_cls) if action not in ["get_all", "get_all_ex", "get_by_id", "create"]: @wrap def new_func(self, *args: Any, **kwargs: Any) -> Response: return Response(self.session.send(request_cls(*args, **kwargs))) new_func.__name__ = new_func.__qualname__ = action return new_func entity_name = api_entity_name(service) class_name = entity_class_name(service).capitalize() properties = { "__module__": __name__, "entity_name": entity_name.lower(), "get_by_id_request": get_by_id_request, } entity = type(str(class_name), (Entity,), properties) if action == "get_by_id": @wrap def get(self, *args: Any, **kwargs: Any) -> entity: return entity(self, self.session.send(request_cls(*args, **kwargs)).response) elif action == "create": @wrap def get(self, *args: Any, **kwargs: Any) -> entity: return entity( self, Namespace(id=self.session.send(request_cls(*args, **kwargs)).response.id), ) elif action in ["get_all", "get_all_ex"]: # noinspection PyProtectedMember for dest in service.response_mapping[request_cls]._get_data_props().keys(): if dest != "scroll_id": break @wrap def get(self, *args: Any, **kwargs: Any) -> TableResponse: return TableResponse( service=self, entity=entity, result=self.session.send(request_cls(*args, **kwargs)), dest=dest, fields=kwargs.pop("only_fields", None), ) else: assert False get.__name__ = get.__qualname__ = action return get @six.add_metaclass(abc.ABCMeta)
Entity
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/conv_test.py
{ "start": 2990, "end": 4152 }
class ____(op_bench.TorchBenchmarkBase): def init(self, IC, OC, kernel, stride, N, H, W, G, pad, device): self.inputs = {"input": torch.rand(N, IC, H, W, device=device)} self.conv2d = nn.Conv2d( IC, OC, kernel, stride=stride, groups=G, padding=pad ).to(device=device) self.set_module_name("Conv2d") def forward(self, input): return self.conv2d(input) def get_memory_traffic_bytes(self): """Calculate memory traffic for Conv2d: read(input + weight) + write(output)""" input_tensor = self.inputs["input"] # Run forward to get output shape with torch.no_grad(): output = self.conv2d(input_tensor) bytes_per_element = input_tensor.element_size() # Input: N × IC × H × W input_elements = input_tensor.numel() # Weight: OC × (IC/G) × kernel × kernel weight_elements = self.conv2d.weight.numel() # Output: N × OC × H_out × W_out output_elements = output.numel() total_elements = input_elements + weight_elements + output_elements return total_elements * bytes_per_element
Conv2dBenchmark
python
astropy__astropy
astropy/table/tests/test_pprint.py
{ "start": 28862, "end": 36461 }
class ____: """Tests of show and hide table columns""" def setup_method(self): self.t = simple_table(size=1, cols=4, kinds="i") @pytest.mark.parametrize("attr", ("pprint_exclude_names", "pprint_include_names")) def test_basic(self, attr): t = self.t assert ( repr(getattr(Table, attr)) == f"<PprintIncludeExclude name={attr} default=None>" ) t_show_hide = getattr(t, attr) assert repr(t_show_hide) == f"<PprintIncludeExclude name={attr} value=None>" # Default value is None assert t_show_hide() is None def test_slice(self): t = self.t t.pprint_include_names = "a" t.pprint_exclude_names = "b" t2 = t[0:1] assert t2.pprint_include_names() == ("a",) assert t2.pprint_exclude_names() == ("b",) def test_copy(self): t = self.t t.pprint_include_names = "a" t.pprint_exclude_names = "b" t2 = t.copy() assert t2.pprint_include_names() == ("a",) assert t2.pprint_exclude_names() == ("b",) t2.pprint_include_names = "c" t2.pprint_exclude_names = "d" assert t.pprint_include_names() == ("a",) assert t.pprint_exclude_names() == ("b",) assert t2.pprint_include_names() == ("c",) assert t2.pprint_exclude_names() == ("d",) @pytest.mark.parametrize("attr", ("pprint_exclude_names", "pprint_include_names")) @pytest.mark.parametrize("value", ("z", ["a", "z"])) def test_setting(self, attr, value): t = self.t t_show_hide = getattr(t, attr) # Expected attribute value ('z',) or ('a', 'z') exp = (value,) if isinstance(value, str) else tuple(value) # Context manager, can include column names that do not exist with t_show_hide.set(value): assert t_show_hide() == exp assert t.meta["__attributes__"] == {attr: exp} assert t_show_hide() is None # Setting back to None clears out meta assert t.meta == {} # Do `t.pprint_include_names/hide = value` setattr(t, attr, value) assert t_show_hide() == exp # Clear attribute t_show_hide.set(None) assert t_show_hide() is None # Now use set() method t_show_hide.set(value) assert t_show_hide() == exp with t_show_hide.set(None): assert t_show_hide() is None assert t.meta == {} assert t_show_hide() == exp @pytest.mark.parametrize("attr", ("pprint_exclude_names", "pprint_include_names")) @pytest.mark.parametrize("value", ("z", ["a", "z"], ("a", "z"))) def test_add_remove(self, attr, value): t = self.t t_show_hide = getattr(t, attr) # Expected attribute value ('z') or ('a', 'z') exp = (value,) if isinstance(value, str) else tuple(value) # add() method for str or list of str t_show_hide.add(value) assert t_show_hide() == exp # Adding twice has no effect t_show_hide.add(value) assert t_show_hide() == exp # Remove values (str or list of str). Reverts to None if all names are # removed. t_show_hide.remove(value) assert t_show_hide() is None # Remove just one name, possibly leaving a name. t_show_hide.add(value) t_show_hide.remove("z") assert t_show_hide() == (None if value == "z" else ("a",)) # Cannot remove name not in the list t_show_hide.set(["a", "z"]) with pytest.raises(ValueError, match=f"x not in {attr}"): t_show_hide.remove(("x", "z")) @pytest.mark.parametrize("attr", ("pprint_exclude_names", "pprint_include_names")) def test_rename(self, attr): t = self.t t_hide_show = getattr(t, attr) t_hide_show.set(["a", "b"]) t.rename_column("a", "aa") assert t_hide_show() == ("aa", "b") @pytest.mark.parametrize("attr", ("pprint_exclude_names", "pprint_include_names")) def test_remove(self, attr): t = self.t t_hide_show = getattr(t, attr) t_hide_show.set(["a", "b"]) del t["a"] assert t_hide_show() == ("b",) def test_serialization(self): # Serialization works for ECSV. Currently fails for FITS, works with # HDF5. t = self.t t.pprint_exclude_names = ["a", "y"] t.pprint_include_names = ["b", "z"] out = StringIO() ascii.write(t, out, format="ecsv") t2 = ascii.read(out.getvalue(), format="ecsv") assert t2.pprint_exclude_names() == ("a", "y") assert t2.pprint_include_names() == ("b", "z") def test_output(self): """Test that pprint_include/exclude_names actually changes the print output""" t = self.t exp = [ " b d ", "--- ---", " 2 4", ] with t.pprint_exclude_names.set(["a", "c"]): out = t.pformat() assert out == exp with t.pprint_include_names.set(["b", "d"]): out = t.pformat() assert out == exp with t.pprint_exclude_names.set(["a", "c"]): out = t.pformat() assert out == exp with t.pprint_include_names.set(["b", "d"]): out = t.pformat() assert out == exp with ( t.pprint_include_names.set(["b", "c", "d"]), t.pprint_exclude_names.set(["c"]), ): out = t.pformat() assert out == exp def test_output_globs(self): """Test that pprint_include/exclude_names works with globs (fnmatch)""" t = self.t t["a2"] = 1 t["a23"] = 2 # Show only the a* columns exp = [ " a a2 a23", "--- --- ---", " 1 1 2", ] with t.pprint_include_names.set("a*"): out = t.pformat() assert out == exp # Show a* but exclude a?? exp = [ " a a2", "--- ---", " 1 1", ] with t.pprint_include_names.set("a*"), t.pprint_exclude_names.set("a??"): out = t.pformat() assert out == exp # Exclude a?? exp = [ " a b c d a2", "--- --- --- --- ---", " 1 2 3 4 1", ] with t.pprint_exclude_names.set("a??"): out = t.pformat() assert out == exp def test_embedded_newline_tab(): """Newlines and tabs are escaped in table repr""" t = Table( rows=[ ["a", "b \n c \t \n d"], ["x", "y\n"], ] ) exp = [ r"col0 col1 ", r"---- --------------", r" a b \n c \t \n d", r" x y\n", ] assert t.pformat() == exp def test_multidims_with_zero_dim(): """Test of fix for #13836 when a zero-dim column is present""" t = Table() t["a"] = ["a", "b"] t["b"] = np.ones(shape=(2, 0, 1), dtype=np.float64) exp = [ " a b ", "str1 float64[0,1]", "---- ------------", " a ", " b ", ] assert t.pformat(show_dtype=True) == exp def test_zero_length_string(): data = np.array([("", 12)], dtype=[("a", "S"), ("b", "i4")]) t = Table(data, copy=False) exp = [ " a b ", "bytes0 int32", "------ -----", " 12", ] assert t.pformat(show_dtype=True) == exp
TestColumnsShowHide
python
pandas-dev__pandas
pandas/tests/frame/test_query_eval.py
{ "start": 16420, "end": 31681 }
class ____: @pytest.fixture def engine(self): return "numexpr" @pytest.fixture def parser(self): return "pandas" def test_date_query_with_attribute_access(self, engine, parser): skip_if_no_pandas_parser(parser) df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) df["dates1"] = date_range("1/1/2012", periods=5) df["dates2"] = date_range("1/1/2013", periods=5) df["dates3"] = date_range("1/1/2014", periods=5) res = df.query( "@df.dates1 < 20130101 < @df.dates3", engine=engine, parser=parser ) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] tm.assert_frame_equal(res, expec) def test_date_query_no_attribute_access(self, engine, parser): df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) df["dates1"] = date_range("1/1/2012", periods=5) df["dates2"] = date_range("1/1/2013", periods=5) df["dates3"] = date_range("1/1/2014", periods=5) res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] tm.assert_frame_equal(res, expec) def test_date_query_with_NaT(self, engine, parser): n = 10 df = DataFrame(np.random.default_rng(2).standard_normal((n, 3))) df["dates1"] = date_range("1/1/2012", periods=n) df["dates2"] = date_range("1/1/2013", periods=n) df["dates3"] = date_range("1/1/2014", periods=n) df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT df.loc[np.random.default_rng(2).random(n) > 0.5, "dates3"] = pd.NaT res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.dates1 < "20130101") & ("20130101" < df.dates3)] tm.assert_frame_equal(res, expec) def test_date_index_query(self, engine, parser): n = 10 df = DataFrame(np.random.default_rng(2).standard_normal((n, 3))) df["dates1"] = date_range("1/1/2012", periods=n) df["dates3"] = date_range("1/1/2014", periods=n) return_value = df.set_index("dates1", inplace=True, drop=True) assert return_value is None res = df.query("index < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.index < "20130101") & ("20130101" < df.dates3)] tm.assert_frame_equal(res, expec) def test_date_index_query_with_NaT(self, engine, parser): n = 10 # Cast to object to avoid implicit cast when setting entry to pd.NaT below df = DataFrame(np.random.default_rng(2).standard_normal((n, 3))).astype( {0: object} ) df["dates1"] = date_range("1/1/2012", periods=n) df["dates3"] = date_range("1/1/2014", periods=n) df.iloc[0, 0] = pd.NaT return_value = df.set_index("dates1", inplace=True, drop=True) assert return_value is None res = df.query("index < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.index < "20130101") & ("20130101" < df.dates3)] tm.assert_frame_equal(res, expec) def test_date_index_query_with_NaT_duplicates(self, engine, parser): n = 10 d = {} d["dates1"] = date_range("1/1/2012", periods=n) d["dates3"] = date_range("1/1/2014", periods=n) df = DataFrame(d) df.loc[np.random.default_rng(2).random(n) > 0.5, "dates1"] = pd.NaT return_value = df.set_index("dates1", inplace=True, drop=True) assert return_value is None res = df.query("dates1 < 20130101 < dates3", engine=engine, parser=parser) expec = df[(df.index.to_series() < "20130101") & ("20130101" < df.dates3)] tm.assert_frame_equal(res, expec) def test_date_query_with_non_date(self, engine, parser): n = 10 df = DataFrame( {"dates": date_range("1/1/2012", periods=n, unit="ns"), "nondate": np.arange(n)} ) result = df.query("dates == nondate", parser=parser, engine=engine) assert len(result) == 0 result = df.query("dates != nondate", parser=parser, engine=engine) tm.assert_frame_equal(result, df) msg = r"Invalid comparison between dtype=datetime64\[ns\] and ndarray" for op in ["<", ">", "<=", ">="]: with pytest.raises(TypeError, match=msg): df.query(f"dates {op} nondate", parser=parser, engine=engine) def test_query_syntax_error(self, engine, parser): df = DataFrame({"i": range(10), "+": range(3, 13), "r": range(4, 14)}) msg = "invalid syntax" with pytest.raises(SyntaxError, match=msg): df.query("i - +", engine=engine, parser=parser) def test_query_scope(self, engine, parser): skip_if_no_pandas_parser(parser) df = DataFrame( np.random.default_rng(2).standard_normal((20, 2)), columns=list("ab") ) a, b = 1, 2 # noqa: F841 res = df.query("a > b", engine=engine, parser=parser) expected = df[df.a > df.b] tm.assert_frame_equal(res, expected) res = df.query("@a > b", engine=engine, parser=parser) expected = df[a > df.b] tm.assert_frame_equal(res, expected) # no local variable c with pytest.raises( UndefinedVariableError, match="local variable 'c' is not defined" ): df.query("@a > b > @c", engine=engine, parser=parser) # no column named 'c' with pytest.raises(UndefinedVariableError, match="name 'c' is not defined"): df.query("@a > b > c", engine=engine, parser=parser) def test_query_doesnt_pickup_local(self, engine, parser): n = m = 10 df = DataFrame( np.random.default_rng(2).integers(m, size=(n, 3)), columns=list("abc") ) # we don't pick up the local 'sin' with pytest.raises(UndefinedVariableError, match="name 'sin' is not defined"): df.query("sin > 5", engine=engine, parser=parser) def test_query_builtin(self, engine, parser): n = m = 10 df = DataFrame( np.random.default_rng(2).integers(m, size=(n, 3)), columns=list("abc") ) df.index.name = "sin" msg = "Variables in expression.+" with pytest.raises(NumExprClobberingError, match=msg): df.query("sin > 5", engine=engine, parser=parser) def test_query(self, engine, parser): df = DataFrame( np.random.default_rng(2).standard_normal((10, 3)), columns=["a", "b", "c"] ) tm.assert_frame_equal( df.query("a < b", engine=engine, parser=parser), df[df.a < df.b] ) tm.assert_frame_equal( df.query("a + b > b * c", engine=engine, parser=parser), df[df.a + df.b > df.b * df.c], ) def test_query_index_with_name(self, engine, parser): df = DataFrame( np.random.default_rng(2).integers(10, size=(10, 3)), index=Index(range(10), name="blob"), columns=["a", "b", "c"], ) res = df.query("(blob < 5) & (a < b)", engine=engine, parser=parser) expec = df[(df.index < 5) & (df.a < df.b)] tm.assert_frame_equal(res, expec) res = df.query("blob < b", engine=engine, parser=parser) expec = df[df.index < df.b] tm.assert_frame_equal(res, expec) def test_query_index_without_name(self, engine, parser): df = DataFrame( np.random.default_rng(2).integers(10, size=(10, 3)), index=range(10), columns=["a", "b", "c"], ) # "index" should refer to the index res = df.query("index < b", engine=engine, parser=parser) expec = df[df.index < df.b] tm.assert_frame_equal(res, expec) # test against a scalar res = df.query("index < 5", engine=engine, parser=parser) expec = df[df.index < 5] tm.assert_frame_equal(res, expec) def test_nested_scope(self, engine, parser): skip_if_no_pandas_parser(parser) df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) df2 = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) expected = df[(df > 0) & (df2 > 0)] result = df.query("(@df > 0) & (@df2 > 0)", engine=engine, parser=parser) tm.assert_frame_equal(result, expected) result = pd.eval("df[df > 0 and df2 > 0]", engine=engine, parser=parser) tm.assert_frame_equal(result, expected) result = pd.eval( "df[df > 0 and df2 > 0 and df[df > 0] > 0]", engine=engine, parser=parser ) expected = df[(df > 0) & (df2 > 0) & (df[df > 0] > 0)] tm.assert_frame_equal(result, expected) result = pd.eval("df[(df>0) & (df2>0)]", engine=engine, parser=parser) expected = df.query("(@df>0) & (@df2>0)", engine=engine, parser=parser) tm.assert_frame_equal(result, expected) def test_nested_raises_on_local_self_reference(self, engine, parser): df = DataFrame(np.random.default_rng(2).standard_normal((5, 3))) # can't reference ourself b/c we're a local so @ is necessary with pytest.raises(UndefinedVariableError, match="name 'df' is not defined"): df.query("df > 0", engine=engine, parser=parser) def test_local_syntax(self, engine, parser): skip_if_no_pandas_parser(parser) df = DataFrame( np.random.default_rng(2).standard_normal((100, 10)), columns=list("abcdefghij"), ) b = 1 expect = df[df.a < b] result = df.query("a < @b", engine=engine, parser=parser) tm.assert_frame_equal(result, expect) expect = df[df.a < df.b] result = df.query("a < b", engine=engine, parser=parser) tm.assert_frame_equal(result, expect) def test_chained_cmp_and_in(self, engine, parser): skip_if_no_pandas_parser(parser) cols = list("abc") df = DataFrame( np.random.default_rng(2).standard_normal((100, len(cols))), columns=cols ) res = df.query( "a < b < c and a not in b not in c", engine=engine, parser=parser ) ind = (df.a < df.b) & (df.b < df.c) & ~df.b.isin(df.a) & ~df.c.isin(df.b) expec = df[ind] tm.assert_frame_equal(res, expec) def test_local_variable_with_in(self, engine, parser): skip_if_no_pandas_parser(parser) a = Series(np.random.default_rng(2).integers(3, size=15), name="a") b = Series(np.random.default_rng(2).integers(10, size=15), name="b") df = DataFrame({"a": a, "b": b}) expected = df.loc[(df.b - 1).isin(a)] result = df.query("b - 1 in a", engine=engine, parser=parser) tm.assert_frame_equal(expected, result) b = Series(np.random.default_rng(2).integers(10, size=15), name="b") expected = df.loc[(b - 1).isin(a)] result = df.query("@b - 1 in a", engine=engine, parser=parser) tm.assert_frame_equal(expected, result) def test_at_inside_string(self, engine, parser): skip_if_no_pandas_parser(parser) c = 1 # noqa: F841 df = DataFrame({"a": ["a", "a", "b", "b", "@c", "@c"]}) result = df.query('a == "@c"', engine=engine, parser=parser) expected = df[df.a == "@c"] tm.assert_frame_equal(result, expected) def test_query_undefined_local(self): engine, parser = self.engine, self.parser skip_if_no_pandas_parser(parser) df = DataFrame(np.random.default_rng(2).random((10, 2)), columns=list("ab")) with pytest.raises( UndefinedVariableError, match="local variable 'c' is not defined" ): df.query("a == @c", engine=engine, parser=parser) def test_index_resolvers_come_after_columns_with_the_same_name( self, engine, parser ): n = 1 # noqa: F841 a = np.r_[20:101:20] df = DataFrame( {"index": a, "b": np.random.default_rng(2).standard_normal(a.size)} ) df.index.name = "index" result = df.query("index > 5", engine=engine, parser=parser) expected = df[df["index"] > 5] tm.assert_frame_equal(result, expected) df = DataFrame( {"index": a, "b": np.random.default_rng(2).standard_normal(a.size)} ) result = df.query("ilevel_0 > 5", engine=engine, parser=parser) expected = df.loc[df.index[df.index > 5]] tm.assert_frame_equal(result, expected) df = DataFrame({"a": a, "b": np.random.default_rng(2).standard_normal(a.size)}) df.index.name = "a" result = df.query("a > 5", engine=engine, parser=parser) expected = df[df.a > 5] tm.assert_frame_equal(result, expected) result = df.query("index > 5", engine=engine, parser=parser) expected = df.loc[df.index[df.index > 5]] tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("op, f", [["==", operator.eq], ["!=", operator.ne]]) def test_inf(self, op, f, engine, parser): n = 10 df = DataFrame( { "a": np.random.default_rng(2).random(n), "b": np.random.default_rng(2).random(n), } ) df.loc[::2, 0] = np.inf q = f"a {op} inf" expected = df[f(df.a, np.inf)] result = df.query(q, engine=engine, parser=parser) tm.assert_frame_equal(result, expected) def test_check_tz_aware_index_query(self, tz_aware_fixture): # https://github.com/pandas-dev/pandas/issues/29463 tz = tz_aware_fixture df_index = date_range( start="2019-01-01", freq="1D", periods=10, tz=tz, name="time" ) expected = DataFrame(index=df_index) df = DataFrame(index=df_index) result = df.query('"2018-01-03 00:00:00+00" < time') tm.assert_frame_equal(result, expected) expected = DataFrame(df_index) result = df.reset_index().query('"2018-01-03 00:00:00+00" < time') tm.assert_frame_equal(result, expected) def test_method_calls_in_query(self, engine, parser): # https://github.com/pandas-dev/pandas/issues/22435 n = 10 df = DataFrame( { "a": 2 * np.random.default_rng(2).random(n), "b": np.random.default_rng(2).random(n), } ) expected = df[df["a"].astype("int") == 0] result = df.query("a.astype('int') == 0", engine=engine, parser=parser) tm.assert_frame_equal(result, expected) df = DataFrame( { "a": np.where( np.random.default_rng(2).random(n) < 0.5, np.nan, np.random.default_rng(2).standard_normal(n), ), "b": np.random.default_rng(2).standard_normal(n), } ) expected = df[df["a"].notnull()] result = df.query("a.notnull()", engine=engine, parser=parser) tm.assert_frame_equal(result, expected) @td.skip_if_no("numexpr")
TestDataFrameQueryNumExprPandas
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/containers.py
{ "start": 46309, "end": 46631 }
class ____(Enum): """ Alignment of the Window content. Note that this is different from `HorizontalAlign` and `VerticalAlign`, which are used for the alignment of the child containers in respectively `VSplit` and `HSplit`. """ LEFT = "LEFT" RIGHT = "RIGHT" CENTER = "CENTER"
WindowAlign