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
dagster-io__dagster
helm/dagster/schema/schema/charts/dagster/subschema/daemon.py
{ "start": 1809, "end": 1938 }
class ____(BaseModel): useThreads: bool numWorkers: Optional[int] = None numSubmitWorkers: Optional[int] = None
Sensors
python
bokeh__bokeh
src/bokeh/events.py
{ "start": 20055, "end": 20445 }
class ____(PointEvent): ''' Announce the end of a pan event on a Bokeh plot. Attributes: sx (float) : x-coordinate of the event in *screen* space sy (float) : y-coordinate of the event in *screen* space x (float) : x-coordinate of the event in *data* space y (float) : y-coordinate of the event in *data* space ''' event_name = 'panend'
PanEnd
python
sphinx-doc__sphinx
sphinx/io.py
{ "start": 2261, "end": 3429 }
class ____(SphinxBaseReader): """A basic document reader for Sphinx.""" def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) warnings.warn( 'sphinx.io.SphinxStandaloneReader is deprecated', RemovedInSphinx10Warning, stacklevel=2, ) def _setup_transforms(self, transforms: list[type[Transform]], /) -> None: self.transforms = self.transforms + transforms def read(self, source: Input, parser: Parser, settings: Values) -> nodes.document: # type: ignore[type-arg] self.source = source if not self.parser: # type: ignore[has-type] self.parser = parser self.settings = settings self.input = self.read_source(settings.env) self.parse() return self.document def read_source(self, env: BuildEnvironment) -> str: """Read content from source and do post-process.""" content = self.source.read() # emit "source-read" event arg = [content] env.events.emit('source-read', env.current_document.docname, arg) return arg[0]
SphinxStandaloneReader
python
langchain-ai__langchain
libs/core/langchain_core/runnables/graph.py
{ "start": 3775, "end": 4137 }
class ____: """Schema for Hexadecimal color codes for different node types. Args: default: The default color code. first: The color code for the first node. last: The color code for the last node. """ default: str = "fill:#f2f0ff,line-height:1.2" first: str = "fill-opacity:0" last: str = "fill:#bfb6fc"
NodeStyles
python
dagster-io__dagster
examples/docs_snippets/docs_snippets/concepts/ops_jobs_graphs/unit_tests.py
{ "start": 7788, "end": 8284 }
class ____(ConfigurableResource): ... @asset def asset_requires_service(service: MyServiceResource): ... @asset def other_asset_requires_service(service: MyServiceResource): ... def test_assets_require_service(): # Mock objects can be provided directly. result = materialize_to_memory( [asset_requires_service, other_asset_requires_service], resources={"service": mock.MagicMock()}, ) assert result.success ... # end_materialize_resources
MyServiceResource
python
ray-project__ray
python/ray/dag/tests/experimental/test_torch_tensor_transport.py
{ "start": 20494, "end": 21572 }
class ____: """Tests worker to driver tensor transport with CPU device.""" def test_src_cpu_tensor(self, ray_start_regular): actor = Actor.remote() ref = run_worker_to_driver_dag(actor, "cpu", "cpu") tensor = ray.get(ref) assert str(tensor.device) == "cpu" @pytest.mark.skipif(not USE_GPU, reason="Test requires GPU") def test_src_gpu_tensor(self, ray_start_regular): actor = Actor.options(num_gpus=1).remote() ref = run_worker_to_driver_dag(actor, "cpu", "cuda") tensor = ray.get(ref) assert str(tensor.device) == "cpu" @pytest.mark.skipif(not USE_GPU, reason="Test requires GPU") def test_src_mix_tensors(self, ray_start_regular): actor = Actor.options(num_gpus=1).remote() ref = run_worker_to_driver_dag( actor, "cpu", {"cpu_tensor": "cpu", "gpu_tensor": "cuda"}, is_dict=True ) tensor = ray.get(ref) assert str(tensor["cpu_tensor"].device) == "cpu" assert str(tensor["gpu_tensor"].device) == "cpu"
TestWorkerToDriverDeviceCPU
python
huggingface__transformers
src/transformers/models/metaclip_2/modular_metaclip_2.py
{ "start": 30322, "end": 33176 }
class ____(CLIPVisionModelWithProjection): """ MetaClip2 vision model with a projection layer on top (a linear layer on top of the pooled output). This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Args: config ([`MetaClip2VisionConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, MetaClip2VisionModelWithProjection >>> model = MetaClip2VisionModelWithProjection.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> processor = AutoProcessor.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> outputs = model(**inputs) >>> image_embeds = outputs.image_embeds ```""" @check_model_inputs(tie_last_hidden_states=False) @auto_docstring def forward( self, pixel_values: Optional[torch.FloatTensor] = None, interpolate_pos_encoding: bool = False, **kwargs: Unpack[TransformersKwargs], ): r""" Examples: ```python >>> from PIL import Image >>> import requests >>> from transformers import AutoProcessor, MetaClip2VisionModelWithProjection >>> model = MetaClip2VisionModelWithProjection.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> processor = AutoProcessor.from_pretrained("facebook/metaclip-2-worldwide-huge-quickgelu") >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> image = Image.open(requests.get(url, stream=True).raw) >>> inputs = processor(images=image, return_tensors="pt") >>> outputs = model(**inputs) >>> image_embeds = outputs.image_embeds ```""" return super().forward( pixel_values=pixel_values, interpolate_pos_encoding=interpolate_pos_encoding, **kwargs, )
MetaClip2VisionModelWithProjection
python
getsentry__sentry
src/sentry/projects/services/project/serial.py
{ "start": 366, "end": 1482 }
class ____(serializers.Serializer[ProjectUpdateArgs]): name = serializers.CharField( help_text="The name for the project", max_length=200, required=False, ) slug = SentrySerializerSlugField( help_text="Uniquely identifies a project and is used for the interface.", max_length=PROJECT_SLUG_MAX_LENGTH, required=False, ) platform = serializers.CharField( help_text="The platform for the project", required=False, allow_null=True, allow_blank=True, ) external_id = serializers.CharField( help_text="The external ID for the project", required=False, allow_null=True, allow_blank=True, ) def serialize_project(project: Project) -> RpcProject: return RpcProject( id=project.id, slug=project.slug or "", name=project.name, organization_id=project.organization_id, status=project.status, first_event=project.first_event, platform=project.platform, external_id=project.external_id, )
ProjectUpdateArgsSerializer
python
pdm-project__pdm
src/pdm/models/repositories/lock.py
{ "start": 1093, "end": 14124 }
class ____(BaseRepository): def __init__( self, lockfile: Mapping[str, Any], sources: list[RepositoryConfig], environment: BaseEnvironment, env_spec: EnvSpec | None = None, ) -> None: super().__init__(sources, environment, env_spec=env_spec or environment.spec) self.packages: dict[CandidateKey, Package] = {} self.targets: list[EnvSpec] = [] self._read_lockfile(lockfile) def add_package(self, package: Package) -> None: self.packages[self._identify_candidate(package.candidate)] = package @cached_property def all_candidates(self) -> dict[str, list[Candidate]]: """Return a dict of all candidates grouped by the package name.""" result: dict[str, list[Candidate]] = {} for entry in self.packages.values(): result.setdefault(entry.candidate.identify(), []).append(entry.candidate) return result @property def candidates(self) -> dict[str, Candidate]: """Return a dict of candidates for the current environment.""" result: dict[str, Candidate] = {} for candidates in self.all_candidates.values(): for can in candidates: if can.req.marker: marker = exclude_multi(can.req.marker, "extras", "dependency_groups") if not marker.matches(self.env_spec): continue result[can.identify()] = can return result def _read_lockfile(self, lockfile: Mapping[str, Any]) -> None: if lockfile.get("lock-version"): return self._read_pylock(lockfile) else: return self._read_pdm_lock(lockfile) def _read_pylock(self, lockfile: Mapping[str, Any]) -> None: root = self.environment.project.root if "targets" in lockfile.get("tool", {}).get("pdm", {}): self.targets = [EnvSpec.from_spec(**t) for t in lockfile["tool"]["pdm"]["targets"]] else: for marker in lockfile.get("environments", []): # pragma: no cover self.targets.append(EnvSpec.from_marker(get_marker(cast(str, marker)))) with cd(root): for package in lockfile.get("packages", []): group_marker = AnyMarker() package_name = package.pop("name") req_dict: dict[str, str | bool] = {} if "version" in package: req_dict["version"] = f"=={package['version']}" if "marker" in package: package_marker = get_marker(cast(str, package["marker"])) req_marker = exclude_multi(package_marker, "extras", "dependency_groups") group_marker = package_marker.inner.only("extras", "dependency_groups") if not req_marker.is_any(): req_dict["marker"] = str(req_marker) if vcs := package.get("vcs"): # pragma: no cover req_dict[vcs["type"]] = vcs["url"] req_dict["ref"] = vcs.get("requested-revision") req_dict["revision"] = vcs.get("commit-id") req_dict["subdirectory"] = vcs.get("subdirectory") elif directory := package.get("directory"): # pragma: no cover req_dict["path"] = directory["path"] req_dict["editable"] = directory.get("editable", False) req_dict["subdirectory"] = directory.get("subdirectory") elif archive := package.get("archive"): # pragma: no cover req_dict["url"] = archive.get("url") req_dict["path"] = archive.get("path") req_dict["subdirectory"] = archive.get("subdirectory") req = Requirement.from_req_dict(package_name, req_dict) if req.is_file_or_url and req.path and not req.url: # type: ignore[attr-defined] req.url = root.joinpath(req.path).as_uri() # type: ignore[attr-defined] candidate = Candidate(req=req, name=package_name, version=package.get("version")) candidate.requires_python = package.get("requires-python", "") for artifact in itertools.chain( package.get("wheels", []), [sdist] if (sdist := package.get("sdist")) else [] ): algo, hash_value = next(iter(artifact["hashes"].items())) hash_item: FileHash = {"hash": f"{algo}:{hash_value}"} if "url" in artifact: hash_item["url"] = artifact["url"] if "name" in artifact: hash_item["file"] = artifact["name"] candidate.hashes.append(hash_item) dependencies = package.get("tool", {}).get("pdm", {}).get("dependencies") self.packages[self._identify_candidate(candidate)] = Package(candidate, dependencies, "", group_marker) def _read_pdm_lock(self, lockfile: Mapping[str, Any]) -> None: from pdm.project.lockfile import FLAG_CROSS_PLATFORM, FLAG_STATIC_URLS root = self.environment.project.root static_urls = FLAG_STATIC_URLS in self.environment.project.lockfile.strategy self.targets = [EnvSpec.from_spec(**t) for t in lockfile.get("metadata", {}).get("targets", [])] if not self.targets and lockfile: # pragma: no cover # XXX: for reading old lockfiles, to be removed in the future if FLAG_CROSS_PLATFORM in self.environment.project.lockfile.strategy: self.targets.append(self.environment.allow_all_spec) else: self.targets.append(self.environment.spec) with cd(root): for package in lockfile.get("package", []): version = package.get("version") if version: package["version"] = f"=={version}" package_name = package.pop("name") req_dict = { k: v for k, v in package.items() if k not in ("dependencies", "requires_python", "summary", "files", "targets") } req = Requirement.from_req_dict(package_name, req_dict) if req.is_file_or_url and req.path and not req.url: # type: ignore[attr-defined] req.url = root.joinpath(req.path).as_uri() # type: ignore[attr-defined] can = Candidate(req, name=package_name, version=version) can.hashes = package.get("files", []) if not static_urls and any("url" in f for f in can.hashes): raise PdmException( "Static URLs are not allowed in lockfile unless enabled by `pdm lock --static-urls`." ) can_id = self._identify_candidate(can) can.requires_python = package.get("requires_python", "") entry = Package( can, package.get("dependencies", []), package.get("summary", ""), ) self.packages[can_id] = entry def _identify_candidate(self, candidate: Candidate) -> CandidateKey: url: str | None = None if not candidate.req.is_named and candidate.link is not None: url = candidate.link.url_without_fragment url = self.environment.project.backend.expand_line(cast(str, url)) if url.startswith("file://"): path = posixpath.normpath(url_to_path(url)) url = Path(path).as_uri() return ( candidate.identify(), candidate.version if not url else None, url, candidate.req.editable, ) def _get_dependencies_from_lockfile(self, candidate: Candidate) -> CandidateMetadata: err = ( f"Missing package {candidate.identify()} from the lockfile, " "the lockfile may be broken. Run `pdm lock --update-reuse` to fix it." ) try: entry = self.packages[self._identify_candidate(candidate)] except KeyError as e: # pragma: no cover raise CandidateNotFound(err) from e if entry.dependencies is None: raise CandidateNotFound(f"Missing dependencies from the lockfile for package {candidate.identify()}") # populate candidate metadata if not candidate.name: candidate.name = entry.candidate.name if not candidate.version: candidate.version = entry.candidate.version if not candidate.requires_python: candidate.requires_python = entry.candidate.requires_python deps: list[Requirement] = [] for line in entry.dependencies: deps.append(parse_line(line)) return CandidateMetadata(deps, candidate.requires_python, entry.summary) def dependency_generators(self) -> Iterable[Callable[[Candidate], CandidateMetadata]]: return (self._get_dependencies_from_lockfile,) def _matching_entries(self, requirement: Requirement) -> Iterable[Package]: for key, entry in self.packages.items(): can_req = entry.candidate.req if requirement.name: if key[0] != requirement.identify(): continue else: assert isinstance(requirement, FileRequirement) if not isinstance(can_req, FileRequirement): continue if requirement.path and can_req.path: if requirement.path != can_req.path: continue elif key[2] is not None and key[2] != url_without_fragments(requirement.url): continue yield entry def find_candidates( self, requirement: Requirement, allow_prereleases: bool | None = None, ignore_requires_python: bool = False, minimal_version: bool = False, ) -> Iterable[Candidate]: if self.is_this_package(requirement): candidate = self.make_this_candidate(requirement) if candidate is not None: yield candidate return for entry in self._matching_entries(requirement): can = entry.candidate.copy_with(requirement) if not requirement.name: # make sure can.identify() won't return a randomly-generated name requirement.name = can.name yield can def get_hashes(self, candidate: Candidate) -> list[FileHash]: return candidate.hashes def evaluate_candidates(self, groups: Collection[str], evaluate_markers: bool = True) -> Iterable[Package]: extras, dependency_groups = self.environment.project.split_extras_groups(list(groups)) for package in self.packages.values(): can = package.candidate if evaluate_markers and can.req.marker and not can.req.marker.matches(self.env_spec): continue if not package.marker.evaluate({"extras": set(extras), "dependency_groups": set(dependency_groups)}): continue if can.req.groups and not any(g in can.req.groups for g in groups): continue yield package def merge_result(self, env_spec: EnvSpec, result: Iterable[Package]) -> None: if env_spec not in self.targets: self.targets.append(env_spec) for entry in result: key = self._identify_candidate(entry.candidate) existing = self.packages.get(key) if existing is None: self.packages[key] = entry else: # merge markers old_marker = existing.candidate.req.marker if old_marker is None or entry.candidate.req.marker is None: new_marker = None else: new_marker = old_marker | entry.candidate.req.marker bare_marker, py_spec = new_marker.split_pyspec() if py_spec.is_superset(self.environment.python_requires): new_marker = bare_marker if new_marker.is_any(): new_marker = None # merge groups new_groups = list(set(existing.candidate.req.groups) | set(entry.candidate.req.groups)) existing.candidate.req = dataclasses.replace( existing.candidate.req, marker=new_marker, groups=new_groups ) # merge file hashes for file in entry.candidate.hashes: if file not in existing.candidate.hashes: existing.candidate.hashes.append(file) # clear caches if "all_candidates" in self.__dict__: del self.__dict__["all_candidates"]
LockedRepository
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 30379, "end": 31240 }
class ____(torch.nn.Module): def __init__(self): super().__init__() self.layer = UnspecInlinableModule() self.step = 10 def forward(self, x: torch.Tensor) -> torch.Tensor: x = x + 1 return self.layer(x) + self.step def make_test(fn, expected_ops=None): def test_fn(self): return torch._dynamo.testing.standard_test( self, fn=fn, nargs=1, expected_ops=expected_ops ) fn.eval() return test_fn def temporary_tensor_subclass(torch_function=None): class TensorProxy(torch.Tensor): @classmethod def __torch_function__(cls, func, types, args=(), kwargs=None): if torch_function is not None: torch_function() return super().__torch_function__(func, types, args, kwargs) return TensorProxy
UnspecModuleWithIntAttr
python
pypa__pip
src/pip/_vendor/rich/layout.py
{ "start": 680, "end": 883 }
class ____(NamedTuple): """An individual layout render.""" region: Region render: List[List[Segment]] RegionMap = Dict["Layout", Region] RenderMap = Dict["Layout", LayoutRender]
LayoutRender
python
pypa__build
src/build/env.py
{ "start": 10222, "end": 14241 }
class ____(_EnvBackend): def create(self, path: str) -> None: import venv self._env_path = path try: import uv self._uv_bin = uv.find_uv_bin() except (ModuleNotFoundError, FileNotFoundError): uv_bin = shutil.which('uv') if uv_bin is None: msg = 'uv executable not found' raise RuntimeError(msg) from None _ctx.log(f'Using external uv from {uv_bin}') self._uv_bin = uv_bin venv.EnvBuilder(symlinks=_fs_supports_symlink(), with_pip=False).create(self._env_path) self.python_executable, self.scripts_dir, _ = _find_executable_and_scripts(self._env_path) def install_requirements(self, requirements: Collection[str]) -> None: cmd = [self._uv_bin, 'pip'] if _ctx.verbosity > 1: cmd += [f'-{"v" * min(2, _ctx.verbosity - 1)}'] run_subprocess([*cmd, 'install', *requirements], env={**os.environ, 'VIRTUAL_ENV': self._env_path}) @property def display_name(self) -> str: return 'venv+uv' @functools.cache def _fs_supports_symlink() -> bool: """Return True if symlinks are supported""" # Using definition used by venv.main() if os.name != 'nt': return True # Windows may support symlinks (setting in Windows 10) with tempfile.NamedTemporaryFile(prefix='build-symlink-') as tmp_file: dest = f'{tmp_file}-b' try: os.symlink(tmp_file.name, dest) os.unlink(dest) except (OSError, NotImplementedError, AttributeError): return False return True def _find_executable_and_scripts(path: str) -> tuple[str, str, str]: """ Detect the Python executable and script folder of a virtual environment. :param path: The location of the virtual environment :return: The Python executable, script folder, and purelib folder """ config_vars = sysconfig.get_config_vars().copy() # globally cached, copy before altering it config_vars['base'] = path scheme_names = sysconfig.get_scheme_names() if 'venv' in scheme_names: # Python distributors with custom default installation scheme can set a # scheme that can't be used to expand the paths in a venv. # This can happen if build itself is not installed in a venv. # The distributors are encouraged to set a "venv" scheme to be used for this. # See https://bugs.python.org/issue45413 # and https://github.com/pypa/virtualenv/issues/2208 paths = sysconfig.get_paths(scheme='venv', vars=config_vars) elif 'posix_local' in scheme_names: # The Python that ships on Debian/Ubuntu varies the default scheme to # install to /usr/local # But it does not (yet) set the "venv" scheme. # If we're the Debian "posix_local" scheme is available, but "venv" # is not, we use "posix_prefix" instead which is venv-compatible there. paths = sysconfig.get_paths(scheme='posix_prefix', vars=config_vars) elif 'osx_framework_library' in scheme_names: # The Python that ships with the macOS developer tools varies the # default scheme depending on whether the ``sys.prefix`` is part of a framework. # But it does not (yet) set the "venv" scheme. # If the Apple-custom "osx_framework_library" scheme is available but "venv" # is not, we use "posix_prefix" instead which is venv-compatible there. paths = sysconfig.get_paths(scheme='posix_prefix', vars=config_vars) else: paths = sysconfig.get_paths(vars=config_vars) executable = os.path.join(paths['scripts'], 'python.exe' if os.name == 'nt' else 'python') if not os.path.exists(executable): msg = f'Virtual environment creation failed, executable {executable} missing' raise RuntimeError(msg) return executable, paths['scripts'], paths['purelib'] __all__ = [ 'DefaultIsolatedEnv', 'IsolatedEnv', ]
_UvBackend
python
openai__openai-python
src/openai/types/responses/response_output_message.py
{ "start": 527, "end": 1104 }
class ____(BaseModel): id: str """The unique ID of the output message.""" content: List[Content] """The content of the output message.""" role: Literal["assistant"] """The role of the output message. Always `assistant`.""" status: Literal["in_progress", "completed", "incomplete"] """The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. """ type: Literal["message"] """The type of the output message. Always `message`."""
ResponseOutputMessage
python
ethereum__web3.py
web3/types.py
{ "start": 6183, "end": 6284 }
class ____(SubscriptionResponse): result: Literal[False] | SyncProgress
SyncingSubscriptionResponse
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-deepinfra/llama_index/llms/deepinfra/base.py
{ "start": 1391, "end": 16541 }
class ____(FunctionCallingLLM): """ DeepInfra LLM. Examples: `pip install llama-index-llms-deepinfra` ```python from llama_index.llms.deepinfra import DeepInfraLLM llm = DeepInfraLLM( model="mistralai/Mixtral-8x22B-Instruct-v0.1", # Default model name api_key = "your-deepinfra-api-key", temperature=0.5, max_tokens=50, additional_kwargs={"top_p": 0.9}, ) response = llm.complete("Hello World!") print(response) ``` """ model: str = Field( default=DEFAULT_MODEL_NAME, description="The DeepInfra model to use." ) temperature: float = Field( default=DEFAULT_TEMPERATURE, description="The temperature to use during generation.", ge=0.0, le=1.0, ) max_tokens: Optional[int] = Field( default=DEFAULT_MAX_TOKENS, description="The maximum number of tokens to generate.", gt=0, ) timeout: Optional[float] = Field( default=None, description="The timeout to use in seconds.", ge=0 ) max_retries: int = Field( default=10, description="The maximum number of API retries.", ge=0 ) _api_key: Optional[str] = PrivateAttr() generate_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional keyword arguments for generation." ) _client: DeepInfraClient = PrivateAttr() def __init__( self, model: str = DEFAULT_MODEL_NAME, additional_kwargs: Optional[Dict[str, Any]] = None, temperature: float = DEFAULT_TEMPERATURE, max_tokens: Optional[int] = DEFAULT_MAX_TOKENS, max_retries: int = 10, api_base: str = API_BASE, timeout: Optional[float] = None, api_key: Optional[str] = None, callback_manager: Optional[CallbackManager] = None, system_prompt: Optional[str] = None, messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT, output_parser: Optional[BaseOutputParser] = None, ) -> None: additional_kwargs = additional_kwargs or {} callback_manager = callback_manager or CallbackManager([]) super().__init__( model=model, api_base=api_base, api_key=api_key, temperature=temperature, max_tokens=max_tokens, timeout=timeout, additional_kwargs=additional_kwargs, max_retries=max_retries, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, pydantic_program_mode=pydantic_program_mode, output_parser=output_parser, ) self._api_key = get_from_param_or_env("api_key", api_key, ENV_VARIABLE) self._client = DeepInfraClient( api_key=self._api_key, api_base=api_base, timeout=timeout, max_retries=max_retries, ) @classmethod def class_name(cls) -> str: return "DeepInfra_LLM" @property def metadata(self) -> LLMMetadata: return LLMMetadata( num_output=self.max_tokens, is_chat_model=self._is_chat_model, model=self.model, model_name=self.model, is_function_calling_model=self._client.is_function_calling_model( self.model ), ) @property def _is_chat_model(self) -> bool: return True # Synchronous Methods @llm_completion_callback() def complete(self, prompt: str, **kwargs) -> CompletionResponse: """ Generate completion for the given prompt. Args: prompt (str): The input prompt to generate completion for. **kwargs: Additional keyword arguments for the API request. Returns: str: The generated text completion. """ payload = self._build_payload(prompt=prompt, **kwargs) result = self._client.request(INFERENCE_ENDPOINT, payload) return CompletionResponse(text=maybe_extract_from_json(result), raw=result) @llm_completion_callback() def stream_complete(self, prompt: str, **kwargs) -> CompletionResponseGen: """ Generate a synchronous streaming completion for the given prompt. Args: prompt (str): The input prompt to generate completion for. **kwargs: Additional keyword arguments for the API request. Yields: CompletionResponseGen: The streaming text completion. """ payload = self._build_payload(prompt=prompt, **kwargs) content = "" for response_dict in self._client.request_stream(INFERENCE_ENDPOINT, payload): content_delta = maybe_extract_from_json(response_dict) content += content_delta yield CompletionResponse( text=content, delta=content_delta, raw=response_dict ) @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs) -> ChatResponse: """ Generate a chat response for the given messages. Args: messages (Sequence[ChatMessage]): A sequence of chat messages. **kwargs: Additional keyword arguments for the API request. Returns: ChatResponse: The chat response containing a sequence of messages. """ messages = chat_messages_to_list(messages) payload = self._build_payload(messages=messages, **kwargs) result = self._client.request(CHAT_API_ENDPOINT, payload) mo = result["choices"][-1]["message"] additional_kwargs = { "tool_calls": mo.get("tool_calls", []) or [], } return ChatResponse( message=ChatMessage( role=mo["role"], content=mo["content"], additional_kwargs=additional_kwargs, ), raw=result, ) @llm_chat_callback() def stream_chat( self, chat_messages: Sequence[ChatMessage], **kwargs ) -> ChatResponseGen: """ Generate a synchronous streaming chat response for the given messages. Args: messages (Sequence[ChatMessage]): A sequence of chat messages. **kwargs: Additional keyword arguments for the API request. Yields: ChatResponseGen: The chat response containing a sequence of messages. """ messages = chat_messages_to_list(chat_messages) payload = self._build_payload(messages=messages, **kwargs) content = "" role = MessageRole.ASSISTANT for response_dict in self._client.request_stream(CHAT_API_ENDPOINT, payload): delta = response_dict["choices"][-1]["delta"] """ Check if the delta contains content. """ if delta.get("content", None): content_delta = delta["content"] content += delta["content"] message = ChatMessage( role=role, content=content, ) yield ChatResponse( message=message, raw=response_dict, delta=content_delta ) # Asynchronous Methods @llm_completion_callback() async def acomplete(self, prompt: str, **kwargs) -> CompletionResponse: """ Asynchronously generate completion for the given prompt. Args: prompt (str): The input prompt to generate completion for. **kwargs: Additional keyword arguments for the API request. Returns: CompletionResponse: The generated text completion. """ payload = self._build_payload(prompt=prompt, **kwargs) result = await self._client.arequest(INFERENCE_ENDPOINT, payload) return CompletionResponse(text=maybe_extract_from_json(result), raw=result) @llm_completion_callback() async def astream_complete( self, prompt: str, **kwargs ) -> CompletionResponseAsyncGen: """ Asynchronously generate a streaming completion for the given prompt. Args: prompt (str): The input prompt to generate completion for. **kwargs: Additional keyword arguments for the API request. Yields: CompletionResponseAsyncGen: The streaming text completion. """ payload = self._build_payload(prompt=prompt, **kwargs) async def gen(): content = "" async for response_dict in self._client.arequest_stream( INFERENCE_ENDPOINT, payload ): content_delta = maybe_extract_from_json(response_dict) content += content_delta yield CompletionResponse( text=content, delta=content_delta, raw=response_dict ) return gen() @llm_chat_callback() async def achat( self, chat_messages: Sequence[ChatMessage], **kwargs ) -> ChatResponse: """ Asynchronously generate a chat response for the given messages. Args: messages (Sequence[ChatMessage]): A sequence of chat messages. **kwargs: Additional keyword arguments for the API request. Returns: ChatResponse: The chat response containing a sequence of messages. """ messages = chat_messages_to_list(chat_messages) payload = self._build_payload(messages=messages, **kwargs) result = await self._client.arequest(CHAT_API_ENDPOINT, payload) mo = result["choices"][-1]["message"] additional_kwargs = {"tool_calls": mo.get("tool_calls", []) or []} return ChatResponse( message=ChatMessage( role=mo["role"], content=mo["content"], additional_kwargs=additional_kwargs, ), raw=result, ) @llm_chat_callback() async def astream_chat( self, chat_messages: Sequence[ChatMessage], **kwargs ) -> ChatResponseAsyncGen: """ Asynchronously generate a streaming chat response for the given messages. Args: messages (Sequence[ChatMessage]): A sequence of chat messages. **kwargs: Additional keyword arguments for the API request. Yields: ChatResponseAsyncGen: The chat response containing a sequence of messages. """ messages = chat_messages_to_list(chat_messages) payload = self._build_payload(messages=messages, **kwargs) async def gen(): content = "" role = MessageRole.ASSISTANT async for response_dict in self._client.arequest_stream( CHAT_API_ENDPOINT, payload ): delta = response_dict["choices"][-1]["delta"] """ Check if the delta contains content. """ if delta.get("content", None): content_delta = delta["content"] content += delta["content"] message = ChatMessage( role=role, content=content, ) yield ChatResponse( message=message, raw=response_dict, delta=content_delta ) return gen() def _prepare_chat_with_tools( self, tools: List["BaseTool"], user_msg: Optional[Union[str, ChatMessage]] = None, chat_history: Optional[List[ChatMessage]] = None, verbose: bool = False, allow_parallel_tool_calls: bool = False, tool_required: bool = False, # unsupported by deepinfra https://deepinfra.com/docs/advanced/function_calling - tool_choice only takes "auto" or "none", (not "required", so sadly can't require it) tool_choice: Union[str, dict] = "auto", **kwargs: Any, ) -> Dict[str, Any]: tool_specs = [tool.metadata.to_openai_tool() for tool in tools] if isinstance(user_msg, str): user_msg = ChatMessage(role=MessageRole.USER, content=user_msg) messages = chat_history or [] if user_msg: messages.append(user_msg) return { "messages": messages, "tools": tool_specs or None, "tool_choice": TOOL_CHOICE, **kwargs, } def _validate_chat_with_tools_response( self, response: "ChatResponse", tools: List["BaseTool"], allow_parallel_tool_calls: bool = False, **kwargs: Any, ) -> ChatResponse: if not allow_parallel_tool_calls: force_single_tool_call(response) return response def get_tool_calls_from_response( self, response: "ChatResponse", error_on_no_tool_call: bool = True, **kwargs: Any, ) -> List[ToolSelection]: tool_calls = response.message.additional_kwargs.get("tool_calls", []) if len(tool_calls) < 1: if error_on_no_tool_call: raise ValueError( f"Expected at least one tool call, but got {len(tool_calls)} tool calls." ) else: return [] tool_selections = [] for tool_call_dict in tool_calls: tool_call = ToolCallMessage.parse_obj(tool_call_dict) argument_dict = json.loads(tool_call.function.arguments) tool_selections.append( ToolSelection( tool_id=tool_call.id, tool_name=tool_call.function.name, tool_kwargs=argument_dict, ) ) return tool_selections # Utility Methods def get_model_endpoint(self) -> str: """ Get DeepInfra model endpoint. """ return f"{INFERENCE_ENDPOINT}/{self.model}" def _build_payload(self, **kwargs) -> Dict[str, Any]: """ Build the payload for the API request. The temperature and max_tokens parameters explicitly override the corresponding values in generate_kwargs. Any provided kwargs override all other parameters, including temperature and max_tokens. Args: prompt (str): The input prompt to generate completion for. stream (bool): Whether to stream the response. **kwargs: Additional keyword arguments for the API request. Returns: Dict[str, Any]: The API request payload. """ return { **self.generate_kwargs, "temperature": self.temperature, "max_tokens": self.max_tokens, "model": self.model, **kwargs, }
DeepInfraLLM
python
xlwings__xlwings
xlwings/base_classes.py
{ "start": 3068, "end": 3924 }
class ____: @property def api(self): raise NotImplementedError() @property def active(self): raise NotImplementedError() def __call__(self, name_or_index): raise NotImplementedError() def __len__(self): raise NotImplementedError() def add(self): raise NotImplementedError() def open( self, fullname, update_links=None, read_only=None, format=None, password=None, write_res_password=None, ignore_read_only_recommended=None, origin=None, delimiter=None, editable=None, notify=None, converter=None, add_to_mru=None, local=None, corrupt_load=None, ): raise NotImplementedError() def __iter__(self): raise NotImplementedError()
Books
python
pennersr__django-allauth
allauth/socialaccount/providers/gumroad/provider.py
{ "start": 221, "end": 343 }
class ____(ProviderAccount): def get_profile_url(self): return self.account.extra_data.get("url")
GumroadAccount
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_length.py
{ "start": 40, "end": 124 }
class ____: def __len__(self): return True # [invalid-length-return]
Bool
python
uqfoundation__dill
dill/tests/test_restricted.py
{ "start": 340, "end": 783 }
class ____: def __bool__(*args, **kwargs): raise Exception('Restricted function') __eq__ = __lt__ = __le__ = __ne__ = __gt__ = __ge__ = __hash__ = __bool__ glob_obj = RestrictedType() def restricted_func(): a = glob_obj def test_function_with_restricted_object(): deserialized = dill.loads(dill.dumps(restricted_func, recurse=True)) if __name__ == '__main__': test_function_with_restricted_object()
RestrictedType
python
walkccc__LeetCode
solutions/3041. Maximize Consecutive Elements in an Array After Modification/3041-2.py
{ "start": 0, "end": 891 }
class ____: def maxSelectedElements(self, nums: list[int]) -> int: ans = 1 prev = -math.inf # the length of the longest consecutive elements (seq0) ending in the # previous number dp0 = 1 # the length of the longest consecutive elements (seq1) ending in the # previous number + 1 dp1 = 1 for num in sorted(nums): if num == prev: dp1 = dp0 + 1 # Append `num + 1` to seq0. elif num == prev + 1: dp0 += 1 # Append `num` to seq0. dp1 += 1 # Add 1 to every number in seq0 and append `num + 1` to seq0. elif num == prev + 2: dp0 = dp1 + 1 # Append `num` to seq1. dp1 = 1 # Start a new sequence [`num + 1`]. else: dp0 = 1 # Start a new sequence [`num`]. dp1 = 1 # Start a new sequence [`num + 1`]. ans = max(ans, dp0, dp1) prev = num return ans
Solution
python
pytorch__pytorch
torch/_ops.py
{ "start": 1394, "end": 10726 }
class ____: """ Base class for OpOverload (which represents C++ ATen operators) and HigherOrderOperator (which represents Python-only operators that are unrepresentable in TorchScript). """ def __init__(self): # The dispatch cache precomputes a mapping of dispatch key that the # dispatcher wants to dispatch to, to an actual implementation of the # dispatch key. Confusingly, the actual implementation could *also* be a # dispatch key, but in this case, this refers to the C++ kernel that # was registered to some dispatch key. Aliases are permitted in the # latter but not the former; for example, you might lookup the # entry for AutogradCPU, and this maps you to the Autograd key for # the generic autograd kernel that works for all devices. Since this # is the Python dispatcher, you can also put an arbitrary Python # callable to call instead. This handler gets precisely the # args/kwargs that the operator was __call__'ed with. # NB: This name is hard-coded in torch/csrc/autograd/python_variable.cpp # for use with OpOverload; cache lookup is done entirely from C++ # for speed. # TODO: The cache is NOT currently used by HigherOrderOperator, but it should! self._dispatch_cache: dict[ DispatchKey, Union[DispatchKey, Callable[..., Any]] ] = {} # This table allows you to override the behavior of a particular # dispatch key to call a custom Python function, rather than the # ordinary C++ configured behavior. This is the raison d'etre of # codespell:ignore # Python dispatcher: to let you program the dispatcher from Python # in case you need something unusual, and don't want to clobber # the existing registrations using the Python operator registration # API. self.py_kernels: dict[DispatchKey, Callable[..., Any]] = {} # This table allows you to override the behavior of a particular # operator for a particular TorchDispatchMode. In practice, # we are using this mostly for ProxyTensorMode. Modes can be # thought of as an open world extension of dispatch keys, so it # makes sense that you should be able to register them, the same # way you can register dispatch keys. self.python_key_table: dict[ type[Union[TorchDispatchMode, torch.Tensor]], Callable[..., Any] ] = {} # This table allows you to override the behavior of functorch # transformations. NB: this currently only does something for # HigherOrderOperator self.functorch_table = {} def __call__(self, *args, **kwargs): raise NotImplementedError def has_kernel_for_dispatch_key(self, k): return k in self.py_kernels def has_kernel_for_any_dispatch_key(self, ks): for k in self.py_kernels: if not torch._C._dispatch_is_alias_key(k) and ks.has(k): return True return False def py_impl( self, k: Union[ type[TorchDispatchMode], type[torch.Tensor], TransformType, DispatchKey, ], ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]: def inner(fn: Callable[_P, _T]) -> Callable[_P, _T]: if inspect.isclass(k) and ( issubclass(k, TorchDispatchMode) or issubclass(k, torch.Tensor) ): assert k not in self.python_key_table # TODO(voz): Should we replace setting DispatchKey.Python entirely with setting mode keys? self.python_key_table[k] = fn self._dispatch_cache.clear() return fn if isinstance(k, TransformType): assert k not in self.functorch_table self.functorch_table[k] = fn return fn assert isinstance(k, DispatchKey) assert k != DispatchKey.Python, ( "Please register a mode for the DispatchKey.Python key instead." ) if k in self.py_kernels: raise RuntimeError( f"Trying to override a python impl for {k} on operator {self.name()}" ) self.py_kernels[k] = fn self._dispatch_cache.clear() return fn return inner # Registers an implementation to all **3** variants of functionalization that we have: # - DispatchKey.Functionalize # - functorch.TransformType.Functionalize # - FunctionalTensorMode # Example: # @py_functionalize_impl # def functionalize_rule(ctx, inner_f, *args): # args_unwrapped = ctx.unwrap_tensors(args) # with ctx.redispatch_to_next(): # out = ctx.functionalize(inner_f)(*args_unwrapped) # return ctx.wrap_tensors(out) def py_functionalize_impl( self, fn: Callable[Concatenate["BaseFunctionalizeAPI", _P], _T] ) -> Callable[Concatenate["BaseFunctionalizeAPI", _P], _T]: from torch._subclasses.functional_tensor import ( CppFunctionalizeAPI, FunctionalTensorMode, FunctorchFunctionalizeAPI, PythonFunctionalizeAPI, ) # Construct our three flavors of functionalization, # each of which have slightly different wrap/unwrap/redispatch policies def functionalize_dk_fn(*args: _P.args, **kwargs: _P.kwargs) -> _T: return fn(CppFunctionalizeAPI(), *args, **kwargs) def functionalize_dispatch_mode_fn( mode: Optional[FunctionalTensorMode], *args: _P.args, **kwargs: _P.kwargs ) -> _T: return fn(PythonFunctionalizeAPI(mode), *args, **kwargs) def functionalize_functorch_fn( interpreter, *args: _P.args, **kwargs: _P.kwargs ) -> _T: return fn(FunctorchFunctionalizeAPI(interpreter), *args, **kwargs) self.py_impl(DispatchKey.Functionalize)(functionalize_dk_fn) self.py_impl(FunctionalTensorMode)(functionalize_dispatch_mode_fn) self.py_impl(TransformType.Functionalize)(functionalize_functorch_fn) return fn def name(self): raise NotImplementedError # Equivalent to computeDispatchTableEntryWithDebug def resolve_key(op: OperatorBase, k: DispatchKey): # type: ignore[valid-type] # 1. (Direct) operator registration if op.has_kernel_for_dispatch_key(k): return k # 2.1 Use CompositeExplicitAutogradNonFunctional kernel if available cand = DispatchKey.CompositeExplicitAutogradNonFunctional if ( k == DispatchKey.Undefined or is_included_in_alias(k, cand) ) and op.has_kernel_for_dispatch_key(cand): return cand # 2.2 Use CompositeExplicitAutograd kernel if available cand = DispatchKey.CompositeExplicitAutograd if ( k == DispatchKey.Undefined or is_included_in_alias(k, cand) ) and op.has_kernel_for_dispatch_key(cand): return cand has_backend_kernel = op.has_kernel_for_any_dispatch_key( torch._C._dispatch_get_backend_keyset_from_autograd(k) ) or op.has_kernel_for_dispatch_key(DispatchKey.CompositeExplicitAutograd) # 2.3. Use CompositeImplicitAutograd kernel if available cand = DispatchKey.CompositeImplicitAutogradNestedTensor if ( (k != DispatchKey.Undefined and is_included_in_alias(k, cand)) and op.has_kernel_for_dispatch_key(cand) and not has_backend_kernel ): return cand cand = DispatchKey.CompositeImplicitAutograd if ( k == DispatchKey.Undefined or is_included_in_alias(k, cand) ) and op.has_kernel_for_dispatch_key(cand): if k == DispatchKey.AutogradOther and op.has_kernel_for_any_dispatch_key( torch._C._dispatch_autogradother_backends ): raise RuntimeError("ambiguous autogradother kernel") elif not has_backend_kernel: return cand # 2.4. For autograd backend keys, use kernel from DispatchKey::Autograd if available cand = DispatchKey.Autograd if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand): return cand # 2.5 Use kernel from DispatchKey::FuncTorchBatchedDecomposition if available cand = DispatchKey.FuncTorchBatchedDecomposition if is_included_in_alias(k, cand) and op.has_kernel_for_dispatch_key(cand): return cand # Backend fallback if torch._C._dispatch_has_backend_fallback(k): # The dispatch key itself will implicitly route to backend fallback. # This is probably not great for the pure Python implementation. return k raise NotImplementedError(f"could not find kernel for {op} at dispatch key {k}") _higher_order_ops: dict[str, "HigherOrderOperator"] = {} _HIGHER_ORDER_OP_DEFAULT_FALLTHROUGH_DISPATCH_KEYS = [ DispatchKey.PythonDispatcher, # type: ignore[attr-defined] DispatchKey.PythonTLSSnapshot, # type: ignore[attr-defined] DispatchKey.ADInplaceOrView, DispatchKey.BackendSelect, DispatchKey.AutocastCPU, # type: ignore[attr-defined] DispatchKey.AutocastCUDA, # type: ignore[attr-defined] DispatchKey.AutocastXPU, # type: ignore[attr-defined] ]
OperatorBase
python
PyCQA__pylint
tests/functional/i/invalid/invalid_format_returned.py
{ "start": 331, "end": 463 }
class ____: """__format__ returns <type 'str'>""" def __format__(self, format_spec): return str(123)
SecondGoodFormat
python
apache__airflow
airflow-ctl/src/airflowctl/api/datamodels/generated.py
{ "start": 9130, "end": 9306 }
class ____(str, Enum): """ Enum for DAG Run states when updating a DAG Run. """ QUEUED = "queued" SUCCESS = "success" FAILED = "failed"
DAGRunPatchStates
python
facebookresearch__faiss
faiss/gpu/test/test_gpu_index_serialize.py
{ "start": 333, "end": 2071 }
class ____(unittest.TestCase): def test_serialize(self): res = faiss.StandardGpuResources() d = 32 k = 10 train = make_t(10000, d) add = make_t(10000, d) query = make_t(10, d) # Construct various GPU index types indexes = [] # Flat indexes.append(faiss.GpuIndexFlatL2(res, d)) # IVF nlist = 5 # IVFFlat indexes.append(faiss.GpuIndexIVFFlat(res, d, nlist, faiss.METRIC_L2)) # IVFSQ config = faiss.GpuIndexIVFScalarQuantizerConfig() config.use_cuvs = False indexes.append(faiss.GpuIndexIVFScalarQuantizer(res, d, nlist, faiss.ScalarQuantizer.QT_fp16, faiss.METRIC_L2, True, config)) # IVFPQ indexes.append(faiss.GpuIndexIVFPQ(res, d, nlist, 4, 8, faiss.METRIC_L2)) for index in indexes: index.train(train) index.add(add) orig_d, orig_i = index.search(query, k) ser = faiss.serialize_index(faiss.index_gpu_to_cpu(index)) cpu_index = faiss.deserialize_index(ser) gpu_cloner_options = faiss.GpuClonerOptions() if isinstance(index, faiss.GpuIndexIVFScalarQuantizer): gpu_cloner_options.use_cuvs = False gpu_index_restore = faiss.index_cpu_to_gpu(res, 0, cpu_index, gpu_cloner_options) restore_d, restore_i = gpu_index_restore.search(query, k) self.assertTrue(np.array_equal(orig_d, restore_d)) self.assertTrue(np.array_equal(orig_i, restore_i)) # Make sure the index is in a state where we can add to it # without error gpu_index_restore.add(query)
TestGpuSerialize
python
coleifer__peewee
tests/models.py
{ "start": 145851, "end": 147623 }
class ____(PGOnConflictTests, ModelTestCase): database = get_in_memory_db() @skip_if(IS_SQLITE_24, 'requires sqlite < 3.24') def test_no_preserve_update_where(self): # Ensure on SQLite < 3.24 we cannot update or preserve values. base = Emp.insert(first='foo', last='bar', empno='125') preserve = base.on_conflict(preserve=[Emp.last]) self.assertRaises(ValueError, preserve.execute) update = base.on_conflict(update={Emp.empno: 'xxx'}) self.assertRaises(ValueError, update.execute) where = base.on_conflict(where=(Emp.id > 10)) self.assertRaises(ValueError, where.execute) @skip_unless(IS_SQLITE_24, 'requires sqlite >= 3.24') def test_update_meets_requirements(self): # Ensure that on >= 3.24 any updates meet the minimum criteria. base = Emp.insert(first='foo', last='bar', empno='125') # Must specify update or preserve. no_update_preserve = base.on_conflict(conflict_target=(Emp.empno,)) self.assertRaises(ValueError, no_update_preserve.execute) # Must specify a conflict target. no_conflict_target = base.on_conflict(update={Emp.empno: '125.1'}) self.assertRaises(ValueError, no_conflict_target.execute) @skip_unless(IS_SQLITE_24, 'requires sqlite >= 3.24') def test_do_nothing(self): query = (Emp .insert(first='foo', last='bar', empno='123') .on_conflict('nothing')) self.assertSQL(query, ( 'INSERT INTO "emp" ("first", "last", "empno") ' 'VALUES (?, ?, ?) ON CONFLICT DO NOTHING'), ['foo', 'bar', '123']) query.execute() # Conflict occurs with empno='123'. self.assertData(list(self.test_data))
TestUpsertSqlite
python
numpy__numpy
benchmarks/benchmarks/bench_random.py
{ "start": 955, "end": 1648 }
class ____(Benchmark): high = { 'bool': 1, 'uint8': 2**7, 'uint16': 2**15, 'uint32': 2**31, 'uint64': 2**63 } param_names = ['dtype'] params = ['bool', 'uint8', 'uint16', 'uint32', 'uint64'] def setup(self, name): from numpy.lib import NumpyVersion if NumpyVersion(np.__version__) < '1.11.0.dev0': raise NotImplementedError def time_randint_fast(self, name): high = self.high[name] np.random.randint(0, high, size=10**5, dtype=name) def time_randint_slow(self, name): high = self.high[name] np.random.randint(0, high + 1, size=10**5, dtype=name)
Randint_dtype
python
huggingface__transformers
src/transformers/models/gpt_oss/modeling_gpt_oss.py
{ "start": 28162, "end": 32622 }
class ____(GptOssPreTrainedModel, GenerationMixin): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} _tp_plan = {"lm_head": "colwise_rep"} _pp_plan = {"lm_head": (["hidden_states"], ["logits"])} def __init__(self, config): super().__init__(config) self.model = GptOssModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) self.router_aux_loss_coef = config.router_aux_loss_coef self.num_experts = config.num_local_experts self.num_experts_per_tok = config.num_experts_per_tok # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_router_logits: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> MoeCausalLMOutputWithPast: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Example: ```python >>> from transformers import AutoTokenizer, GptOssForCausalLM >>> model = GptOssForCausalLM.from_pretrained("mistralai/GptOss-8x7B-v0.1") >>> tokenizer = AutoTokenizer.from_pretrained("mistralai/GptOss-8x7B-v0.1") >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" output_router_logits = ( output_router_logits if output_router_logits is not None else self.config.output_router_logits ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs: MoeModelOutputWithPast = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_router_logits=output_router_logits, cache_position=cache_position, **kwargs, ) hidden_states = outputs.last_hidden_state # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function(logits, labels, self.vocab_size, **kwargs) aux_loss = None if output_router_logits: aux_loss = load_balancing_loss_func( outputs.router_logits, self.num_experts, self.num_experts_per_tok, attention_mask, ) if labels is not None: loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device return MoeCausalLMOutputWithPast( loss=loss, aux_loss=aux_loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, router_logits=outputs.router_logits, )
GptOssForCausalLM
python
getsentry__sentry
src/sentry/workflow_engine/endpoints/serializers/workflow_serializer.py
{ "start": 536, "end": 3652 }
class ____(Serializer): def get_attrs( self, item_list: Sequence[Workflow], user, **kwargs ) -> MutableMapping[Workflow, dict[str, Any]]: attrs: MutableMapping[Workflow, dict[str, Any]] = defaultdict(dict) trigger_conditions = list( DataConditionGroup.objects.filter( id__in=[w.when_condition_group_id for w in item_list if w.when_condition_group_id] ) ) trigger_condition_map = { group.id: serialized for group, serialized in zip( trigger_conditions, serialize(trigger_conditions, user=user) ) } last_triggered_map: dict[int, datetime] = dict( WorkflowFireHistory.objects.filter( workflow__in=item_list, ) .values("workflow_id") .annotate(last_triggered=Max("date_added")) .values_list("workflow_id", "last_triggered") ) wdcg_list = list(WorkflowDataConditionGroup.objects.filter(workflow__in=item_list)) condition_groups = {wdcg.condition_group for wdcg in wdcg_list} serialized_condition_groups = { dcg.id: serialized for dcg, serialized in zip(condition_groups, serialize(condition_groups, user=user)) } dcg_map = defaultdict(list) for wdcg in wdcg_list: dcg_map[wdcg.workflow_id].append(serialized_condition_groups[wdcg.condition_group_id]) detectors_map = defaultdict(list) detector_workflows = DetectorWorkflow.objects.filter(workflow__in=item_list).values_list( "detector_id", "workflow_id" ) for detector_id, workflow_id in detector_workflows: detectors_map[workflow_id].append(str(detector_id)) for item in item_list: attrs[item]["triggers"] = trigger_condition_map.get( item.when_condition_group_id ) # when condition group attrs[item]["actionFilters"] = dcg_map.get( item.id, [] ) # The data condition groups for filtering actions attrs[item]["detectorIds"] = detectors_map[item.id] attrs[item]["lastTriggered"] = last_triggered_map.get(item.id) return attrs def serialize(self, obj: Workflow, attrs: Mapping[str, Any], user, **kwargs) -> dict[str, Any]: return { "id": str(obj.id), "name": str(obj.name), "organizationId": str(obj.organization_id), "createdBy": str(obj.created_by_id) if obj.created_by_id else None, "dateCreated": obj.date_added, "dateUpdated": obj.date_updated, "triggers": attrs.get("triggers"), "actionFilters": attrs.get("actionFilters"), "environment": obj.environment.name if obj.environment else None, "config": convert_dict_key_case(obj.config, snake_to_camel_case), "detectorIds": attrs.get("detectorIds"), "enabled": obj.enabled, "lastTriggered": attrs.get("lastTriggered"), }
WorkflowSerializer
python
encode__django-rest-framework
tests/schemas/test_coreapi.py
{ "start": 17958, "end": 18083 }
class ____(ExampleViewSet): permission_classes = [] http_method_names = ['get', 'head', 'options']
MethodLimitedViewSet
python
getsentry__sentry
src/sentry/notifications/platform/templates/sample.py
{ "start": 4384, "end": 4679 }
class ____(NotificationData): source = "deployment-service" project_name: str version: str environment: str deployer: str commit_sha: str commit_message: str deployment_url: str rollback_url: str @template_registry.register(DeploymentData.source)
DeploymentData
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 229636, "end": 230226 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field(sgqlc.types.list_of("CommitEdge"), graphql_name="edges") nodes = sgqlc.types.Field(sgqlc.types.list_of("Commit"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
CommitConnection
python
pypa__setuptools
setuptools/_distutils/tests/test_build_py.py
{ "start": 299, "end": 6882 }
class ____(support.TempdirManager): def test_package_data(self): sources = self.mkdtemp() jaraco.path.build( { '__init__.py': "# Pretend this is a package.", 'README.txt': 'Info about this package', }, sources, ) destination = self.mkdtemp() dist = Distribution({"packages": ["pkg"], "package_dir": {"pkg": sources}}) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.command_obj["build"] = support.DummyCommand( force=False, build_lib=destination ) dist.packages = ["pkg"] dist.package_data = {"pkg": ["README.txt"]} dist.package_dir = {"pkg": sources} cmd = build_py(dist) cmd.compile = True cmd.ensure_finalized() assert cmd.package_data == dist.package_data cmd.run() # This makes sure the list of outputs includes byte-compiled # files for Python modules but not for package data files # (there shouldn't *be* byte-code files for those!). assert len(cmd.get_outputs()) == 3 pkgdest = os.path.join(destination, "pkg") files = os.listdir(pkgdest) pycache_dir = os.path.join(pkgdest, "__pycache__") assert "__init__.py" in files assert "README.txt" in files if sys.dont_write_bytecode: assert not os.path.exists(pycache_dir) else: pyc_files = os.listdir(pycache_dir) assert f"__init__.{sys.implementation.cache_tag}.pyc" in pyc_files def test_empty_package_dir(self): # See bugs #1668596/#1720897 sources = self.mkdtemp() jaraco.path.build({'__init__.py': '', 'doc': {'testfile': ''}}, sources) os.chdir(sources) dist = Distribution({ "packages": ["pkg"], "package_dir": {"pkg": ""}, "package_data": {"pkg": ["doc/*"]}, }) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.script_args = ["build"] dist.parse_command_line() try: dist.run_commands() except DistutilsFileError: self.fail("failed package_data test when package_dir is ''") @pytest.mark.skipif('sys.dont_write_bytecode') def test_byte_compile(self): project_dir, dist = self.create_dist(py_modules=['boiledeggs']) os.chdir(project_dir) self.write_file('boiledeggs.py', 'import antigravity') cmd = build_py(dist) cmd.compile = True cmd.build_lib = 'here' cmd.finalize_options() cmd.run() found = os.listdir(cmd.build_lib) assert sorted(found) == ['__pycache__', 'boiledeggs.py'] found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) assert found == [f'boiledeggs.{sys.implementation.cache_tag}.pyc'] @pytest.mark.skipif('sys.dont_write_bytecode') def test_byte_compile_optimized(self): project_dir, dist = self.create_dist(py_modules=['boiledeggs']) os.chdir(project_dir) self.write_file('boiledeggs.py', 'import antigravity') cmd = build_py(dist) cmd.compile = False cmd.optimize = 1 cmd.build_lib = 'here' cmd.finalize_options() cmd.run() found = os.listdir(cmd.build_lib) assert sorted(found) == ['__pycache__', 'boiledeggs.py'] found = os.listdir(os.path.join(cmd.build_lib, '__pycache__')) expect = f'boiledeggs.{sys.implementation.cache_tag}.opt-1.pyc' assert sorted(found) == [expect] def test_dir_in_package_data(self): """ A directory in package_data should not be added to the filelist. """ # See bug 19286 sources = self.mkdtemp() jaraco.path.build( { 'pkg': { '__init__.py': '', 'doc': { 'testfile': '', # create a directory that could be incorrectly detected as a file 'otherdir': {}, }, } }, sources, ) os.chdir(sources) dist = Distribution({"packages": ["pkg"], "package_data": {"pkg": ["doc/*"]}}) # script_name need not exist, it just need to be initialized dist.script_name = os.path.join(sources, "setup.py") dist.script_args = ["build"] dist.parse_command_line() try: dist.run_commands() except DistutilsFileError: self.fail("failed package_data when data dir includes a dir") def test_dont_write_bytecode(self, caplog): # makes sure byte_compile is not used dist = self.create_dist()[1] cmd = build_py(dist) cmd.compile = True cmd.optimize = 1 old_dont_write_bytecode = sys.dont_write_bytecode sys.dont_write_bytecode = True try: cmd.byte_compile([]) finally: sys.dont_write_bytecode = old_dont_write_bytecode assert 'byte-compiling is disabled' in caplog.records[0].message def test_namespace_package_does_not_warn(self, caplog): """ Originally distutils implementation did not account for PEP 420 and included warns for package directories that did not contain ``__init__.py`` files. After the acceptance of PEP 420, these warnings don't make more sense so we want to ensure there are not displayed to not confuse the users. """ # Create a fake project structure with a package namespace: tmp = self.mkdtemp() jaraco.path.build({'ns': {'pkg': {'module.py': ''}}}, tmp) os.chdir(tmp) # Configure the package: attrs = { "name": "ns.pkg", "packages": ["ns", "ns.pkg"], "script_name": "setup.py", } dist = Distribution(attrs) # Run code paths that would trigger the trap: cmd = dist.get_command_obj("build_py") cmd.finalize_options() modules = cmd.find_all_modules() assert len(modules) == 1 module_path = modules[0][-1] assert module_path.replace(os.sep, "/") == "ns/pkg/module.py" cmd.run() assert not any( "package init file" in msg and "not found" in msg for msg in caplog.messages )
TestBuildPy
python
pytorch__pytorch
torch/ao/quantization/fx/_model_report/detector.py
{ "start": 17392, "end": 34345 }
class ____(DetectorBase): r""" Determines whether dynamic or static quantization is more appropriate for a given module. Takes advantage of the ModelReportObserver that records range information. Stationary distribution of data are strictly above tolerance level for the comparison statistic: S = average_batch_activation_range/epoch_activation_range Nonstationary distributions are below or at the tolerance level for this metric. If the distribution of data right after the module is non-stationary, recommend dynamic quantization Otherwise recommend static quantization Args: tolerance (float, optional): The threshold where S metric is stationary above and non-stationary otherwise. Default: 0.5 """ # names for the pre and post observers that are inserted DEFAULT_PRE_OBSERVER_NAME = "model_report_pre_observer" DEFAULT_POST_OBSERVER_NAME = "model_report_post_observer" # naming conventions for stationary vs non-stationary data STATIONARY_STR = "stationary" NON_STATIONARY_STR = "non-stationary" # naming for activation INPUT_ACTIVATION_PREFIX = "input_activation_" OUTPUT_ACTIVATION_PREFIX = "output_activation_" # naming conventions for the keys of the return module info TOLERANCE_KEY = "dynamic_static_tolerance" DEFAULT_DYNAMIC_REC_KEY = "dynamic_recommended" PRE_OBS_COMP_STAT_KEY = INPUT_ACTIVATION_PREFIX + "dynamic_static_comp_stat" POST_OBS_COMP_STAT_KEY = OUTPUT_ACTIVATION_PREFIX + "dynamic_static_comp_stat" PRE_OBS_DATA_DIST_KEY = ( INPUT_ACTIVATION_PREFIX + "dynamic_static_data_classification" ) POST_OBS_DATA_DIST_KEY = ( OUTPUT_ACTIVATION_PREFIX + "dynamic_static_data_classification" ) IS_CURRENTLY_SUPPORTED_KEY = "is_dynamic_supported" # modules that are supported both dynamic and static for this report function DEFAULT_DYNAMIC_STATIC_CHECK_SUPPORTED = {nn.Linear} # modules that will be supported soon for both DEFAULT_DYNAMIC_STATIC_FUTURE_SUPPORTED = {nn.Conv1d, nn.Conv2d, nn.Conv3d} def __init__(self, tolerance=0.5): super().__init__() # set tolerance level and initialize a set to keep track of useful fqn locations self.tolerance = tolerance self.useful_observer_fqns: set[str] = set() def determine_observer_insert_points( self, prepared_fx_model: GraphModule ) -> dict[str, dict[str, Any]]: r""" Determines where observers need to be inserted for the Dynamic vs Static detector. For this detector, we want to place observers on either side of linear layers in the model. Currently inserts observers for: linear layers Args: prepared_fx_model (GraphModule): The prepared Fx GraphModule Returns a Dict mapping from unique observer fqns (where we want to insert them) to a Dict with: key "target_node" -> the node we are trying to observe with this observer (torch.fx.node.Node) key "observer_to_insert" -> the observer we wish to insert (ObserverBase) key "is_post_observer" -> True if this is meant to be a post-observer for target_node, False if pre-observer key "observer_args" -> The arguments that are meant to be passed into the observer """ # observer for this detector is ModelReportObserver obs_ctr = ModelReportObserver # return dict obs_fqn_to_info: dict[str, dict[str, Any]] = {} for fqn, module in prepared_fx_model.named_modules(): # make sure module is supported if self._is_supported(module, insert=True): # if it's a supported type, we want to get node and add observer insert locations targeted_node = self._get_targeting_node(prepared_fx_model, fqn) # add entry for pre-observer pre_obs_fqn = fqn + "." + self.DEFAULT_PRE_OBSERVER_NAME obs_fqn_to_info[pre_obs_fqn] = { DETECTOR_TARGET_NODE_KEY: targeted_node, DETECTOR_OBS_TO_INSERT_KEY: obs_ctr(), DETECTOR_IS_POST_OBS_KEY: False, DETECTOR_OBS_ARGS_KEY: targeted_node.args, } # add entry for post-observer post_obs_fqn = fqn + "." + self.DEFAULT_POST_OBSERVER_NAME obs_fqn_to_info[post_obs_fqn] = { DETECTOR_TARGET_NODE_KEY: targeted_node, DETECTOR_OBS_TO_INSERT_KEY: obs_ctr(), DETECTOR_IS_POST_OBS_KEY: True, DETECTOR_OBS_ARGS_KEY: (targeted_node,), } return obs_fqn_to_info def get_detector_name(self) -> str: r"""returns the string name of this detector""" return "dynamic_vs_static_detector" def get_qconfig_info(self, model) -> dict[str, DetectorQConfigInfo]: r"""Returns the DetectorQConfigInfo for each module_fqn relevant Args model (nn.Module or subclass): model to find observer insertion points Returns a Dict mapping from unique observer fqns (where we want to insert them) to: A DetectorQConfigInfo with the information to generate a QConfig for a specific module """ # run the helper function to populate the dictionary dynamic_static_info = self._generate_dict_info(model) # we actually have a qconfig info object we are populating module_fqn_to_detector_qconfig_info = {} for module_fqn in dynamic_static_info: # create a detector info instance detector_qconfig_info = DetectorQConfigInfo(module_fqn) # see if per channel quantization is supported dynamic_static_recommended: bool = dynamic_static_info[module_fqn][ self.DEFAULT_DYNAMIC_REC_KEY ] detector_qconfig_info.is_activation_dynamic = dynamic_static_recommended module_fqn_to_detector_qconfig_info[module_fqn] = detector_qconfig_info return module_fqn_to_detector_qconfig_info def _is_supported(self, module: nn.Module, insert: bool = False) -> bool: r"""Returns whether the given module is supported for observers Args module: The module to check and ensure is supported insert: True if this is check for observer insertion, false if for report gen Returns True if the module is supported by observer, False otherwise """ # check to see if module is of a supported type is_supported_type = any( isinstance(module, x) for x in self.DEFAULT_DYNAMIC_STATIC_CHECK_SUPPORTED ) # check if it will be supported future_supported_type = any( isinstance(module, x) for x in self.DEFAULT_DYNAMIC_STATIC_FUTURE_SUPPORTED ) # supported supported = is_supported_type or future_supported_type # this is check for observer insertion if insert: return supported else: # this is for report gen and we also need to check if it contains observers has_obs = hasattr(module, self.DEFAULT_PRE_OBSERVER_NAME) and hasattr( module, self.DEFAULT_POST_OBSERVER_NAME ) return supported and has_obs def _generate_dict_info(self, model: GraphModule) -> dict[str, Any]: r""" Helper function for generate_detector_report that does the generation of the dictionary. This process is done as specified in generate_detector_report documentation Args: model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers Returns a Dictionary mapping modules with ModelReportObservers around them to: whether dynamic quantization is recommended their S metric of input to module whether input to module is stationary or non-stationary their S metric of output of module whether output of module is stationary or non-stationary the tolerance level to decided whether input/output is stationary or non-stationary whether it is currently supported or planned for the future """ # store modules dynamic vs static information module_dynamic_static_info = {} # This for loop goes through the modules, and extracts all relevant information into module_dynamic_static_info # This information primary includes whether the data distributions around a supported module is stationary or not # Based on this, it is recorded whether dynamic or static quantization is recommended # loop through all submodules included nested ones for fqn, module in model.named_modules(): # if module is Linear has the ModelReportObserver attached to it if self._is_supported(module): # get pre and post observers for the module pre_obs = getattr(module, self.DEFAULT_PRE_OBSERVER_NAME) post_obs = getattr(module, self.DEFAULT_POST_OBSERVER_NAME) # get the statistics for each module pre_stat = pre_obs.get_batch_to_epoch_ratio() post_stat = post_obs.get_batch_to_epoch_ratio() # record module, pre and post stat, and whether to do dynamic or static based off it # true if post observer data distribution is non-stationary, false if it's stationary dynamic_recommended = post_stat <= self.tolerance # specify the classifications for whether data distributions considered stationary or non-stationary pre_obs_dist_classif = ( self.STATIONARY_STR if pre_stat > self.tolerance else self.NON_STATIONARY_STR ) post_obs_dist_classif = ( self.STATIONARY_STR if post_stat > self.tolerance else self.NON_STATIONARY_STR ) # check if current support or future support is_supported_type = any( isinstance(module, x) for x in self.DEFAULT_DYNAMIC_STATIC_CHECK_SUPPORTED ) # store the set of important information for this module module_info = { self.TOLERANCE_KEY: self.tolerance, self.DEFAULT_DYNAMIC_REC_KEY: dynamic_recommended, self.PRE_OBS_COMP_STAT_KEY: pre_stat, self.PRE_OBS_DATA_DIST_KEY: pre_obs_dist_classif, self.POST_OBS_COMP_STAT_KEY: post_stat, self.POST_OBS_DATA_DIST_KEY: post_obs_dist_classif, self.IS_CURRENTLY_SUPPORTED_KEY: is_supported_type, } module_dynamic_static_info[fqn] = module_info return module_dynamic_static_info def generate_detector_report( self, model: GraphModule ) -> tuple[str, dict[str, Any]]: r""" Determines whether dynamic or static quantization is more appropriate for a given module. Takes advantage of the ModelReportObserver that records range information. Stationary distribution of data are strictly above tolerance level for the comparison statistic: S = average_batch_activation_range/epoch_activation_range Nonstationary distributions are below or at the tolerance level for this metric. If the distribution of data right after the module is non-stationary, recommend dynamic quantization Otherwise recommend static quantization This will then generate suggestions for dynamic vs static quantization focused around Linear. Args: model (GraphModule): The prepared and calibrated GraphModule with inserted ModelReportObservers Returns a tuple with two elements: String report of of whether dynamic or static quantization is recommended for certain modules Dictionary mapping modules with ModelReportObservers around them to: whether dynamic quantization is recommended their S metric of input to module whether input to module is stationary or non-stationary their S metric of output of module whether output of module is stationary or non-stationary the tolerance level to decided whether input/output is stationary or non-stationary whether it is currently supported or planned for the future """ # get the dictionary of the information to format the string report module_dynamic_static_info = self._generate_dict_info(model) dynamic_vs_static_string = "Dynamic vs. Static Quantization suggestions: \n" modules_added: bool = False # check to make sure at least 1 module added. dynamic_benefit = ( " You will get more accurate results if you use dynamic quantization" ) static_benefit = ( " You can increase model efficiency if you use static quantization" ) future_support_str = ( ". This layer is not yet supported for dynamic quantization" ) # This for loop goes through the information collected in module_dynamic_static_info and: # Populates the string based report with the information from module_dynamic_static_info # Compiles the complete report by appending relevant formatted strings for module_fqn in module_dynamic_static_info: # there is at least 1 module for suggestion modules_added = True module_info = module_dynamic_static_info[module_fqn] suggestion_string_template = ( "For module {} it is suggested to use {} quantization because {}.\n" ) # decide what string formatting values will be quantization_type = "" quantization_reasoning = "the distribution of data before {} is {} and the distribution after is {}." benefit_str = "" # strings for if dynamic quantized per tensor is needed recommend_per_tensor = ( ". We recommend to add a {} before this module if it is static." ) rec_lay_to_add = "dynamic quantize per tensor layer" dynamic_per_tensor_string = recommend_per_tensor.format(rec_lay_to_add) dynamic_per_tensor_reasoning_string = " This is because the input to this module has a non-stationary distribution" # start composing explanation if module_info[self.DEFAULT_DYNAMIC_REC_KEY]: quantization_type = "dynamic" # check if currently supported or future supported benefit_str = dynamic_benefit if not module_info[self.IS_CURRENTLY_SUPPORTED_KEY]: benefit_str += future_support_str else: quantization_type = "static" benefit_str = static_benefit # now set the quantization explanation string quantization_reasoning = ( quantization_reasoning.format( module_fqn, module_info[self.PRE_OBS_DATA_DIST_KEY], module_info[self.POST_OBS_DATA_DIST_KEY], ) + benefit_str ) # if we have a non-stationary input -> linear -> stationary we suggested static # however, we want to also recommend they add a dynamic quantize per tensor right if this change is made if ( module_info[self.PRE_OBS_DATA_DIST_KEY] == self.NON_STATIONARY_STR and module_info[self.POST_OBS_DATA_DIST_KEY] == self.STATIONARY_STR ): quantization_reasoning = ( quantization_reasoning + dynamic_per_tensor_string + dynamic_per_tensor_reasoning_string ) # format the overall suggestion string with the specific inputs module_suggestion_string = suggestion_string_template.format( module_fqn, quantization_type, quantization_reasoning ) # append to overall suggestion dynamic_vs_static_string += module_suggestion_string if not modules_added: dynamic_vs_static_string += "No applicable layers for suggestions. Only linear and conv are valid.\n" # return the string as well as the dictionary of information return (dynamic_vs_static_string, module_dynamic_static_info)
DynamicStaticDetector
python
kubernetes-client__python
kubernetes/client/models/v1_capacity_request_policy_range.py
{ "start": 383, "end": 6167 }
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 = { 'max': 'str', 'min': 'str', 'step': 'str' } attribute_map = { 'max': 'max', 'min': 'min', 'step': 'step' } def __init__(self, max=None, min=None, step=None, local_vars_configuration=None): # noqa: E501 """V1CapacityRequestPolicyRange - 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._max = None self._min = None self._step = None self.discriminator = None if max is not None: self.max = max self.min = min if step is not None: self.step = step @property def max(self): """Gets the max of this V1CapacityRequestPolicyRange. # noqa: E501 Max defines the upper limit for capacity that can be requested. Max must be less than or equal to the capacity value. Min and requestPolicy.default must be less than or equal to the maximum. # noqa: E501 :return: The max of this V1CapacityRequestPolicyRange. # noqa: E501 :rtype: str """ return self._max @max.setter def max(self, max): """Sets the max of this V1CapacityRequestPolicyRange. Max defines the upper limit for capacity that can be requested. Max must be less than or equal to the capacity value. Min and requestPolicy.default must be less than or equal to the maximum. # noqa: E501 :param max: The max of this V1CapacityRequestPolicyRange. # noqa: E501 :type: str """ self._max = max @property def min(self): """Gets the min of this V1CapacityRequestPolicyRange. # noqa: E501 Min specifies the minimum capacity allowed for a consumption request. Min must be greater than or equal to zero, and less than or equal to the capacity value. requestPolicy.default must be more than or equal to the minimum. # noqa: E501 :return: The min of this V1CapacityRequestPolicyRange. # noqa: E501 :rtype: str """ return self._min @min.setter def min(self, min): """Sets the min of this V1CapacityRequestPolicyRange. Min specifies the minimum capacity allowed for a consumption request. Min must be greater than or equal to zero, and less than or equal to the capacity value. requestPolicy.default must be more than or equal to the minimum. # noqa: E501 :param min: The min of this V1CapacityRequestPolicyRange. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and min is None: # noqa: E501 raise ValueError("Invalid value for `min`, must not be `None`") # noqa: E501 self._min = min @property def step(self): """Gets the step of this V1CapacityRequestPolicyRange. # noqa: E501 Step defines the step size between valid capacity amounts within the range. Max (if set) and requestPolicy.default must be a multiple of Step. Min + Step must be less than or equal to the capacity value. # noqa: E501 :return: The step of this V1CapacityRequestPolicyRange. # noqa: E501 :rtype: str """ return self._step @step.setter def step(self, step): """Sets the step of this V1CapacityRequestPolicyRange. Step defines the step size between valid capacity amounts within the range. Max (if set) and requestPolicy.default must be a multiple of Step. Min + Step must be less than or equal to the capacity value. # noqa: E501 :param step: The step of this V1CapacityRequestPolicyRange. # noqa: E501 :type: str """ self._step = step 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, V1CapacityRequestPolicyRange): 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, V1CapacityRequestPolicyRange): return True return self.to_dict() != other.to_dict()
V1CapacityRequestPolicyRange
python
sympy__sympy
sympy/codegen/ast.py
{ "start": 18450, "end": 25671 }
class ____(CodegenAST): """ Represents a block of code. Explanation =========== For now only assignments are supported. This restriction will be lifted in the future. Useful attributes on this object are: ``left_hand_sides``: Tuple of left-hand sides of assignments, in order. ``left_hand_sides``: Tuple of right-hand sides of assignments, in order. ``free_symbols``: Free symbols of the expressions in the right-hand sides which do not appear in the left-hand side of an assignment. Useful methods on this object are: ``topological_sort``: Class method. Return a CodeBlock with assignments sorted so that variables are assigned before they are used. ``cse``: Return a new CodeBlock with common subexpressions eliminated and pulled out as assignments. Examples ======== >>> from sympy import symbols, ccode >>> from sympy.codegen.ast import CodeBlock, Assignment >>> x, y = symbols('x y') >>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1)) >>> print(ccode(c)) x = 1; y = x + 1; """ def __new__(cls, *args): left_hand_sides = [] right_hand_sides = [] for i in args: if isinstance(i, Assignment): lhs, rhs = i.args left_hand_sides.append(lhs) right_hand_sides.append(rhs) obj = CodegenAST.__new__(cls, *args) obj.left_hand_sides = Tuple(*left_hand_sides) obj.right_hand_sides = Tuple(*right_hand_sides) return obj def __iter__(self): return iter(self.args) def _sympyrepr(self, printer, *args, **kwargs): il = printer._context.get('indent_level', 0) joiner = ',\n' + ' '*il joined = joiner.join(map(printer._print, self.args)) return ('{}(\n'.format(' '*(il-4) + self.__class__.__name__,) + ' '*il + joined + '\n' + ' '*(il - 4) + ')') _sympystr = _sympyrepr @property def free_symbols(self): return super().free_symbols - set(self.left_hand_sides) @classmethod def topological_sort(cls, assignments): """ Return a CodeBlock with topologically sorted assignments so that variables are assigned before they are used. Examples ======== The existing order of assignments is preserved as much as possible. This function assumes that variables are assigned to only once. This is a class constructor so that the default constructor for CodeBlock can error when variables are used before they are assigned. >>> from sympy import symbols >>> from sympy.codegen.ast import CodeBlock, Assignment >>> x, y, z = symbols('x y z') >>> assignments = [ ... Assignment(x, y + z), ... Assignment(y, z + 1), ... Assignment(z, 2), ... ] >>> CodeBlock.topological_sort(assignments) CodeBlock( Assignment(z, 2), Assignment(y, z + 1), Assignment(x, y + z) ) """ if not all(isinstance(i, Assignment) for i in assignments): # Will support more things later raise NotImplementedError("CodeBlock.topological_sort only supports Assignments") if any(isinstance(i, AugmentedAssignment) for i in assignments): raise NotImplementedError("CodeBlock.topological_sort does not yet work with AugmentedAssignments") # Create a graph where the nodes are assignments and there is a directed edge # between nodes that use a variable and nodes that assign that # variable, like # [(x := 1, y := x + 1), (x := 1, z := y + z), (y := x + 1, z := y + z)] # If we then topologically sort these nodes, they will be in # assignment order, like # x := 1 # y := x + 1 # z := y + z # A = The nodes # # enumerate keeps nodes in the same order they are already in if # possible. It will also allow us to handle duplicate assignments to # the same variable when those are implemented. A = list(enumerate(assignments)) # var_map = {variable: [nodes for which this variable is assigned to]} # like {x: [(1, x := y + z), (4, x := 2 * w)], ...} var_map = defaultdict(list) for node in A: i, a = node var_map[a.lhs].append(node) # E = Edges in the graph E = [] for dst_node in A: i, a = dst_node for s in a.rhs.free_symbols: for src_node in var_map[s]: E.append((src_node, dst_node)) ordered_assignments = topological_sort([A, E]) # De-enumerate the result return cls(*[a for i, a in ordered_assignments]) def cse(self, symbols=None, optimizations=None, postprocess=None, order='canonical'): """ Return a new code block with common subexpressions eliminated. Explanation =========== See the docstring of :func:`sympy.simplify.cse_main.cse` for more information. Examples ======== >>> from sympy import symbols, sin >>> from sympy.codegen.ast import CodeBlock, Assignment >>> x, y, z = symbols('x y z') >>> c = CodeBlock( ... Assignment(x, 1), ... Assignment(y, sin(x) + 1), ... Assignment(z, sin(x) - 1), ... ) ... >>> c.cse() CodeBlock( Assignment(x, 1), Assignment(x0, sin(x)), Assignment(y, x0 + 1), Assignment(z, x0 - 1) ) """ from sympy.simplify.cse_main import cse # Check that the CodeBlock only contains assignments to unique variables if not all(isinstance(i, Assignment) for i in self.args): # Will support more things later raise NotImplementedError("CodeBlock.cse only supports Assignments") if any(isinstance(i, AugmentedAssignment) for i in self.args): raise NotImplementedError("CodeBlock.cse does not yet work with AugmentedAssignments") for i, lhs in enumerate(self.left_hand_sides): if lhs in self.left_hand_sides[:i]: raise NotImplementedError("Duplicate assignments to the same " "variable are not yet supported (%s)" % lhs) # Ensure new symbols for subexpressions do not conflict with existing existing_symbols = self.atoms(Symbol) if symbols is None: symbols = numbered_symbols() symbols = filter_symbols(symbols, existing_symbols) replacements, reduced_exprs = cse(list(self.right_hand_sides), symbols=symbols, optimizations=optimizations, postprocess=postprocess, order=order) new_block = [Assignment(var, expr) for var, expr in zip(self.left_hand_sides, reduced_exprs)] new_assignments = [Assignment(var, expr) for var, expr in replacements] return self.topological_sort(new_assignments + new_block)
CodeBlock
python
automl__auto-sklearn
test/test_pipeline/components/feature_preprocessing/test_fast_ica.py
{ "start": 276, "end": 1715 }
class ____(PreprocessingTestCase): def test_default_configuration(self): transformation, original = _test_preprocessing(FastICA, dataset="diabetes") self.assertEqual(transformation.shape[0], original.shape[0]) self.assertFalse((transformation == 0).all()) def test_default_configuration_regression(self): for i in range(5): X_train, Y_train, X_test, Y_test = get_dataset(dataset="diabetes") configuration_space = FastICA.get_hyperparameter_search_space() default = configuration_space.get_default_configuration() preprocessor = FastICA( random_state=1, **{hp_name: default[hp_name] for hp_name in default} ) preprocessor.fit(X_train, Y_train) X_train_trans = preprocessor.transform(X_train) X_test_trans = preprocessor.transform(X_test) # fit a classifier on top classifier = Ridge() predictor = classifier.fit(X_train_trans, Y_train) predictions = predictor.predict(X_test_trans) accuracy = sklearn.metrics.r2_score(Y_test, predictions) self.assertAlmostEqual(accuracy, 0.32614416980439365) @unittest.skip("Always returns float64") def test_preprocessing_dtype(self): super(FastICAComponentTest, self)._test_preprocessing_dtype( FastICA, dataset="diabetes" )
FastICAComponentTest
python
run-llama__llama_index
llama-index-core/llama_index/core/instrumentation/events/embedding.py
{ "start": 908, "end": 1311 }
class ____(BaseEvent): """ EmbeddingStartEvent. Args: model_dict (dict): Model dictionary containing details about the embedding model. """ model_config = ConfigDict(protected_namespaces=("pydantic_model_",)) model_dict: dict @classmethod def class_name(cls) -> str: """Class name.""" return "SparseEmbeddingStartEvent"
SparseEmbeddingStartEvent
python
kamyu104__LeetCode-Solutions
Python/maximum-number-that-sum-of-the-prices-is-less-than-or-equal-to-k.py
{ "start": 116, "end": 1487 }
class ____(object): def findMaximumNumber(self, k, x): """ :type k: int :type x: int :rtype: int """ def floor_log2(x): return x.bit_length()-1 def binary_search_right(left, right, check): while left <= right: mid = left+(right-left)//2 if not check(mid): right = mid-1 else: left = mid+1 return right def count(l): return (prefix_cnt<<(x*l))+lookup[l] result = prefix_cnt = 0 lookup = [0] i = 0 while (lookup[-1]<<x)+(1<<(i+x-1)) <= k: lookup.append((lookup[-1]<<x)+(1<<(i+x-1))) i += x while k >= prefix_cnt: # l = result.bit_length() # assert(prefix_cnt == sum(c == '1' and (l-i)%x == 0 for i, c in enumerate(bin(result)[2:]))) l = binary_search_right(1, len(lookup)-1, lambda l: count(l) <= k) cnt, i = count(l), x*l c = min(floor_log2(k//cnt) if cnt else float("inf"), x-1) cnt <<= c i += c k -= cnt result += 1<<i prefix_cnt += int((i+1)%x == 0) return result-1 # Time: O(max(logk, x) * (max(logk, x) / x)) # Space: O(1) # bit manipulation, combinatorics
Solution
python
dask__dask
dask/array/random.py
{ "start": 708, "end": 17670 }
class ____: """ Container for the BitGenerators. ``Generator`` exposes a number of methods for generating random numbers drawn from a variety of probability distributions and serves as a replacement for ``RandomState``. The main difference between the two is that ``Generator`` relies on an additional ``BitGenerator`` to manage state and generate the random bits, which are then transformed into random values from useful distributions. The default ``BitGenerator`` used by ``Generator`` is ``PCG64``. The ``BitGenerator`` can be changed by passing an instantiated ``BitGenerator`` to ``Generator``. The function :func:`dask.array.random.default_rng` is the recommended way to instantiate a ``Generator``. .. warning:: No Compatibility Guarantee. ``Generator`` does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change. Parameters ---------- bit_generator : BitGenerator BitGenerator to use as the core generator. Notes ----- In addition to the distribution-specific arguments, each ``Generator`` method takes a keyword argument `size` that defaults to ``None``. If `size` is ``None``, then a single value is generated and returned. If `size` is an integer, then a 1-D array filled with generated values is returned. If `size` is a tuple, then an array with that shape is filled and returned. The Python stdlib module `random` contains pseudo-random number generator with a number of methods that are similar to the ones available in ``Generator``. It uses Mersenne Twister, and this bit generator can be accessed using ``MT19937``. ``Generator``, besides being Dask-aware, has the advantage that it provides a much larger number of probability distributions to choose from. All ``Generator`` methods are identical to ``np.random.Generator`` except that they also take a `chunks=` keyword argument. ``Generator`` does not guarantee parity in the generated numbers with any third party library. In particular, numbers generated by `Dask` and `NumPy` will differ even if they use the same seed. Examples -------- >>> from numpy.random import PCG64 >>> from dask.array.random import Generator >>> rng = Generator(PCG64()) >>> rng.standard_normal().compute() # doctest: +SKIP array(0.44595957) # random See Also -------- default_rng : Recommended constructor for `Generator`. np.random.Generator """ def __init__(self, bit_generator): self._bit_generator = bit_generator def __str__(self): return f"{self.__class__.__name__}({self._bit_generator.__class__.__name__})" @property def _backend_name(self): # Assumes typename(self._RandomState) starts with an # array-library name (e.g. "numpy" or "cupy") return typename(self._bit_generator).split(".")[0] @property def _backend(self): # Assumes `self._backend_name` is an importable # array-library name (e.g. "numpy" or "cupy") return importlib.import_module(self._backend_name) @derived_from(np.random.Generator, skipblocks=1) def beta(self, a, b, size=None, chunks="auto", **kwargs): return _wrap_func(self, "beta", a, b, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def binomial(self, n, p, size=None, chunks="auto", **kwargs): return _wrap_func(self, "binomial", n, p, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def chisquare(self, df, size=None, chunks="auto", **kwargs): return _wrap_func(self, "chisquare", df, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def choice( self, a, size=None, replace=True, p=None, axis=0, shuffle=True, chunks="auto", ): ( a, size, replace, p, axis, chunks, meta, dependencies, ) = _choice_validate_params(self, a, size, replace, p, axis, chunks) sizes = list(product(*chunks)) bitgens = _spawn_bitgens(self._bit_generator, len(sizes)) name = f"da.random.choice-{tokenize(bitgens, size, chunks, a, replace, p, axis, shuffle)}" keys = product([name], *(range(len(bd)) for bd in chunks)) dsk = { k: Task(k, _choice_rng, bitgen, a, size, replace, p, axis, shuffle) for k, bitgen, size in zip(keys, bitgens, sizes) } graph = HighLevelGraph.from_collections(name, dsk, dependencies=dependencies) return Array(graph, name, chunks, meta=meta) @derived_from(np.random.Generator, skipblocks=1) def exponential(self, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "exponential", scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def f(self, dfnum, dfden, size=None, chunks="auto", **kwargs): return _wrap_func(self, "f", dfnum, dfden, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def gamma(self, shape, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "gamma", shape, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def geometric(self, p, size=None, chunks="auto", **kwargs): return _wrap_func(self, "geometric", p, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def gumbel(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "gumbel", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def hypergeometric(self, ngood, nbad, nsample, size=None, chunks="auto", **kwargs): return _wrap_func( self, "hypergeometric", ngood, nbad, nsample, size=size, chunks=chunks, **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def integers( self, low, high=None, size=None, dtype=np.int64, endpoint=False, chunks="auto", **kwargs, ): return _wrap_func( self, "integers", low, high=high, size=size, dtype=dtype, endpoint=endpoint, chunks=chunks, **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def laplace(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "laplace", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def logistic(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "logistic", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def lognormal(self, mean=0.0, sigma=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "lognormal", mean, sigma, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def logseries(self, p, size=None, chunks="auto", **kwargs): return _wrap_func(self, "logseries", p, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def multinomial(self, n, pvals, size=None, chunks="auto", **kwargs): return _wrap_func( self, "multinomial", n, pvals, size=size, chunks=chunks, extra_chunks=((len(pvals),),), **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def multivariate_hypergeometric( self, colors, nsample, size=None, method="marginals", chunks="auto", **kwargs ): return _wrap_func( self, "multivariate_hypergeometric", colors, nsample, size=size, method=method, chunks=chunks, **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def negative_binomial(self, n, p, size=None, chunks="auto", **kwargs): return _wrap_func( self, "negative_binomial", n, p, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def noncentral_chisquare(self, df, nonc, size=None, chunks="auto", **kwargs): return _wrap_func( self, "noncentral_chisquare", df, nonc, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def noncentral_f(self, dfnum, dfden, nonc, size=None, chunks="auto", **kwargs): return _wrap_func( self, "noncentral_f", dfnum, dfden, nonc, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def normal(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "normal", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def pareto(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "pareto", a, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def permutation(self, x): from dask.array.slicing import shuffle_slice if self._backend_name == "cupy": raise NotImplementedError( "`Generator.permutation` not supported for cupy-backed " "Generator objects. Use the 'numpy' array backend to " "call `dask.array.random.default_rng`, or pass in " " `numpy.random.PCG64()`." ) if isinstance(x, numbers.Number): x = arange(x, chunks="auto") index = self._backend.arange(len(x)) _shuffle(self._bit_generator, index) return shuffle_slice(x, index) @derived_from(np.random.Generator, skipblocks=1) def poisson(self, lam=1.0, size=None, chunks="auto", **kwargs): return _wrap_func(self, "poisson", lam, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def power(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "power", a, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def random(self, size=None, dtype=np.float64, out=None, chunks="auto", **kwargs): return _wrap_func( self, "random", size=size, dtype=dtype, out=out, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def rayleigh(self, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func(self, "rayleigh", scale, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def standard_cauchy(self, size=None, chunks="auto", **kwargs): return _wrap_func(self, "standard_cauchy", size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def standard_exponential(self, size=None, chunks="auto", **kwargs): return _wrap_func( self, "standard_exponential", size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def standard_gamma(self, shape, size=None, chunks="auto", **kwargs): return _wrap_func( self, "standard_gamma", shape, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def standard_normal(self, size=None, chunks="auto", **kwargs): return _wrap_func(self, "standard_normal", size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def standard_t(self, df, size=None, chunks="auto", **kwargs): return _wrap_func(self, "standard_t", df, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def triangular(self, left, mode, right, size=None, chunks="auto", **kwargs): return _wrap_func( self, "triangular", left, mode, right, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def uniform(self, low=0.0, high=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "uniform", low, high, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def vonmises(self, mu, kappa, size=None, chunks="auto", **kwargs): return _wrap_func( self, "vonmises", mu, kappa, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def wald(self, mean, scale, size=None, chunks="auto", **kwargs): return _wrap_func(self, "wald", mean, scale, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def weibull(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "weibull", a, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def zipf(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "zipf", a, size=size, chunks=chunks, **kwargs) def default_rng(seed=None): """ Construct a new Generator with the default BitGenerator (PCG64). Parameters ---------- seed : {None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional A seed to initialize the `BitGenerator`. If None, then fresh, unpredictable entropy will be pulled from the OS. If an ``int`` or ``array_like[ints]`` is passed, then it will be passed to `SeedSequence` to derive the initial `BitGenerator` state. One may also pass in a `SeedSequence` instance. Additionally, when passed a `BitGenerator`, it will be wrapped by `Generator`. If passed a `Generator`, it will be returned unaltered. Returns ------- Generator The initialized generator object. Notes ----- If ``seed`` is not a `BitGenerator` or a `Generator`, a new `BitGenerator` is instantiated. This function does not manage a default global instance. Examples -------- ``default_rng`` is the recommended constructor for the random number class ``Generator``. Here are several ways we can construct a random number generator using ``default_rng`` and the ``Generator`` class. Here we use ``default_rng`` to generate a random float: >>> import dask.array as da >>> rng = da.random.default_rng(12345) >>> print(rng) Generator(PCG64) >>> rfloat = rng.random().compute() >>> rfloat array(0.86999885) >>> type(rfloat) <class 'numpy.ndarray'> Here we use ``default_rng`` to generate 3 random integers between 0 (inclusive) and 10 (exclusive): >>> import dask.array as da >>> rng = da.random.default_rng(12345) >>> rints = rng.integers(low=0, high=10, size=3).compute() >>> rints array([2, 8, 7]) >>> type(rints[0]) <class 'numpy.int64'> Here we specify a seed so that we have reproducible results: >>> import dask.array as da >>> rng = da.random.default_rng(seed=42) >>> print(rng) Generator(PCG64) >>> arr1 = rng.random((3, 3)).compute() >>> arr1 array([[0.91674416, 0.91098667, 0.8765925 ], [0.30931841, 0.95465607, 0.17509458], [0.99662814, 0.75203348, 0.15038118]]) If we exit and restart our Python interpreter, we'll see that we generate the same random numbers again: >>> import dask.array as da >>> rng = da.random.default_rng(seed=42) >>> arr2 = rng.random((3, 3)).compute() >>> arr2 array([[0.91674416, 0.91098667, 0.8765925 ], [0.30931841, 0.95465607, 0.17509458], [0.99662814, 0.75203348, 0.15038118]]) See Also -------- np.random.default_rng """ if hasattr(seed, "capsule"): # We are passed a BitGenerator, so just wrap it return Generator(seed) elif isinstance(seed, Generator): # Pass through a Generator return seed elif hasattr(seed, "bit_generator"): # a Generator. Just not ours return Generator(seed.bit_generator) # Otherwise, use the backend-default BitGenerator return Generator(array_creation_dispatch.default_bit_generator(seed))
Generator
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 12626, "end": 12829 }
class ____(Stmt): """A node that represents the include tag.""" fields = ("template", "with_context", "ignore_missing") template: "Expr" with_context: bool ignore_missing: bool
Include
python
huggingface__transformers
src/transformers/models/detr/modeling_detr.py
{ "start": 17265, "end": 18710 }
class ____(nn.Module): """ This module learns positional embeddings up to a fixed maximum size. """ def __init__(self, embedding_dim=256): super().__init__() self.row_embeddings = nn.Embedding(50, embedding_dim) self.column_embeddings = nn.Embedding(50, embedding_dim) def forward(self, pixel_values, pixel_mask=None): height, width = pixel_values.shape[-2:] width_values = torch.arange(width, device=pixel_values.device) height_values = torch.arange(height, device=pixel_values.device) x_emb = self.column_embeddings(width_values) y_emb = self.row_embeddings(height_values) pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1) pos = pos.permute(2, 0, 1) pos = pos.unsqueeze(0) pos = pos.repeat(pixel_values.shape[0], 1, 1, 1) return pos def build_position_encoding(config): n_steps = config.d_model // 2 if config.position_embedding_type == "sine": # TODO find a better way of exposing other arguments position_embedding = DetrSinePositionEmbedding(n_steps, normalize=True) elif config.position_embedding_type == "learned": position_embedding = DetrLearnedPositionEmbedding(n_steps) else: raise ValueError(f"Not supported {config.position_embedding_type}") return position_embedding
DetrLearnedPositionEmbedding
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-azcognitive-search/llama_index/readers/azcognitive_search/base.py
{ "start": 331, "end": 2070 }
class ____(BaseReader): """ General reader for any Azure Cognitive Search index reader. Args: service_name (str): the name of azure cognitive search service. search_key (str): provide azure search access key directly. index (str): index name """ def __init__(self, service_name: str, searck_key: str, index: str) -> None: """Initialize Azure cognitive search service using the search key.""" import logging logger = logging.getLogger("azure.core.pipeline.policies.http_logging_policy") logger.setLevel(logging.WARNING) azure_credential = AzureKeyCredential(searck_key) self.search_client = SearchClient( endpoint=f"https://{service_name}.search.windows.net", index_name=index, credential=azure_credential, ) def load_data( self, query: str, content_field: str, filter: Optional[str] = None ) -> List[Document]: """ Read data from azure cognitive search index. Args: query (str): search term in Azure Search index content_field (str): field name of the document content. filter (str): Filter expression. For example : 'sourcepage eq 'employee_handbook-3.pdf' and sourcefile eq 'employee_handbook.pdf'' Returns: List[Document]: A list of documents. """ search_result = self.search_client.search(query, filter=filter) return [ Document( text=result[content_field], extra_info={"id": result["id"], "score": result["@search.score"]}, ) for result in search_result ]
AzCognitiveSearchReader
python
pypa__setuptools
setuptools/_distutils/tests/test_build_ext.py
{ "start": 22341, "end": 22539 }
class ____(TestBuildExt): def build_ext(self, *args, **kwargs): build_ext = super().build_ext(*args, **kwargs) build_ext.parallel = True return build_ext
TestParallelBuildExt
python
getsentry__sentry
src/sentry/interfaces/contexts.py
{ "start": 6017, "end": 6178 }
class ____(ContextType): type = "device" context_to_tag_mapping = {"": "{model}", "family": "{family}"} # model_id, arch @contexttype
DeviceContextType
python
pydantic__pydantic
tests/test_forward_ref.py
{ "start": 13108, "end": 13148 }
class ____: literal: Literal[1, 2]
Base
python
pytest-dev__pytest
testing/test_terminal.py
{ "start": 98743, "end": 110958 }
class ____: DEFAULT_FILE_CONTENTS = """ import pytest @pytest.mark.parametrize("i", range(4)) def test_ok(i): ''' some docstring ''' pass def test_fail(): assert False """ LONG_SKIP_FILE_CONTENTS = """ import pytest @pytest.mark.skip( "some long skip reason that will not fit on a single line with other content that goes" " on and on and on and on and on" ) def test_skip(): pass """ @pytest.mark.parametrize("verbosity", [1, 2]) def test_execute_positive(self, verbosity, pytester: Pytester) -> None: # expected: one test case per line (with file name), word describing result p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=verbosity) result = pytester.runpytest(p) result.stdout.fnmatch_lines( [ "collected 5 items", "", f"{p.name}::test_ok[0] PASSED [ 20%]", f"{p.name}::test_ok[1] PASSED [ 40%]", f"{p.name}::test_ok[2] PASSED [ 60%]", f"{p.name}::test_ok[3] PASSED [ 80%]", f"{p.name}::test_fail FAILED [100%]", ], consecutive=True, ) def test_execute_0_global_1(self, pytester: Pytester) -> None: # expected: one file name per line, single character describing result p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=0) result = pytester.runpytest("-v", p) result.stdout.fnmatch_lines( [ "collecting ... collected 5 items", "", f"{p.name} ....F [100%]", ], consecutive=True, ) @pytest.mark.parametrize("verbosity", [-1, -2]) def test_execute_negative(self, verbosity, pytester: Pytester) -> None: # expected: single character describing result p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=verbosity) result = pytester.runpytest(p) result.stdout.fnmatch_lines( [ "collected 5 items", "....F [100%]", ], consecutive=True, ) def test_execute_skipped_positive_2(self, pytester: Pytester) -> None: # expected: one test case per line (with file name), word describing result, full reason p = TestFineGrainedTestCase._initialize_files( pytester, verbosity=2, file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS, ) result = pytester.runpytest(p) result.stdout.fnmatch_lines( [ "collected 1 item", "", f"{p.name}::test_skip SKIPPED (some long skip", "reason that will not fit on a single line with other content that goes", "on and on and on and on and on) [100%]", ], consecutive=True, ) def test_execute_skipped_positive_1(self, pytester: Pytester) -> None: # expected: one test case per line (with file name), word describing result, reason truncated p = TestFineGrainedTestCase._initialize_files( pytester, verbosity=1, file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS, ) result = pytester.runpytest(p) result.stdout.fnmatch_lines( [ "collected 1 item", "", f"{p.name}::test_skip SKIPPED (some long ski...) [100%]", ], consecutive=True, ) def test_execute_skipped__0_global_1(self, pytester: Pytester) -> None: # expected: one file name per line, single character describing result (no reason) p = TestFineGrainedTestCase._initialize_files( pytester, verbosity=0, file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS, ) result = pytester.runpytest("-v", p) result.stdout.fnmatch_lines( [ "collecting ... collected 1 item", "", f"{p.name} s [100%]", ], consecutive=True, ) @pytest.mark.parametrize("verbosity", [-1, -2]) def test_execute_skipped_negative(self, verbosity, pytester: Pytester) -> None: # expected: single character describing result (no reason) p = TestFineGrainedTestCase._initialize_files( pytester, verbosity=verbosity, file_contents=TestFineGrainedTestCase.LONG_SKIP_FILE_CONTENTS, ) result = pytester.runpytest(p) result.stdout.fnmatch_lines( [ "collected 1 item", "s [100%]", ], consecutive=True, ) @pytest.mark.parametrize("verbosity", [1, 2]) def test__collect_only_positive(self, verbosity, pytester: Pytester) -> None: p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=verbosity) result = pytester.runpytest("--collect-only", p) result.stdout.fnmatch_lines( [ "collected 5 items", "", f"<Dir {p.parent.name}>", f" <Module {p.name}>", " <Function test_ok[0]>", " some docstring", " <Function test_ok[1]>", " some docstring", " <Function test_ok[2]>", " some docstring", " <Function test_ok[3]>", " some docstring", " <Function test_fail>", ], consecutive=True, ) def test_collect_only_0_global_1(self, pytester: Pytester) -> None: p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=0) result = pytester.runpytest("-v", "--collect-only", p) result.stdout.fnmatch_lines( [ "collecting ... collected 5 items", "", f"<Dir {p.parent.name}>", f" <Module {p.name}>", " <Function test_ok[0]>", " <Function test_ok[1]>", " <Function test_ok[2]>", " <Function test_ok[3]>", " <Function test_fail>", ], consecutive=True, ) def test_collect_only_negative_1(self, pytester: Pytester) -> None: p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=-1) result = pytester.runpytest("--collect-only", p) result.stdout.fnmatch_lines( [ "collected 5 items", "", f"{p.name}::test_ok[0]", f"{p.name}::test_ok[1]", f"{p.name}::test_ok[2]", f"{p.name}::test_ok[3]", f"{p.name}::test_fail", ], consecutive=True, ) def test_collect_only_negative_2(self, pytester: Pytester) -> None: p = TestFineGrainedTestCase._initialize_files(pytester, verbosity=-2) result = pytester.runpytest("--collect-only", p) result.stdout.fnmatch_lines( [ "collected 5 items", "", f"{p.name}: 5", ], consecutive=True, ) @staticmethod def _initialize_files( pytester: Pytester, verbosity: int, file_contents: str = DEFAULT_FILE_CONTENTS ) -> Path: p = pytester.makepyfile(file_contents) pytester.makeini( f""" [pytest] verbosity_test_cases = {verbosity} """ ) return p def test_summary_xfail_reason(pytester: Pytester) -> None: pytester.makepyfile( """ import pytest @pytest.mark.xfail def test_xfail(): assert False @pytest.mark.xfail(reason="foo") def test_xfail_reason(): assert False """ ) result = pytester.runpytest("-rx") expect1 = "XFAIL test_summary_xfail_reason.py::test_xfail" expect2 = "XFAIL test_summary_xfail_reason.py::test_xfail_reason - foo" result.stdout.fnmatch_lines([expect1, expect2]) assert result.stdout.lines.count(expect1) == 1 assert result.stdout.lines.count(expect2) == 1 @pytest.fixture() def xfail_testfile(pytester: Pytester) -> Path: return pytester.makepyfile( """ import pytest def test_fail(): a, b = 1, 2 assert a == b @pytest.mark.xfail def test_xfail(): c, d = 3, 4 assert c == d """ ) def test_xfail_tb_default(xfail_testfile, pytester: Pytester) -> None: result = pytester.runpytest(xfail_testfile) # test_fail, show traceback result.stdout.fnmatch_lines( [ "*= FAILURES =*", "*_ test_fail _*", "*def test_fail():*", "* a, b = 1, 2*", "*> assert a == b*", "*E assert 1 == 2*", ] ) # test_xfail, don't show traceback result.stdout.no_fnmatch_line("*= XFAILURES =*") def test_xfail_tb_true(xfail_testfile, pytester: Pytester) -> None: result = pytester.runpytest(xfail_testfile, "--xfail-tb") # both test_fail and test_xfail, show traceback result.stdout.fnmatch_lines( [ "*= FAILURES =*", "*_ test_fail _*", "*def test_fail():*", "* a, b = 1, 2*", "*> assert a == b*", "*E assert 1 == 2*", "*= XFAILURES =*", "*_ test_xfail _*", "*def test_xfail():*", "* c, d = 3, 4*", "*> assert c == d*", "*E assert 3 == 4*", "*short test summary info*", ] ) def test_xfail_tb_line(xfail_testfile, pytester: Pytester) -> None: result = pytester.runpytest(xfail_testfile, "--xfail-tb", "--tb=line") # both test_fail and test_xfail, show line result.stdout.fnmatch_lines( [ "*= FAILURES =*", "*test_xfail_tb_line.py:5: assert 1 == 2", "*= XFAILURES =*", "*test_xfail_tb_line.py:10: assert 3 == 4", "*short test summary info*", ] ) def test_summary_xpass_reason(pytester: Pytester) -> None: pytester.makepyfile( """ import pytest @pytest.mark.xfail def test_pass(): ... @pytest.mark.xfail(reason="foo") def test_reason(): ... """ ) result = pytester.runpytest("-rX") expect1 = "XPASS test_summary_xpass_reason.py::test_pass" expect2 = "XPASS test_summary_xpass_reason.py::test_reason - foo" result.stdout.fnmatch_lines([expect1, expect2]) assert result.stdout.lines.count(expect1) == 1 assert result.stdout.lines.count(expect2) == 1 def test_xpass_output(pytester: Pytester) -> None: pytester.makepyfile( """ import pytest @pytest.mark.xfail def test_pass(): print('hi there') """ ) result = pytester.runpytest("-rX") result.stdout.fnmatch_lines( [ "*= XPASSES =*", "*_ test_pass _*", "*- Captured stdout call -*", "*= short test summary info =*", "XPASS test_xpass_output.py::test_pass*", "*= 1 xpassed in * =*", ] )
TestFineGrainedTestCase
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py
{ "start": 45962, "end": 48046 }
class ____(TestQueuedEventEndpoint): @pytest.mark.usefixtures("time_freezer") def test_should_respond_204(self, test_client, session, create_dummy_dag): dag, _ = create_dummy_dag() dag_id = dag.dag_id self.create_assets(session=session, num=1) asset_id = 1 self._create_asset_dag_run_queues(dag_id, asset_id, session) adrqs = session.query(AssetDagRunQueue).all() assert len(adrqs) == 1 response = test_client.delete( f"/dags/{dag_id}/assets/queuedEvents", ) assert response.status_code == 204 adrqs = session.query(AssetDagRunQueue).all() assert len(adrqs) == 0 check_last_log(session, dag_id=dag_id, event="delete_dag_asset_queued_events", logical_date=None) def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.delete("/dags/random/assets/queuedEvents") assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.get("/dags/random/assets/queuedEvents") assert response.status_code == 403 def test_should_respond_404_invalid_dag(self, test_client): dag_id = "not_exists" response = test_client.delete( f"/dags/{dag_id}/assets/queuedEvents", ) assert response.status_code == 404 assert response.json()["detail"] == "Queue event with dag_id: `not_exists` was not found" def test_should_respond_404_valid_dag_no_adrq(self, test_client, session, create_dummy_dag): dag, _ = create_dummy_dag() dag_id = dag.dag_id self.create_assets(session=session, num=1) adrqs = session.query(AssetDagRunQueue).all() assert len(adrqs) == 0 response = test_client.delete( f"/dags/{dag_id}/assets/queuedEvents", ) assert response.status_code == 404 assert response.json()["detail"] == "Queue event with dag_id: `dag` was not found"
TestDeleteDagDatasetQueuedEvents
python
xlwings__xlwings
xlwings/constants.py
{ "start": 8908, "end": 9047 }
class ____: xlAllocateIncrement = 2 # from enum XlAllocationValue xlAllocateValue = 1 # from enum XlAllocationValue
AllocationValue
python
tensorflow__tensorflow
tensorflow/python/ops/numpy_ops/tests/np_einsum_test.py
{ "start": 1099, "end": 9188 }
class ____(tntu.TestCase): def _check(self, s, *ops): a = np.einsum(s, *ops) b = tnp.einsum(s, *ops) self.assertAllClose(a, b, check_dtypes=True, atol=1e-4, rtol=1e-4) def test_three_operands_1(self): r = self.rng() x = r.randn(3) y = r.randn(4) z = r.randn(5) s = 'i,j,k->ijk' self._check(s, x, y, z) def test_three_operands_2(self): r = self.rng() x = r.randn(3) y = r.randn(4) z = r.randn(5) s = 'i,j,k->ijk' self._check(s, x, y, z) def test_two_operands_1(self): r = self.rng() x = r.randn(3, 4) y = r.randn(4) s = 'ij,j->i' self._check(s, x, y) def test_two_operands_2(self): r = self.rng() x = r.randn(3, 4, 5) y = r.randn(4) s = 'ijk,j->i' self._check(s, x, y) def test_two_operands_3(self): r = self.rng() x = r.randn(3, 4, 3) y = r.randn(3) s = 'iji,i->j' self._check(s, x, y) def test_two_operands_4(self): r = self.rng() x = r.randn(3, 4) y = r.randn(3, 4) s = 'ij,ij->' self._check(s, x, y) def test_two_operands_5(self): r = self.rng() x = r.randn(10, 2, 3) y = r.randn(3, 4) s = 'nij,jk->nik' self._check(s, x, y) def test_two_operands_6(self): # based on https://github.com/google/jax/issues/37#issuecomment-448572187 r = self.rng() x = r.randn(2, 1) y = r.randn(2, 3, 4) s = 'sa,shb->shab' self._check(s, x, y) def test_one_operand_1(self): r = self.rng() x = r.randn(3, 4, 5) s = 'ijk->j' self._check(s, x) def test_one_operand_2(self): r = self.rng() x = r.randn(3, 4, 5) s = 'ijk->kij' self._check(s, x) def test_one_operand_3(self): r = self.rng() x = r.randn(3, 4, 5) s = 'ijk->ki' self._check(s, x) def test_one_operand_4(self): r = self.rng() x = r.randn(3, 4, 5) s = 'ijk->ki' self._check(s, x) def test_one_operand_5(self): r = self.rng() x = r.randn(2, 3, 4, 5) s = '...ijk->...ki' self._check(s, x) def test_one_operand_6(self): r = self.rng() x = r.randn(3, 4, 5) s = '...ijk->ki' self._check(s, x) def test_one_operand_7(self): r = self.rng() x = r.randn(3, 3) s = 'ii->' self._check(s, x) def test_one_operand_8(self): r = self.rng() x = r.randn(3, 3) s = 'ij->' self._check(s, x) def test_one_operand_9(self): r = self.rng() x = r.randn(3, 3, 3) s = 'iii->' self._check(s, x) def test_one_operand_10(self): r = self.rng() x = r.randn(3, 3) s = 'ii->i' self._check(s, x) def test_one_operand_11(self): r = self.rng() x = r.randn(3, 3, 4) s = 'iij->i' self._check(s, x) def test_one_operand_12(self): r = self.rng() x = r.randn(3, 3, 3) s = 'iii->i' self._check(s, x) def test_one_operand_13(self): r = self.rng() x = r.randn(3, 3, 5, 4, 4) s = 'iijkk->i' self._check(s, x) def test_one_operand_14(self): r = self.rng() x = r.randn(3, 3, 5, 4, 4) s = 'iijkk->ik' self._check(s, x) def test_one_operand_15(self): r = self.rng() x = r.randn(3, 3, 5, 4, 4) s = 'iijkl->il' self._check(s, x) def test_one_operand_16(self): r = self.rng() x = r.randn(3, 3) s = 'ij->ij' self._check(s, x) def test_tf_unsupported_1(self): # from https://www.tensorflow.org/api_docs/python/tf/einsum r = self.rng() x = r.randn(2, 3, 5, 1) y = r.randn(3, 4, 5, 1) s = 'ij...,jk...->ik...' self._check(s, x, y) def test_tf_unsupported_2(self): # from https://www.tensorflow.org/api_docs/python/tf/einsum r = self.rng() x = r.randn(2, 3, 3) y = r.randn(4) s = 'ijj,k->ik' self._check(s, x, y) def test_tf_unsupported_3(self): # from https://www.tensorflow.org/api_docs/python/tf/einsum r = self.rng() x = r.randn(2, 3) y = r.randn(2, 3) z = r.randn(3, 4) s = 'ij,ij,jk->ik' self._check(s, x, y, z) # these tests are based on https://github.com/dask/dask/pull/3412/files @parameterized.named_parameters( {'testcase_name': '_{}_dtype={}'.format(einstr, dtype.__name__), # pylint: disable=g-complex-comprehension 'einstr': einstr, 'dtype': dtype} for einstr in [ 'abc,bad->abcd', 'abcdef,bcdfg->abcdeg', 'ea,fb,abcd,gc,hd->efgh', 'ab,b', 'aa', 'a,a->', 'a,a->a', 'a,a', 'a,b', 'a,b,c', 'a', 'ba,b', 'ba,b->', 'defab,fedbc->defac', 'ab...,bc...->ac...', 'a...a', 'abc...->cba...', '...ab->...a', 'a...a->a...', # Following 2 from # https://stackoverflow.com/a/19203475/1611416 '...abc,...abcd->...d', 'ab...,b->ab...', # https://github.com/dask/dask/pull/3412#discussion_r182413444 'aa->a', 'ab,ab,c->c', 'aab,bc->ac', 'aab,bcc->ac', 'fdf,cdd,ccd,afe->ae', 'fff,fae,bef,def->abd', ] # TODO(wangpeng): Add tnp.bool_ to dtype list for dtype in [tnp.float32, tnp.int32, tnp.complex64]) def test_from_dask(self, einstr, dtype): r = tntu.rand_default() if '->' in einstr: input_str, _ = einstr.split('->') else: input_str = einstr input_names = input_str.split(',') dims = itertools.cycle([2, 3, 4]) shapes = defaultdict(lambda: next(dims)) input_shapes = [tuple(shapes[c] for c in names.replace('...', '01')) for names in input_names] operands = [r(shape, dtype) for shape in input_shapes] self._check(einstr, *operands) def test_ordered_front_batch_dim_case(self): x = np.ones((1, 8, 20, 4)) y = np.ones((1, 8, 20, 4)) s = 'ijkl,ijml->ijkm' self._check(s, x, y) # pylint: disable=invalid-name def test_einsum_path(self): # just check examples from np.einsum_path docstring a = self.rng().rand(2, 2) b = self.rng().rand(2, 5) c = self.rng().rand(5, 2) path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy') self.assertEqual(str(path_info[0]), "['einsum_path', (1, 2), (0, 1)]") self.assertEqual(path_info[1].split('\n')[0], ' Complete contraction: ij,jk,kl->il') # check this doesn't crash I = self.rng().rand(10, 10, 10, 10) C = self.rng().rand(10, 10) np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C, optimize='greedy') @tntu.disable def test_einsum_kpmurphy_example(self): # code from an email with @murphyk N = 2 C = 3 D = 4 K = 5 T = 6 r = self.rng() S = r.randn(N, T, K) W = r.randn(K, D) V = r.randn(D, C) L = np.zeros((N, C)) for n in range(N): for c in range(C): s = 0 for d in range(D): for k in range(K): for t in range(T): s += S[n, t, k] * W[k, d] * V[d, c] L[n, c] = s path = tnp.einsum_path('ntk,kd,dc->nc', S, W, V, optimize='optimal')[0] rtol = 1e-2 if tntu.device_under_test() == 'tpu' else None self.assertAllClose(L, tnp.einsum('ntk,kd,dc->nc', S, W, V, optimize=path), check_dtypes=False, rtol=rtol) # pylint: enable=invalid-name @tntu.disable def test_contraction_broadcasting(self): r = self.rng() x = r.randn(3, 4, 5) y = r.randn(3, 1, 6) s = 'cij,cjk->cik' self._check(s, x, y) @tntu.disable def test_batch_broadcasting(self): r = self.rng() x = r.randn(1, 4, 5) y = r.randn(3, 5, 6) s = 'cij,cjk->cik' self._check(s, x, y) @tntu.disable def test_batch_and_contraction_broadcasting(self): r = self.rng() x = r.randn(1, 4, 5) y = r.randn(3, 1, 6) s = 'cij,cjk->cik' self._check(s, x, y) @tntu.disable def test_broadcasting_issue_2189(self): r = self.rng() x = r.randn(2, 1, 3, 3) y = r.randn(2, 4, 3) s = '...ij,...j' self._check(s, x, y) if __name__ == '__main__': absltest.main()
EinsumTest
python
openai__gym
gym/envs/toy_text/blackjack.py
{ "start": 974, "end": 10806 }
class ____(gym.Env): """ Blackjack is a card game where the goal is to beat the dealer by obtaining cards that sum to closer to 21 (without going over 21) than the dealers cards. ### Description Card Values: - Face cards (Jack, Queen, King) have a point value of 10. - Aces can either count as 11 (called a 'usable ace') or 1. - Numerical cards (2-9) have a value equal to their number. This game is played with an infinite deck (or with replacement). The game starts with the dealer having one face up and one face down card, while the player has two face up cards. The player can request additional cards (hit, action=1) until they decide to stop (stick, action=0) or exceed 21 (bust, immediate loss). After the player sticks, the dealer reveals their facedown card, and draws until their sum is 17 or greater. If the dealer goes bust, the player wins. If neither the player nor the dealer busts, the outcome (win, lose, draw) is decided by whose sum is closer to 21. ### Action Space There are two actions: stick (0), and hit (1). ### Observation Space The observation consists of a 3-tuple containing: the player's current sum, the value of the dealer's one showing card (1-10 where 1 is ace), and whether the player holds a usable ace (0 or 1). This environment corresponds to the version of the blackjack problem described in Example 5.1 in Reinforcement Learning: An Introduction by Sutton and Barto (http://incompleteideas.net/book/the-book-2nd.html). ### Rewards - win game: +1 - lose game: -1 - draw game: 0 - win game with natural blackjack: +1.5 (if <a href="#nat">natural</a> is True) +1 (if <a href="#nat">natural</a> is False) ### Arguments ``` gym.make('Blackjack-v1', natural=False, sab=False) ``` <a id="nat">`natural=False`</a>: Whether to give an additional reward for starting with a natural blackjack, i.e. starting with an ace and ten (sum is 21). <a id="sab">`sab=False`</a>: Whether to follow the exact rules outlined in the book by Sutton and Barto. If `sab` is `True`, the keyword argument `natural` will be ignored. If the player achieves a natural blackjack and the dealer does not, the player will win (i.e. get a reward of +1). The reverse rule does not apply. If both the player and the dealer get a natural, it will be a draw (i.e. reward 0). ### Version History * v0: Initial versions release (1.0.0) """ metadata = { "render_modes": ["human", "rgb_array"], "render_fps": 4, } def __init__(self, render_mode: Optional[str] = None, natural=False, sab=False): self.action_space = spaces.Discrete(2) self.observation_space = spaces.Tuple( (spaces.Discrete(32), spaces.Discrete(11), spaces.Discrete(2)) ) # Flag to payout 1.5 on a "natural" blackjack win, like casino rules # Ref: http://www.bicyclecards.com/how-to-play/blackjack/ self.natural = natural # Flag for full agreement with the (Sutton and Barto, 2018) definition. Overrides self.natural self.sab = sab self.render_mode = render_mode def step(self, action): assert self.action_space.contains(action) if action: # hit: add a card to players hand and return self.player.append(draw_card(self.np_random)) if is_bust(self.player): terminated = True reward = -1.0 else: terminated = False reward = 0.0 else: # stick: play out the dealers hand, and score terminated = True while sum_hand(self.dealer) < 17: self.dealer.append(draw_card(self.np_random)) reward = cmp(score(self.player), score(self.dealer)) if self.sab and is_natural(self.player) and not is_natural(self.dealer): # Player automatically wins. Rules consistent with S&B reward = 1.0 elif ( not self.sab and self.natural and is_natural(self.player) and reward == 1.0 ): # Natural gives extra points, but doesn't autowin. Legacy implementation reward = 1.5 if self.render_mode == "human": self.render() return self._get_obs(), reward, terminated, False, {} def _get_obs(self): return (sum_hand(self.player), self.dealer[0], usable_ace(self.player)) def reset( self, seed: Optional[int] = None, options: Optional[dict] = None, ): super().reset(seed=seed) self.dealer = draw_hand(self.np_random) self.player = draw_hand(self.np_random) _, dealer_card_value, _ = self._get_obs() suits = ["C", "D", "H", "S"] self.dealer_top_card_suit = self.np_random.choice(suits) if dealer_card_value == 1: self.dealer_top_card_value_str = "A" elif dealer_card_value == 10: self.dealer_top_card_value_str = self.np_random.choice(["J", "Q", "K"]) else: self.dealer_top_card_value_str = str(dealer_card_value) if self.render_mode == "human": self.render() return self._get_obs(), {} def render(self): if self.render_mode is None: gym.logger.warn( "You are calling render method without specifying any render mode. " "You can specify the render_mode at initialization, " f'e.g. gym("{self.spec.id}", render_mode="rgb_array")' ) return try: import pygame except ImportError: raise DependencyNotInstalled( "pygame is not installed, run `pip install gym[toy_text]`" ) player_sum, dealer_card_value, usable_ace = self._get_obs() screen_width, screen_height = 600, 500 card_img_height = screen_height // 3 card_img_width = int(card_img_height * 142 / 197) spacing = screen_height // 20 bg_color = (7, 99, 36) white = (255, 255, 255) if not hasattr(self, "screen"): pygame.init() if self.render_mode == "human": pygame.display.init() self.screen = pygame.display.set_mode((screen_width, screen_height)) else: pygame.font.init() self.screen = pygame.Surface((screen_width, screen_height)) if not hasattr(self, "clock"): self.clock = pygame.time.Clock() self.screen.fill(bg_color) def get_image(path): cwd = os.path.dirname(__file__) image = pygame.image.load(os.path.join(cwd, path)) return image def get_font(path, size): cwd = os.path.dirname(__file__) font = pygame.font.Font(os.path.join(cwd, path), size) return font small_font = get_font( os.path.join("font", "Minecraft.ttf"), screen_height // 15 ) dealer_text = small_font.render( "Dealer: " + str(dealer_card_value), True, white ) dealer_text_rect = self.screen.blit(dealer_text, (spacing, spacing)) def scale_card_img(card_img): return pygame.transform.scale(card_img, (card_img_width, card_img_height)) dealer_card_img = scale_card_img( get_image( os.path.join( "img", f"{self.dealer_top_card_suit}{self.dealer_top_card_value_str}.png", ) ) ) dealer_card_rect = self.screen.blit( dealer_card_img, ( screen_width // 2 - card_img_width - spacing // 2, dealer_text_rect.bottom + spacing, ), ) hidden_card_img = scale_card_img(get_image(os.path.join("img", "Card.png"))) self.screen.blit( hidden_card_img, ( screen_width // 2 + spacing // 2, dealer_text_rect.bottom + spacing, ), ) player_text = small_font.render("Player", True, white) player_text_rect = self.screen.blit( player_text, (spacing, dealer_card_rect.bottom + 1.5 * spacing) ) large_font = get_font(os.path.join("font", "Minecraft.ttf"), screen_height // 6) player_sum_text = large_font.render(str(player_sum), True, white) player_sum_text_rect = self.screen.blit( player_sum_text, ( screen_width // 2 - player_sum_text.get_width() // 2, player_text_rect.bottom + spacing, ), ) if usable_ace: usable_ace_text = small_font.render("usable ace", True, white) self.screen.blit( usable_ace_text, ( screen_width // 2 - usable_ace_text.get_width() // 2, player_sum_text_rect.bottom + spacing // 2, ), ) if self.render_mode == "human": pygame.event.pump() pygame.display.update() self.clock.tick(self.metadata["render_fps"]) else: return np.transpose( np.array(pygame.surfarray.pixels3d(self.screen)), axes=(1, 0, 2) ) def close(self): if hasattr(self, "screen"): import pygame pygame.display.quit() pygame.quit() # Pixel art from Mariia Khmelnytska (https://www.123rf.com/photo_104453049_stock-vector-pixel-art-playing-cards-standart-deck-vector-set.html)
BlackjackEnv
python
spyder-ide__spyder
spyder/plugins/ipythonconsole/widgets/tests/test_remotekernels.py
{ "start": 835, "end": 3578 }
class ____: def test_start_stop_kernel( self, ipyconsole, remote_client, remote_client_id, qtbot ): """Starts and stops a kernel on the remote server.""" ipyconsole.get_widget().create_ipyclient_for_server(remote_client_id) shell = ipyconsole.get_current_shellwidget() qtbot.waitUntil( lambda: shell.spyder_kernel_ready and shell._prompt_html is not None, timeout=180000, # longer timeout for installation ) ipyconsole.get_widget().close_client() assert await_future( list_kernels(remote_client, remote_client_id), timeout=5 ) == [] def test_restart_kernel(self, remote_shell, ipyconsole, qtbot): """Test that kernel is restarted correctly.""" # Do an assignment to verify that it's not there after restarting with qtbot.waitSignal(remote_shell.executed): remote_shell.execute("a = 10") remote_shell._prompt_html = None ipyconsole.get_widget().restart_action.trigger() qtbot.waitUntil( lambda: remote_shell.spyder_kernel_ready and remote_shell._prompt_html is not None, timeout=4000, ) assert not remote_shell.is_defined("a") with qtbot.waitSignal(remote_shell.executed): remote_shell.execute("b = 10") # Make sure that kernel is responsive after restart qtbot.waitUntil(lambda: remote_shell.is_defined("b"), timeout=2000) def test_interrupt_kernel(self, remote_shell, qtbot): """Test that the kernel correctly interrupts.""" loop_string = "while True: pass" with qtbot.waitSignal(remote_shell.executed): remote_shell.execute("b = 10") remote_shell.execute(loop_string) qtbot.wait(500) remote_shell.interrupt_kernel() qtbot.wait(1000) # Make sure that kernel didn't die assert remote_shell.get_value("b") == 10 def test_kernel_kill(self, remote_shell, qtbot): """Test that the kernel correctly restarts after a kill.""" crash_string = ( "import os, signal; os.kill(os.getpid(), signal.SIGTERM)" ) with qtbot.waitSignal(remote_shell.sig_prompt_ready, timeout=30000): remote_shell.execute(crash_string) assert "The kernel died, restarting..." in remote_shell._control.toPlainText() with qtbot.waitSignal(remote_shell.executed): remote_shell.execute("b = 10") # Make sure that kernel is responsive after restart qtbot.waitUntil(lambda: remote_shell.is_defined("b"), timeout=2000) if __name__ == "__main__": pytest.main()
TestIpythonConsole
python
spack__spack
var/spack/test_repos/spack_repo/diff/packages/p3/package.py
{ "start": 217, "end": 291 }
class ____(Package): version("1.0") variant("p3var", default=True)
P3
python
allegroai__clearml
clearml/binding/frameworks/fastai_bind.py
{ "start": 463, "end": 1102 }
class ____(object): @staticmethod def update_current_task(task: Any, **_: Any) -> None: if fastai is None: return # noinspection PyBroadException try: if Version(fastai.__version__) < Version("2.0.0"): PatchFastaiV1.update_current_task(task) PostImportHookPatching.add_on_import("fastai", PatchFastaiV1.patch_model_callback) else: PatchFastaiV2.update_current_task(task) PostImportHookPatching.add_on_import("fastai", PatchFastaiV2.patch_model_callback) except Exception: pass
PatchFastai
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 280303, "end": 280797 }
class ____(sgqlc.types.Input): """Autogenerated input type of ReopenDiscussion""" __schema__ = github_schema __field_names__ = ("discussion_id", "client_mutation_id") discussion_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="discussionId") """ID of the discussion to be reopened.""" client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
ReopenDiscussionInput
python
langchain-ai__langchain
libs/langchain/langchain_classic/chains/combine_documents/map_rerank.py
{ "start": 1029, "end": 9396 }
class ____(BaseCombineDocumentsChain): r"""Combining documents by mapping a chain over them, then reranking results. This algorithm calls an LLMChain on each input document. The LLMChain is expected to have an OutputParser that parses the result into both an answer (`answer_key`) and a score (`rank_key`). The answer with the highest score is then returned. Example: ```python from langchain_classic.chains import MapRerankDocumentsChain, LLMChain from langchain_core.prompts import PromptTemplate from langchain_openai import OpenAI from langchain_classic.output_parsers.regex import RegexParser document_variable_name = "context" model = OpenAI() # The prompt here should take as an input variable the # `document_variable_name` # The actual prompt will need to be a lot more complex, this is just # an example. prompt_template = ( "Use the following context to tell me the chemical formula " "for water. Output both your answer and a score of how confident " "you are. Context: {context}" ) output_parser = RegexParser( regex=r"(.*?)\nScore: (.*)", output_keys=["answer", "score"], ) prompt = PromptTemplate( template=prompt_template, input_variables=["context"], output_parser=output_parser, ) llm_chain = LLMChain(llm=model, prompt=prompt) chain = MapRerankDocumentsChain( llm_chain=llm_chain, document_variable_name=document_variable_name, rank_key="score", answer_key="answer", ) ``` """ llm_chain: LLMChain """Chain to apply to each document individually.""" document_variable_name: str """The variable name in the llm_chain to put the documents in. If only one variable in the llm_chain, this need not be provided.""" rank_key: str """Key in output of llm_chain to rank on.""" answer_key: str """Key in output of llm_chain to return as answer.""" metadata_keys: list[str] | None = None """Additional metadata from the chosen document to return.""" return_intermediate_steps: bool = False """Return intermediate steps. Intermediate steps include the results of calling llm_chain on each document.""" model_config = ConfigDict( arbitrary_types_allowed=True, extra="forbid", ) @override def get_output_schema( self, config: RunnableConfig | None = None, ) -> type[BaseModel]: schema: dict[str, Any] = { self.output_key: (str, None), } if self.return_intermediate_steps: schema["intermediate_steps"] = (list[str], None) if self.metadata_keys: schema.update(dict.fromkeys(self.metadata_keys, (Any, None))) return create_model("MapRerankOutput", **schema) @property def output_keys(self) -> list[str]: """Expect input key.""" _output_keys = super().output_keys if self.return_intermediate_steps: _output_keys = [*_output_keys, "intermediate_steps"] if self.metadata_keys is not None: _output_keys += self.metadata_keys return _output_keys @model_validator(mode="after") def validate_llm_output(self) -> Self: """Validate that the combine chain outputs a dictionary.""" output_parser = self.llm_chain.prompt.output_parser if not isinstance(output_parser, RegexParser): msg = ( "Output parser of llm_chain should be a RegexParser," f" got {output_parser}" ) raise ValueError(msg) # noqa: TRY004 output_keys = output_parser.output_keys if self.rank_key not in output_keys: msg = ( f"Got {self.rank_key} as key to rank on, but did not find " f"it in the llm_chain output keys ({output_keys})" ) raise ValueError(msg) if self.answer_key not in output_keys: msg = ( f"Got {self.answer_key} as key to return, but did not find " f"it in the llm_chain output keys ({output_keys})" ) raise ValueError(msg) return self @model_validator(mode="before") @classmethod def get_default_document_variable_name(cls, values: dict) -> Any: """Get default document variable name, if not provided.""" if "llm_chain" not in values: msg = "llm_chain must be provided" raise ValueError(msg) llm_chain_variables = values["llm_chain"].prompt.input_variables if "document_variable_name" not in values: if len(llm_chain_variables) == 1: values["document_variable_name"] = llm_chain_variables[0] else: msg = ( "document_variable_name must be provided if there are " "multiple llm_chain input_variables" ) raise ValueError(msg) elif values["document_variable_name"] not in llm_chain_variables: msg = ( f"document_variable_name {values['document_variable_name']} was " f"not found in llm_chain input_variables: {llm_chain_variables}" ) raise ValueError(msg) return values def combine_docs( self, docs: list[Document], callbacks: Callbacks = None, **kwargs: Any, ) -> tuple[str, dict]: """Combine documents in a map rerank manner. Combine by mapping first chain over all documents, then reranking the results. Args: docs: List of documents to combine callbacks: Callbacks to be passed through **kwargs: additional parameters to be passed to LLM calls (like other input variables besides the documents) Returns: The first element returned is the single string output. The second element returned is a dictionary of other keys to return. """ results = self.llm_chain.apply_and_parse( # FYI - this is parallelized and so it is fast. [{self.document_variable_name: d.page_content, **kwargs} for d in docs], callbacks=callbacks, ) return self._process_results(docs, results) async def acombine_docs( self, docs: list[Document], callbacks: Callbacks = None, **kwargs: Any, ) -> tuple[str, dict]: """Combine documents in a map rerank manner. Combine by mapping first chain over all documents, then reranking the results. Args: docs: List of documents to combine callbacks: Callbacks to be passed through **kwargs: additional parameters to be passed to LLM calls (like other input variables besides the documents) Returns: The first element returned is the single string output. The second element returned is a dictionary of other keys to return. """ results = await self.llm_chain.aapply_and_parse( # FYI - this is parallelized and so it is fast. [{self.document_variable_name: d.page_content, **kwargs} for d in docs], callbacks=callbacks, ) return self._process_results(docs, results) def _process_results( self, docs: list[Document], results: Sequence[str | list[str] | dict[str, str]], ) -> tuple[str, dict]: typed_results = cast("list[dict]", results) sorted_res = sorted( zip(typed_results, docs, strict=False), key=lambda x: -int(x[0][self.rank_key]), ) output, document = sorted_res[0] extra_info = {} if self.metadata_keys is not None: for key in self.metadata_keys: extra_info[key] = document.metadata[key] if self.return_intermediate_steps: extra_info["intermediate_steps"] = results return output[self.answer_key], extra_info @property def _chain_type(self) -> str: return "map_rerank_documents_chain"
MapRerankDocumentsChain
python
scrapy__scrapy
tests/test_downloader_handlers_http_base.py
{ "start": 26831, "end": 27066 }
class ____(TestSimpleHttpsBase): """Connect to HTTPS hosts where the certificate are issued to an ip instead of a domain.""" keyfile = "keys/localhost.ip.key" certfile = "keys/localhost.ip.crt"
TestHttpsInvalidDNSPatternBase
python
kamyu104__LeetCode-Solutions
Python/maximum-cost-of-trip-with-k-highways.py
{ "start": 1568, "end": 2427 }
class ____(object): def maximumCost(self, n, highways, k): """ :type n: int :type highways: List[List[int]] :type k: int :rtype: int """ if k+1 > n: # required to optimize, otherwise, TLE or MLE return -1 adj = [[] for _ in xrange(n)] for c1, c2, t in highways: adj[c1].append((c2, t)) adj[c2].append((c1, t)) result = -1 dp = [(u, 1<<u, 0) for u in xrange(n)] while dp: new_dp = [] for u, mask, total in dp: if bin(mask).count('1') == k+1: result = max(result, total) for v, t in adj[u]: if mask&(1<<v) == 0: new_dp.append((v, mask|(1<<v), total+t)) dp = new_dp return result
Solution2
python
huggingface__transformers
src/transformers/models/wavlm/modeling_wavlm.py
{ "start": 33095, "end": 39499 }
class ____(nn.Module): def __init__(self, config): super().__init__() # feature dim might need to be down-projected if config.output_hidden_size != config.hidden_size: self.proj = nn.Linear(config.hidden_size, config.output_hidden_size) self.proj_layer_norm = nn.LayerNorm(config.output_hidden_size) else: self.proj = self.proj_layer_norm = None self.layers = nn.ModuleList(WavLMAdapterLayer(config) for _ in range(config.num_adapter_layers)) self.layerdrop = config.layerdrop def forward(self, hidden_states): # down project hidden_states if necessary if self.proj is not None and self.proj_layer_norm is not None: hidden_states = self.proj(hidden_states) hidden_states = self.proj_layer_norm(hidden_states) hidden_states = hidden_states.transpose(1, 2) for layer in self.layers: layerdrop_prob = np.random.random() if not self.training or (layerdrop_prob > self.layerdrop): hidden_states = layer(hidden_states) hidden_states = hidden_states.transpose(1, 2) return hidden_states def _compute_mask_indices( shape: tuple[int, int], mask_prob: float, mask_length: int, attention_mask: Optional[torch.LongTensor] = None, min_masks: int = 0, ) -> np.ndarray: """ Computes random mask spans for a given shape. Used to implement [SpecAugment: A Simple Data Augmentation Method for ASR](https://huggingface.co/papers/1904.08779). Note that this method is not optimized to run on TPU and should be run on CPU as part of the preprocessing during training. Args: shape: The shape for which to compute masks. This should be of a tuple of size 2 where the first element is the batch size and the second element is the length of the axis to span. mask_prob: The percentage of the whole axis (between 0 and 1) which will be masked. The number of independently generated mask spans of length `mask_length` is computed by `mask_prob*shape[1]/mask_length`. Note that due to overlaps, `mask_prob` is an upper bound and the actual percentage will be smaller. mask_length: size of the mask min_masks: minimum number of masked spans attention_mask: A (right-padded) attention mask which independently shortens the feature axis of each batch dimension. """ batch_size, sequence_length = shape if mask_length < 1: raise ValueError("`mask_length` has to be bigger than 0.") if mask_length > sequence_length: raise ValueError( f"`mask_length` has to be smaller than `sequence_length`, but got `mask_length`: {mask_length}" f" and `sequence_length`: {sequence_length}`" ) # epsilon is used for probabilistic rounding epsilon = np.random.rand(1).item() def compute_num_masked_span(input_length): """Given input length, compute how many spans should be masked""" num_masked_span = int(mask_prob * input_length / mask_length + epsilon) num_masked_span = max(num_masked_span, min_masks) # make sure num masked span <= sequence_length if num_masked_span * mask_length > sequence_length: num_masked_span = sequence_length // mask_length # make sure num_masked span is also <= input_length - (mask_length - 1) if input_length - (mask_length - 1) < num_masked_span: num_masked_span = max(input_length - (mask_length - 1), 0) return num_masked_span # compute number of masked spans in batch input_lengths = ( attention_mask.detach().sum(-1).tolist() if attention_mask is not None else [sequence_length for _ in range(batch_size)] ) # SpecAugment mask to fill spec_aug_mask = np.zeros((batch_size, sequence_length), dtype=bool) spec_aug_mask_idxs = [] max_num_masked_span = compute_num_masked_span(sequence_length) if max_num_masked_span == 0: return spec_aug_mask for input_length in input_lengths: # compute num of masked spans for this input num_masked_span = compute_num_masked_span(input_length) # get random indices to mask spec_aug_mask_idx = np.random.choice( np.arange(input_length - (mask_length - 1)), num_masked_span, replace=False ) # pick first sampled index that will serve as a dummy index to pad vector # to ensure same dimension for all batches due to probabilistic rounding # Picking first sample just pads those vectors twice. if len(spec_aug_mask_idx) == 0: # this case can only happen if `input_length` is strictly smaller then # `sequence_length` in which case the last token has to be a padding # token which we can use as a dummy mask id dummy_mask_idx = sequence_length - 1 else: dummy_mask_idx = spec_aug_mask_idx[0] spec_aug_mask_idx = np.concatenate( [spec_aug_mask_idx, np.ones(max_num_masked_span - num_masked_span, dtype=np.int32) * dummy_mask_idx] ) spec_aug_mask_idxs.append(spec_aug_mask_idx) spec_aug_mask_idxs = np.array(spec_aug_mask_idxs) # expand masked indices to masked spans spec_aug_mask_idxs = np.broadcast_to( spec_aug_mask_idxs[:, :, None], (batch_size, max_num_masked_span, mask_length) ) spec_aug_mask_idxs = spec_aug_mask_idxs.reshape(batch_size, max_num_masked_span * mask_length) # add offset to the starting indexes so that indexes now create a span offsets = np.arange(mask_length)[None, None, :] offsets = np.broadcast_to(offsets, (batch_size, max_num_masked_span, mask_length)).reshape( batch_size, max_num_masked_span * mask_length ) spec_aug_mask_idxs = spec_aug_mask_idxs + offsets # ensure that we cannot have indices larger than sequence_length if spec_aug_mask_idxs.max() > sequence_length - 1: spec_aug_mask_idxs[spec_aug_mask_idxs > sequence_length - 1] = sequence_length - 1 # scatter indices to mask np.put_along_axis(spec_aug_mask, spec_aug_mask_idxs, 1, -1) return spec_aug_mask WavLMBaseModelOutput = Wav2Vec2BaseModelOutput @auto_docstring
WavLMAdapter
python
dask__dask
dask/dataframe/dask_expr/datasets.py
{ "start": 3572, "end": 6847 }
class ____: def __init__(self, dtypes, columns, freq, kwargs): self.dtypes = dtypes self.columns = columns self.freq = freq self.kwargs = kwargs def __call__(self, start, end, state_data): dtypes = self.dtypes columns = self.columns freq = self.freq kwargs = self.kwargs state = np.random.RandomState(state_data) index = pd.date_range(start=start, end=end, freq=freq, name="timestamp") data = {} for k, dt in dtypes.items(): kws = { kk.rsplit("_", 1)[1]: v for kk, v in kwargs.items() if kk.rsplit("_", 1)[0] == k } # Note: we compute data for all dtypes in order, not just those in the output # columns. This ensures the same output given the same state_data, regardless # of whether there is any column projection. # cf. https://github.com/dask/dask/pull/9538#issuecomment-1267461887 result = make[dt](len(index), state, **kws) if k in columns: data[k] = result df = pd.DataFrame(data, index=index, columns=columns) if df.index[-1] == end: df = df.iloc[:-1] return df def timeseries( start="2000-01-01", end="2000-01-31", freq="1s", partition_freq="1D", dtypes=None, seed=None, **kwargs, ): """Create timeseries dataframe with random data Parameters ---------- start: datetime (or datetime-like string) Start of time series end: datetime (or datetime-like string) End of time series dtypes: dict (optional) Mapping of column names to types. Valid types include {float, int, str, 'category'} freq: string String like '2s' or '1H' or '12W' for the time series frequency partition_freq: string String like '1M' or '2Y' to divide the dataframe into partitions seed: int (optional) Randomstate seed kwargs: Keywords to pass down to individual column creation functions. Keywords should be prefixed by the column name and then an underscore. Examples -------- >>> from dask.dataframe.dask_expr.datasets import timeseries >>> df = timeseries( ... start='2000', end='2010', ... dtypes={'value': float, 'name': str, 'id': int}, ... freq='2h', partition_freq='1D', seed=1 ... ) >>> df.head() # doctest: +SKIP id name value 2000-01-01 00:00:00 969 Jerry -0.309014 2000-01-01 02:00:00 1010 Ray -0.760675 2000-01-01 04:00:00 1016 Patricia -0.063261 2000-01-01 06:00:00 960 Charlie 0.788245 2000-01-01 08:00:00 1031 Kevin 0.466002 """ if dtypes is None: dtypes = {"name": "string", "id": int, "x": float, "y": float} if seed is None: seed = np.random.randint(2e9) expr = Timeseries( start, end, dtypes, freq, partition_freq, seed, kwargs, columns=list(dtypes.keys()), ) if pyarrow_strings_enabled(): return new_collection(ArrowStringConversion(expr)) return new_collection(expr)
MakeTimeseriesPart
python
openai__openai-python
src/openai/types/beta/assistant_update_params.py
{ "start": 6612, "end": 6937 }
class ____(TypedDict, total=False): vector_store_ids: SequenceNotStr[str] """ Overrides the [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. """
ToolResourcesFileSearch
python
gevent__gevent
src/gevent/tests/test__example_echoserver.py
{ "start": 170, "end": 1198 }
class ____(util.TestServer): example = 'echoserver.py' def _run_all_tests(self): def test_client(message): if greentest.PY3: kwargs = {'buffering': 1} else: kwargs = {'bufsize': 1} kwargs['mode'] = 'rb' conn = create_connection((params.DEFAULT_LOCAL_HOST_ADDR, 16000)) conn.settimeout(greentest.DEFAULT_XPC_SOCKET_TIMEOUT) rfile = conn.makefile(**kwargs) welcome = rfile.readline() self.assertIn(b'Welcome', welcome) conn.sendall(message) received = rfile.read(len(message)) self.assertEqual(received, message) self.assertRaises(timeout, conn.recv, 1) rfile.close() conn.close() client1 = gevent.spawn(test_client, b'hello\r\n') client2 = gevent.spawn(test_client, b'world\r\n') gevent.joinall([client1, client2], raise_error=True) if __name__ == '__main__': greentest.main()
Test
python
astropy__astropy
astropy/modeling/functional_models.py
{ "start": 41663, "end": 44089 }
class ____(_InverseTrigonometric1D): """ One dimensional ArcTangent model returning values between -pi/2 and pi/2 only. Parameters ---------- amplitude : float Oscillation amplitude for corresponding Tangent frequency : float Oscillation frequency for corresponding Tangent phase : float Oscillation phase for corresponding Tangent See Also -------- Tangent1D, ArcSine1D, ArcCosine1D Notes ----- Model formula: .. math:: f(x) = ((arctan(x / A) / 2pi) - p) / f Examples -------- .. plot:: :include-source: import numpy as np import matplotlib.pyplot as plt from astropy.modeling.models import ArcTangent1D plt.figure() s1 = ArcTangent1D(amplitude=1, frequency=.25) r=np.arange(-10, 10, .01) for amplitude in range(1,4): s1.amplitude = amplitude plt.plot(r, s1(r), color=str(0.25 * amplitude), lw=2) plt.axis([-10, 10, -np.pi/2, np.pi/2]) plt.show() """ @staticmethod def evaluate(x, amplitude, frequency, phase): """One dimensional ArcTangent model function.""" # Note: If frequency and x are quantities, they should normally have # inverse units, so that argument ends up being dimensionless. However, # np.sin of a dimensionless quantity will crash, so we remove the # quantity-ness from argument in this case (another option would be to # multiply by * u.rad but this would be slower overall). argument = x / amplitude if isinstance(argument, Quantity): argument = argument.value arc_cos = np.arctan(argument) / TWOPI return (arc_cos - phase) / frequency @staticmethod def fit_deriv(x, amplitude, frequency, phase): """One dimensional ArcTangent model derivative.""" d_amplitude = -x / ( TWOPI * frequency * amplitude**2 * (1 + (x / amplitude) ** 2) ) d_frequency = (phase - (np.arctan(x / amplitude) / TWOPI)) / frequency**2 d_phase = -1 / frequency * np.ones(x.shape) return [d_amplitude, d_frequency, d_phase] @property def inverse(self): """One dimensional inverse of ArcTangent.""" return Tangent1D( amplitude=self.amplitude, frequency=self.frequency, phase=self.phase )
ArcTangent1D
python
walkccc__LeetCode
solutions/429. N-ary Tree Level Order Traversal/429.py
{ "start": 0, "end": 387 }
class ____: def levelOrder(self, root: 'Node') -> list[list[int]]: if not root: return [] ans = [] q = collections.deque([root]) while q: currLevel = [] for _ in range(len(q)): node = q.popleft() currLevel.append(node.val) for child in node.children: q.append(child) ans.append(currLevel) return ans
Solution
python
scrapy__scrapy
tests/test_command_startproject.py
{ "start": 3911, "end": 10287 }
class ____: def test_startproject_template_override(self, tmp_path: Path) -> None: tmpl = tmp_path / "templates" tmpl_proj = tmpl / "project" project_name = "testproject" copytree(Path(scrapy.__path__[0], "templates"), tmpl) (tmpl_proj / "root_template").write_bytes(b"") args = ["--set", f"TEMPLATES_DIR={tmpl}"] _, out, _ = proc("startproject", project_name, *args, cwd=tmp_path) assert f"New Scrapy project '{project_name}', using template directory" in out assert str(tmpl_proj) in out assert (tmp_path / project_name / "root_template").exists() def test_startproject_permissions_from_writable(self, tmp_path: Path) -> None: """Check that generated files have the right permissions when the template folder has the same permissions as in the project, i.e. everything is writable.""" scrapy_path = scrapy.__path__[0] project_template = Path(scrapy_path, "templates", "project") project_name = "startproject1" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) destination = tmp_path / "proj" destination.mkdir() process = subprocess.Popen( ( sys.executable, "-m", "scrapy.cmdline", "startproject", project_name, ), cwd=destination, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=get_testenv(), ) process.wait() project_dir = destination / project_name actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions def test_startproject_permissions_from_read_only(self, tmp_path: Path) -> None: """Check that generated files have the right permissions when the template folder has been made read-only, which is something that some systems do. See https://github.com/scrapy/scrapy/pull/4604 """ scrapy_path = scrapy.__path__[0] templates_dir = Path(scrapy_path, "templates") project_template = Path(templates_dir, "project") project_name = "startproject2" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) def _make_read_only(path: Path): current_permissions = path.stat().st_mode path.chmod(current_permissions & ~ANYONE_WRITE_PERMISSION) read_only_templates_dir = tmp_path / "templates" copytree(templates_dir, read_only_templates_dir) for root, dirs, files in os.walk(read_only_templates_dir): for node in chain(dirs, files): _make_read_only(Path(root, node)) destination = tmp_path / "proj" destination.mkdir() assert ( call( "startproject", project_name, "--set", f"TEMPLATES_DIR={read_only_templates_dir}", cwd=destination, ) == 0 ) project_dir = destination / project_name actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions def test_startproject_permissions_unchanged_in_destination( self, tmp_path: Path ) -> None: """Check that preexisting folders and files in the destination folder do not see their permissions modified.""" scrapy_path = scrapy.__path__[0] project_template = Path(scrapy_path, "templates", "project") project_name = "startproject3" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) destination = tmp_path / "proj" project_dir = destination / project_name project_dir.mkdir(parents=True) existing_nodes = { f"{permissions:o}{extension}": permissions for extension in ("", ".d") for permissions in ( 0o444, 0o555, 0o644, 0o666, 0o755, 0o777, ) } for node, permissions in existing_nodes.items(): path = project_dir / node if node.endswith(".d"): path.mkdir(mode=permissions) else: path.touch(mode=permissions) expected_permissions[node] = oct(path.stat().st_mode) assert call("startproject", project_name, ".", cwd=project_dir) == 0 actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions def test_startproject_permissions_umask_022(self, tmp_path: Path) -> None: """Check that generated files have the right permissions when the system uses a umask value that causes new files to have different permissions than those from the template folder.""" @contextmanager def umask(new_mask): cur_mask = os.umask(new_mask) yield os.umask(cur_mask) scrapy_path = scrapy.__path__[0] project_template = Path(scrapy_path, "templates", "project") project_name = "umaskproject" renamings = ( ("module", project_name), (".tmpl", ""), ) expected_permissions = get_permissions_dict( project_template, renamings, IGNORE, ) with umask(0o002): destination = tmp_path / "proj" destination.mkdir() assert call("startproject", project_name, cwd=destination) == 0 project_dir = destination / project_name actual_permissions = get_permissions_dict(project_dir) assert actual_permissions == expected_permissions
TestStartprojectTemplates
python
h5py__h5py
h5py/tests/test_vds/test_highlevel_vds.py
{ "start": 15887, "end": 17852 }
class ____(ut.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() self.path = osp.join(self.tmpdir, "resize.h5") with h5.File(self.path, "w") as f: source_dset = f.create_dataset( "source", data=np.arange(20), shape=(10, 2), maxshape=(None, 2), chunks=(10, 1), fillvalue=-1 ) self.layout = h5.VirtualLayout((10, 1), int, maxshape=(None, 1)) layout_source = h5.VirtualSource(source_dset) self.layout[:h5.UNLIMITED, 0] = layout_source[:h5.UNLIMITED, 1] f.create_virtual_dataset("virtual", self.layout) def test_unlimited_axis(self): comp1 = np.arange(1, 20, 2).reshape(10, 1) comp2 = np.vstack(( comp1, np.full(shape=(10, 1), fill_value=-1) )) comp3 = np.vstack(( comp1, np.full(shape=(10, 1), fill_value=0) )) fname = osp.join(self.tmpdir, make_name("resize2{}.h5")) shutil.copyfile(self.path, fname) with h5.File(fname, "a") as f: source_dset = f['source'] virtual_dset = f['virtual'] np.testing.assert_array_equal(comp1, virtual_dset) source_dset.resize(20, axis=0) np.testing.assert_array_equal(comp2, virtual_dset) source_dset[10:, 1] = np.zeros((10,), dtype=int) np.testing.assert_array_equal(comp3, virtual_dset) def tearDown(self): shutil.rmtree(self.tmpdir) def test_no_mappings(writable_file): name = make_name() with writable_file.build_virtual_dataset(name, (10, 20), np.int32): pass dset = writable_file[name] assert dset.is_virtual assert dset.virtual_sources() == [] np.testing.assert_array_equal(dset[()], np.zeros((10, 20), np.int32)) if __name__ == "__main__": ut.main()
VDSUnlimitedTestCase
python
pandas-dev__pandas
asv_bench/benchmarks/sparse.py
{ "start": 3836, "end": 4975 }
class ____: params = [np.nan, 0] param_names = ["fill_value"] def setup(self, fill_value): N = 10**6 self.arr1 = self.make_block_array( length=N, num_blocks=1000, block_size=10, fill_value=fill_value ) self.arr2 = self.make_block_array( length=N, num_blocks=1000, block_size=10, fill_value=fill_value ) def make_block_array(self, length, num_blocks, block_size, fill_value): arr = np.full(length, fill_value) indices = np.random.choice( np.arange(0, length, block_size), num_blocks, replace=False ) for ind in indices: arr[ind : ind + block_size] = np.random.randint(0, 100, block_size) return SparseArray(arr, fill_value=fill_value) def time_make_union(self, fill_value): self.arr1.sp_index.make_union(self.arr2.sp_index) def time_intersect(self, fill_value): self.arr2.sp_index.intersect(self.arr2.sp_index) def time_addition(self, fill_value): self.arr1 + self.arr2 def time_division(self, fill_value): self.arr1 / self.arr2
ArithmeticBlock
python
ray-project__ray
python/ray/data/_internal/datasource/parquet_datasource.py
{ "start": 5724, "end": 10303 }
class ____: """Result of splitting a predicate by column type. Attributes: data_predicate: Expression containing only data column predicates (for PyArrow pushdown), or None if no data predicates exist. partition_predicate: Expression containing only partition column predicates (for partition pruning), or None if no partition predicates exist. """ data_predicate: Optional[Expr] partition_predicate: Optional[Expr] def _split_predicate_by_columns( predicate: Expr, partition_columns: set, ) -> _SplitPredicateResult: """Split a predicate into data-only and partition-only parts. This function extracts both data column predicates and partition column predicates from AND chains, enabling both PyArrow pushdown (data part) and partition pruning (partition part). Args: predicate: The predicate expression to analyze. partition_columns: Set of partition column names. Returns: _SplitPredicateResult containing: - data_predicate: Expression with only data columns (for PyArrow pushdown), or None if no data predicates can be extracted. - partition_predicate: Expression with only partition columns (for pruning), or None if no partition predicates can be extracted. Examples: >>> from ray.data.expressions import col >>> # Pure data predicate: >>> result = _split_predicate_by_columns(col("data1") > 5, {"partition_col"}) >>> result.data_predicate is not None # Should have data predicate True >>> result.partition_predicate is None # Should not have partition predicate True >>> # Pure partition predicate: >>> result = _split_predicate_by_columns(col("partition_col") == "US", {"partition_col"}) >>> result.data_predicate is None # Should not have data predicate True >>> result.partition_predicate is not None # Should have partition predicate True >>> # Mixed AND - can split both parts: >>> result = _split_predicate_by_columns( ... (col("data1") > 5) & (col("partition_col") == "US"), ... {"partition_col"} ... ) >>> result.data_predicate is not None # Should have data predicate True >>> result.partition_predicate is not None # Should have partition predicate True >>> # Mixed OR - can't split safely: >>> result = _split_predicate_by_columns( ... (col("data1") > 5) | (col("partition_col") == "US"), ... {"partition_col"} ... ) >>> result.data_predicate is None # Should not have data predicate True >>> result.partition_predicate is None # Should not have partition predicate True """ referenced_cols = set(get_column_references(predicate)) data_cols = referenced_cols - partition_columns partition_cols_in_predicate = referenced_cols & partition_columns if not partition_cols_in_predicate: # Pure data predicate return _SplitPredicateResult(data_predicate=predicate, partition_predicate=None) if not data_cols: # Pure partition predicate return _SplitPredicateResult(data_predicate=None, partition_predicate=predicate) # Mixed predicate - try to split if it's an AND chain if isinstance(predicate, BinaryExpr) and predicate.op == Operation.AND: # Recursively split left and right sides left_result = _split_predicate_by_columns(predicate.left, partition_columns) right_result = _split_predicate_by_columns(predicate.right, partition_columns) # Helper to combine predicates from both sides def combine_predicates( left: Optional[Expr], right: Optional[Expr] ) -> Optional[Expr]: if left and right: return left & right return left or right data_predicate = combine_predicates( left_result.data_predicate, right_result.data_predicate ) partition_predicate = combine_predicates( left_result.partition_predicate, right_result.partition_predicate ) return _SplitPredicateResult( data_predicate=data_predicate, partition_predicate=partition_predicate ) # For OR, NOT, or other operations with mixed columns, # we can't safely split - must evaluate the full predicate together return _SplitPredicateResult(data_predicate=None, partition_predicate=None)
_SplitPredicateResult
python
encode__django-rest-framework
tests/schemas/views.py
{ "start": 750, "end": 901 }
class ____(APIView): permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get(self, *args, **kwargs): pass
ExampleDetailView
python
realpython__materials
python-serialize/http-payload/django-rest-api/rest_api/models.py
{ "start": 78, "end": 272 }
class ____(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length=200) created_at = models.DateTimeField(default=timezone.now)
User
python
pytorch__pytorch
torch/_inductor/template_heuristics/decompose_k.py
{ "start": 1265, "end": 2382 }
class ____(GemmMaxAutotuneTemplateConfigHeuristics): def _get_template_configs_impl( self, kernel_inputs: KernelInputs, op_name: str, ) -> Generator[dict[str, Any], None, None]: """ Get all the valid k_splits for the given m, n, k. """ assert isinstance(kernel_inputs, MMKernelInputs), ( f"{self.__class__.__name__} requires MMKernelInputs" ) # Check for unbacked symbols - if found, yield nothing unbacked_symbols = any( len(get_free_symbols(itr, unbacked_only=True)) > 0 for itr in ( *kernel_inputs.shapes_symbolic(), *kernel_inputs.strides_symbolic(), ) ) if unbacked_symbols: return m, n, k = kernel_inputs.mnk_symbolic() k_splits = get_k_splits(m, n, k) for k_split in k_splits: if not V.graph.sizevars.statically_known_true( sympy.Eq(sympy.Mod(k, k_split), 0) ): continue yield {"k_split": k_split}
DecomposeKConfigHeuristics
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 377148, "end": 377902 }
class ____(ValueChannelMixin, core.PositionValueDef): """ Longitude2Value schema wrapper. Definition object for a constant value (primitive value or gradient definition) of an encoding channel. Parameters ---------- value : dict, float, :class:`ExprRef`, Literal['height', 'width'] A constant value in visual domain (e.g., ``"red"`` / ``"#0099ff"`` / `gradient definition <https://vega.github.io/vega-lite/docs/types.html#gradient>`__ for color, values between ``0`` to ``1`` for opacity). """ _class_is_valid_at_instantiation = False _encoding_name = "longitude2" def __init__(self, value, **kwds): super().__init__(value=value, **kwds) @with_property_setters
Longitude2Value
python
celery__celery
celery/backends/s3.py
{ "start": 299, "end": 2752 }
class ____(KeyValueStoreBackend): """An S3 task result store. Raises: celery.exceptions.ImproperlyConfigured: if module :pypi:`boto3` is not available, if the :setting:`aws_access_key_id` or setting:`aws_secret_access_key` are not set, or it the :setting:`bucket` is not set. """ def __init__(self, **kwargs): super().__init__(**kwargs) if not boto3 or not botocore: raise ImproperlyConfigured('You must install boto3' 'to use s3 backend') conf = self.app.conf self.endpoint_url = conf.get('s3_endpoint_url', None) self.aws_region = conf.get('s3_region', None) self.aws_access_key_id = conf.get('s3_access_key_id', None) self.aws_secret_access_key = conf.get('s3_secret_access_key', None) self.bucket_name = conf.get('s3_bucket', None) if not self.bucket_name: raise ImproperlyConfigured('Missing bucket name') self.base_path = conf.get('s3_base_path', None) self._s3_resource = self._connect_to_s3() def _get_s3_object(self, key): key_bucket_path = self.base_path + key if self.base_path else key return self._s3_resource.Object(self.bucket_name, key_bucket_path) def get(self, key): key = bytes_to_str(key) s3_object = self._get_s3_object(key) try: s3_object.load() data = s3_object.get()['Body'].read() return data if self.content_encoding == 'binary' else data.decode('utf-8') except botocore.exceptions.ClientError as error: if error.response['Error']['Code'] == "404": return None raise error def set(self, key, value): key = bytes_to_str(key) s3_object = self._get_s3_object(key) s3_object.put(Body=value) def delete(self, key): key = bytes_to_str(key) s3_object = self._get_s3_object(key) s3_object.delete() def _connect_to_s3(self): session = boto3.Session( aws_access_key_id=self.aws_access_key_id, aws_secret_access_key=self.aws_secret_access_key, region_name=self.aws_region ) if session.get_credentials() is None: raise ImproperlyConfigured('Missing aws s3 creds') return session.resource('s3', endpoint_url=self.endpoint_url)
S3Backend
python
pyca__cryptography
tests/hazmat/primitives/test_ec.py
{ "start": 7177, "end": 8349 }
class ____: def test_with_numbers(self, backend, subtests): vectors = itertools.product( load_vectors_from_file( os.path.join( "asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp" ), load_fips_ecdsa_key_pair_vectors, ), _HASH_TYPES.values(), ) for vector, hash_type in vectors: with subtests.test(): curve = ec._CURVE_TYPES[vector["curve"]] _skip_ecdsa_vector(backend, curve, hash_type) key = ec.EllipticCurvePrivateNumbers( vector["d"], ec.EllipticCurvePublicNumbers( vector["x"], vector["y"], curve ), ).private_key(backend) assert key priv_num = key.private_numbers() assert priv_num.private_value == vector["d"] assert priv_num.public_numbers.x == vector["x"] assert priv_num.public_numbers.y == vector["y"] assert curve.name == priv_num.public_numbers.curve.name
TestECWithNumbers
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_memorystore.py
{ "start": 9514, "end": 13494 }
class ____(GoogleCloudBaseOperator): """ Export Redis instance data into a Redis RDB format file in Cloud Storage. Redis will continue serving during this operation. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudMemorystoreExportInstanceOperator` :param location: The location of the Cloud Memorystore instance (for example europe-west1) :param instance: The logical name of the Redis instance in the customer project. :param output_config: Required. Specify data to be exported. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.redis_v1.types.OutputConfig` :param project_id: Project ID of the project that contains the instance. If set to None or missing, the default project_id from the Google Cloud connection is used. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = ( "location", "instance", "output_config", "project_id", "retry", "timeout", "metadata", "gcp_conn_id", "impersonation_chain", ) operator_extra_links = (RedisInstanceDetailsLink(),) def __init__( self, *, location: str, instance: str, output_config: dict | OutputConfig, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.location = location self.instance = instance self.output_config = output_config self.project_id = project_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain @property def extra_links_params(self) -> dict[str, Any]: return { "instance_id": self.instance, "location_id": self.location, } def execute(self, context: Context) -> None: hook = CloudMemorystoreHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain ) hook.export_instance( location=self.location, instance=self.instance, output_config=self.output_config, project_id=self.project_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) RedisInstanceDetailsLink.persist( context=context, project_id=self.project_id or hook.project_id, )
CloudMemorystoreExportInstanceOperator
python
nedbat__coveragepy
tests/test_api.py
{ "start": 44641, "end": 45104 }
class ____(CoverageTest): """Check that reporting methods don't permanently change the configuration.""" def test_config_doesnt_change(self) -> None: self.make_file("simple.py", "a = 1") cov = coverage.Coverage() self.start_import_stop(cov, "simple") assert cov.get_option("report:show_missing") is False cov.report(show_missing=True) assert cov.get_option("report:show_missing") is False
ImmutableConfigTest
python
Textualize__textual
docs/examples/widgets/progress_bar_gradient.py
{ "start": 166, "end": 868 }
class ____(App[None]): """Progress bar with a rainbow gradient.""" def compose(self) -> ComposeResult: gradient = Gradient.from_colors( "#881177", "#aa3355", "#cc6666", "#ee9944", "#eedd00", "#99dd55", "#44dd88", "#22ccbb", "#00bbcc", "#0099cc", "#3366bb", "#663399", ) with Center(): with Middle(): yield ProgressBar(total=100, gradient=gradient) def on_mount(self) -> None: self.query_one(ProgressBar).update(progress=70) if __name__ == "__main__": ProgressApp().run()
ProgressApp
python
getsentry__sentry
src/sentry/migrations/0938_rm_eventattachment_fileid_part1.py
{ "start": 239, "end": 1527 }
class ____(CheckedMigration): # This flag is used to mark that a migration shouldn't be automatically run in production. # This should only be used for operations where it's safe to run the migration after your # code has deployed. So this should not be used for most operations that alter the schema # of a table. # Here are some things that make sense to mark as post deployment: # - Large data migrations. Typically we want these to be run manually so that they can be # monitored and not block the deploy for a long period of time while they run. # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to # run this outside deployments so that we don't block them. Note that while adding an index # is a schema change, it's completely safe to run the operation after the code has deployed. # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment is_post_deployment = False dependencies = [ ("sentry", "0937_fix_defaults"), ] operations = [ SafeRemoveField( model_name="eventattachment", name="file_id", deletion_action=DeletionAction.MOVE_TO_PENDING, ), ]
Migration
python
django__django
tests/admin_filters/tests.py
{ "start": 7638, "end": 7744 }
class ____(DecadeFilterBookAdmin): show_facets = ShowFacets.ALWAYS
DecadeFilterBookAdminWithAlwaysFacets
python
doocs__leetcode
solution/3300-3399/3339.Find the Number of K-Even Arrays/Solution.py
{ "start": 0, "end": 508 }
class ____: def countOfArrays(self, n: int, m: int, k: int) -> int: @cache def dfs(i: int, j: int, k: int) -> int: if j < 0: return 0 if i >= n: return int(j == 0) return ( cnt1 * dfs(i + 1, j, 1) + cnt0 * dfs(i + 1, j - (k & 1 ^ 1), 0) ) % mod cnt0 = m // 2 cnt1 = m - cnt0 mod = 10**9 + 7 ans = dfs(0, k, 1) dfs.cache_clear() return ans
Solution
python
conda__conda
conda/core/portability.py
{ "start": 1503, "end": 16066 }
class ____(Exception): pass def _subdir_is_win(subdir: str) -> bool: """ Determine if the given `subdir` corresponds to a Windows operating system. :param subdir: The subdirectory name which may contain an OS identifier. :return: Returns True if `subdir` indicates a Windows OS; otherwise, False. """ if "-" in subdir: os, _ = subdir.lower().split("-", 1) return os == "win" else: # For noarch, check that we are running on windows return on_win def update_prefix( path: str, new_prefix: str, placeholder: str = PREFIX_PLACEHOLDER, mode: FileMode = FileMode.text, subdir: str = context.subdir, ) -> None: """ Update the prefix in a file or directory. :param path: The path to the file or directory. :param new_prefix: The new prefix to replace the old prefix with. :param placeholder: The placeholder to use for the old prefix. Defaults to PREFIX_PLACEHOLDER. :param mode: The file mode. Defaults to FileMode.text. :param subdir: The subdirectory. Defaults to context.subdir. """ if _subdir_is_win(subdir) and mode == FileMode.text: # force all prefix replacements to forward slashes to simplify need to escape backslashes # replace with unix-style path separators new_prefix = new_prefix.replace("\\", "/") def _update_prefix(original_data): """ A function that updates the prefix in a file or directory. :param original_data: The original data to be updated. :return: The updated data after prefix replacement. """ # Step 1. do all prefix replacement data = replace_prefix(mode, original_data, placeholder, new_prefix, subdir) # Step 2. if the shebang is too long or the new prefix contains spaces, shorten it using # /usr/bin/env trick -- NOTE: this trick assumes the environment WILL BE activated if not _subdir_is_win(subdir): data = replace_long_shebang(mode, data) # Step 3. if the before and after content is the same, skip writing if data == original_data: raise CancelOperation() # Step 4. if we have a binary file, make sure the byte size is the same before # and after the update if mode == FileMode.binary and len(data) != len(original_data): raise BinaryPrefixReplacementError( path, placeholder, new_prefix, len(original_data), len(data) ) return data updated = update_file_in_place_as_binary(realpath(path), _update_prefix) if updated and mode == FileMode.binary and subdir == "osx-arm64" and on_mac: # Apple arm64 needs signed executables subprocess.run( ["/usr/bin/codesign", "-s", "-", "-f", realpath(path)], capture_output=True ) def replace_prefix( mode: FileMode, data: bytes, placeholder: str, new_prefix: str, subdir: str = "noarch", ) -> bytes: """ Replaces `placeholder` text with the `new_prefix` provided. The `mode` provided can either be text or binary. We use the `POPULAR_ENCODINGS` module level constant defined above to make several passes at replacing the placeholder. We do this to account for as many encodings as possible. If this causes any performance problems in the future, it could potentially be removed (i.e. just using the most popular "utf-8" encoding"). More information/discussion available here: https://github.com/conda/conda/pull/9946 :param mode: The mode of operation. :param original_data: The original data to be updated. :param placeholder: The placeholder to be replaced. :param new_prefix: The new prefix to be used. :param subdir: The subdirectory to be used. :return: The updated data after prefix replacement. """ for encoding in POPULAR_ENCODINGS: if mode == FileMode.text: if not _subdir_is_win(subdir): # if new_prefix contains spaces, it might break the shebang! # handle this by escaping the spaces early, which will trigger a # /usr/bin/env replacement later on newline_pos = data.find(b"\n") if newline_pos > -1: shebang_line, rest_of_data = data[:newline_pos], data[newline_pos:] shebang_placeholder = f"#!{placeholder}".encode(encoding) if shebang_placeholder in shebang_line: escaped_shebang = f"#!{new_prefix}".replace(" ", "\\ ").encode( encoding ) shebang_line = shebang_line.replace( shebang_placeholder, escaped_shebang ) data = shebang_line + rest_of_data # the rest of the file can be replaced normally data = data.replace( placeholder.encode(encoding), new_prefix.encode(encoding) ) elif mode == FileMode.binary: data = binary_replace( data, placeholder.encode(encoding), new_prefix.encode(encoding), encoding=encoding, subdir=subdir, ) else: raise CondaIOError(f"Invalid mode: {mode!r}") return data def binary_replace( data: bytes, search: bytes, replacement: bytes, encoding: str = "utf-8", subdir: str = "noarch", ) -> bytes: """ Replaces occurrences of a search string with a replacement string in a given byte string. :param data: The byte string in which to perform the replacements. :param search: The string to search for in the byte string. :param replacement: The string to replace occurrences of the search string with. :param encoding: The encoding to use when encoding and decoding strings. Defaults to "utf-8". :param subdir: The subdirectory to search for. Defaults to "noarch". :return: The byte string with the replacements made. :raises _PaddingError: If the padding calculation results in a negative value. This function performs replacements only for pyzzer-type entry points on Windows. For all other cases, it returns the original byte string unchanged. """ zeros = "\0".encode(encoding) if _subdir_is_win(subdir): # on Windows for binary files, we currently only replace a pyzzer-type entry point # we skip all other prefix replacement if has_pyzzer_entry_point(data): return replace_pyzzer_entry_point_shebang(data, search, replacement) else: return data def replace(match: re.Match[bytes]) -> bytes: """ Replaces occurrences of the search string with the replacement string in a matched group. :param match: The matched group containing the search string. :return: The replaced string with padding. :raises _PaddingError: If the padding calculation results in a negative value. """ occurrences = match.group().count(search) padding = (len(search) - len(replacement)) * occurrences if padding < 0: raise _PaddingError return match.group().replace(search, replacement) + b"\0" * padding original_data_len = len(data) pat = re.compile( re.escape(search) + b"(?:(?!(?:" + zeros + b")).)*" + zeros, flags=re.DOTALL ) data = pat.sub(replace, data) if len(data) != original_data_len: raise RuntimeError("Replaced data has different length than original.") return data def has_pyzzer_entry_point(data: bytes) -> bool: """ Check if the given byte string contains a pyzzer entry point. :param data: The byte string to check. :return: True if the byte string contains a pyzzer entry point, False otherwise. """ pos: int = data.rfind(b"PK\x05\x06") return pos >= 0 def replace_pyzzer_entry_point_shebang( all_data: bytes, placeholder: bytes, new_prefix: str ) -> bytes: """ Code adapted from pyzzer. This is meant to deal with entry point exe's created by distlib, which consist of a launcher, then a shebang, then a zip archive of the entry point code to run. We need to change the shebang. https://bitbucket.org/vinay.sajip/pyzzer/src/5d5740cb04308f067d5844a56fbe91e7a27efccc/pyzzer/__init__.py?at=default&fileviewer=file-view-default#__init__.py-112 # NOQA :param all_data: The byte string to search for the entry point. :param placeholder: The placeholder string to search for in the entry point. :param new_prefix: The new prefix to replace the placeholder string with. :return: The updated byte string with the replaced shebang. """ # Copyright (c) 2013 Vinay Sajip. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. launcher = shebang = None pos = all_data.rfind(b"PK\x05\x06") if pos >= 0: end_cdr = all_data[pos + 12 : pos + 20] cdr_size, cdr_offset = struct.unpack("<LL", end_cdr) arc_pos = pos - cdr_size - cdr_offset data = all_data[arc_pos:] if arc_pos > 0: pos = all_data.rfind(b"#!", 0, arc_pos) if pos >= 0: shebang = all_data[pos:arc_pos] if pos > 0: launcher = all_data[:pos] if data and shebang and launcher: if hasattr(placeholder, "encode"): placeholder = placeholder.encode("utf-8") if hasattr(new_prefix, "encode"): new_prefix = new_prefix.encode("utf-8") shebang = shebang.replace(placeholder, new_prefix) all_data = b"".join([launcher, shebang, data]) return all_data def replace_long_shebang(mode: FileMode, data: bytes) -> bytes: """ Replace long shebang lines in text mode with a shorter one. :param mode: The file mode. :param data: The byte string to search for the entry point. :return: The updated byte string with the replaced shebang. """ # this function only changes a shebang line if it exists and is greater than 127 characters if mode == FileMode.text: if not isinstance(data, bytes): try: data = bytes(data, encoding="utf-8") except: data = data.encode("utf-8") shebang_match = re.match(SHEBANG_REGEX, data, re.MULTILINE) if shebang_match: whole_shebang, executable, options = shebang_match.groups() prefix, executable_name = executable.decode("utf-8").rsplit("/", 1) if len(whole_shebang) > MAX_SHEBANG_LENGTH or "\\ " in prefix: new_shebang = ( f"#!/usr/bin/env {executable_name}{options.decode('utf-8')}" ) data = data.replace(whole_shebang, new_shebang.encode("utf-8")) else: # TODO: binary shebangs exist; figure this out in the future if text works well pass return data def generate_shebang_for_entry_point( executable: str, with_usr_bin_env: bool = False ) -> str: """ This function can be used to generate a shebang line for Python entry points. Use cases: - At install/link time, to generate the `noarch: python` entry points. - conda init uses it to create its own entry point during conda-build :param executable: The path to the Python executable. :param with_usr_bin_env: Whether to use the `/usr/bin/env` approach. :return: The generated shebang line. """ shebang = f"#!{executable}\n" if os.environ.get("CONDA_BUILD") == "1" and "/_h_env_placehold" in executable: # This is being used during a conda-build process, # which uses long prefixes on purpose. This will be replaced # with the real environment prefix at install time. Do not # do nothing for now. return shebang # In principle, the naive shebang will work as long as the path # to the python executable does not contain spaces AND it's not # longer than 127 characters. Otherwise, we must fix it if len(shebang) > MAX_SHEBANG_LENGTH or " " in executable: if with_usr_bin_env: # This approach works well for all cases BUT it requires # the executable to be in PATH. In other words, the environment # needs to be activated! shebang = f"#!/usr/bin/env {basename(executable)}\n" else: # This approach follows a method inspired by `pypa/distlib` # https://github.com/pypa/distlib/blob/91aa92e64/distlib/scripts.py#L129 # Explanation: these lines are both valid Python and shell :) # 1. Python will read it as a triple-quoted string; end of story # 2. The shell will see: # * '' (empty string) # * 'exec' "path/with spaces/to/python" "this file" "arguments" # * # ''' (inline comment with three quotes, ignored by shell) # This method works well BUT in some shells, $PS1 is dropped, which # makes the prompt disappear. This is very problematic for the conda # entry point! Details: https://github.com/conda/conda/issues/11885 shebang = dals( f""" #!/bin/sh '''exec' "{executable}" "$0" "$@" #''' """ ) return shebang
_PaddingError
python
apache__airflow
providers/google/tests/unit/google/cloud/hooks/test_cloud_memorystore.py
{ "start": 9220, "end": 18661 }
class ____: def setup_method(self): with mock.patch( "airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.__init__", new=mock_base_gcp_hook_no_default_project_id, ): self.hook = CloudMemorystoreHook(gcp_conn_id="test") @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_create_instance_when_exists(self, mock_get_conn): mock_get_conn.return_value.get_instance.return_value = Instance(name=TEST_NAME) result = self.hook.create_instance( location=TEST_LOCATION, instance_id=TEST_INSTANCE_ID, instance=Instance(name=TEST_NAME), project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) mock_get_conn.return_value.get_instance.assert_called_once_with( request=dict(name="projects/test-project-id/locations/test-location/instances/test-instance-id"), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) assert Instance(name=TEST_NAME) == result @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_create_instance_when_not_exists(self, mock_get_conn): mock_get_conn.return_value.get_instance.side_effect = [ NotFound("Instance not found"), Instance(name=TEST_NAME), ] mock_get_conn.return_value.create_instance.return_value.result.return_value = Instance(name=TEST_NAME) result = self.hook.create_instance( location=TEST_LOCATION, instance_id=TEST_INSTANCE_ID, instance=Instance(name=TEST_NAME), project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) mock_get_conn.return_value.get_instance.assert_has_calls( [ mock.call( request=dict( name="projects/test-project-id/locations/test-location/instances/test-instance-id" ), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ), mock.call( request=dict( name="projects/test-project-id/locations/test-location/instances/test-instance-id" ), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ), ] ) mock_get_conn.return_value.create_instance.assert_called_once_with( request=dict( parent=TEST_PARENT, instance=Instance( name=TEST_NAME, labels={"airflow-version": "v" + version.version.replace(".", "-").replace("+", "-")}, ), instance_id=TEST_INSTANCE_ID, ), metadata=TEST_METADATA, retry=TEST_RETRY, timeout=TEST_TIMEOUT, ) assert Instance(name=TEST_NAME) == result @mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id", new_callable=PropertyMock, return_value=None, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_create_instance_without_project_id(self, mock_get_conn, mock_project_id): with pytest.raises(AirflowException): self.hook.create_instance( location=TEST_LOCATION, instance_id=TEST_INSTANCE_ID, instance=Instance(name=TEST_NAME), project_id=None, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_delete_instance(self, mock_get_conn): self.hook.delete_instance( location=TEST_LOCATION, instance=TEST_INSTANCE_ID, project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) mock_get_conn.return_value.delete_instance.assert_called_once_with( request=dict(name=TEST_NAME), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA ) @mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id", new_callable=PropertyMock, return_value=None, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_delete_instance_without_project_id(self, mock_get_conn, mock_project_id): with pytest.raises(AirflowException): self.hook.delete_instance( location=TEST_LOCATION, instance=Instance(name=TEST_NAME), project_id=None, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_get_instance(self, mock_get_conn): self.hook.get_instance( location=TEST_LOCATION, instance=TEST_INSTANCE_ID, project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) mock_get_conn.return_value.get_instance.assert_called_once_with( request=dict(name=TEST_NAME), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA ) @mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id", new_callable=PropertyMock, return_value=None, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_get_instance_without_project_id(self, mock_get_conn, mock_project_id): with pytest.raises(AirflowException): self.hook.get_instance( location=TEST_LOCATION, instance=Instance(name=TEST_NAME), project_id=None, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_list_instances(self, mock_get_conn): self.hook.list_instances( location=TEST_LOCATION, page_size=TEST_PAGE_SIZE, project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) mock_get_conn.return_value.list_instances.assert_called_once_with( request=dict(parent=TEST_PARENT, page_size=TEST_PAGE_SIZE), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) @mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id", new_callable=PropertyMock, return_value=None, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_list_instances_without_project_id(self, mock_get_conn, mock_project_id): with pytest.raises(AirflowException): self.hook.list_instances( location=TEST_LOCATION, page_size=TEST_PAGE_SIZE, project_id=None, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_update_instance(self, mock_get_conn): self.hook.update_instance( update_mask=TEST_UPDATE_MASK, instance=Instance(name=TEST_NAME), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, project_id=TEST_PROJECT_ID, ) mock_get_conn.return_value.update_instance.assert_called_once_with( request=dict(update_mask={"paths": ["memory_size_gb"]}, instance=Instance(name=TEST_NAME)), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, ) @mock.patch( "airflow.providers.google.common.hooks.base_google.GoogleBaseHook.project_id", new_callable=PropertyMock, return_value=None, ) @mock.patch("airflow.providers.google.cloud.hooks.cloud_memorystore.CloudMemorystoreHook.get_conn") def test_update_instance_without_project_id(self, mock_get_conn, mock_project_id): with pytest.raises(AirflowException): self.hook.update_instance( update_mask=TEST_UPDATE_MASK, instance=Instance(name=TEST_NAME), retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, )
TestCloudMemorystoreWithoutDefaultProjectIdHook
python
PyCQA__pylint
tests/benchmark/test_baseline_benchmarks.py
{ "start": 1680, "end": 2424 }
class ____(BaseRawFileChecker): """A checker that sleeps, the wall-clock time should reduce as we add workers. As we apply a roughly constant amount of "work" in this checker any variance is likely to be caused by the pylint system. """ name = "long-sleeper" msgs = { "R9999": ( "Test", "test-check", "Some helpful text.", ) } sleep_duration = 0.5 # the time to pretend we're doing work for def process_module(self, node: nodes.Module) -> None: """Sleeps for `sleep_duration` on each call. This effectively means each file costs ~`sleep_duration`+framework overhead """ time.sleep(self.sleep_duration)
SleepingCheckerLong
python
ipython__ipython
IPython/utils/sentinel.py
{ "start": 157, "end": 454 }
class ____: def __init__(self, name: str, module: str, docstring: str | None = None) -> None: self.name = name self.module = module if docstring: self.__doc__ = docstring def __repr__(self) -> str: return str(self.module) + "." + self.name
Sentinel
python
jazzband__prettytable
tests/test_json.py
{ "start": 85, "end": 1693 }
class ____: def test_json_output(self, helper_table: PrettyTable) -> None: result = helper_table.get_json_string() assert ( result.strip() == """ [ [ "", "Field 1", "Field 2", "Field 3" ], { "": 1, "Field 1": "value 1", "Field 2": "value2", "Field 3": "value3" }, { "": 4, "Field 1": "value 4", "Field 2": "value5", "Field 3": "value6" }, { "": 7, "Field 1": "value 7", "Field 2": "value8", "Field 3": "value9" } ]""".strip() ) options = {"fields": ["Field 1", "Field 3"]} result = helper_table.get_json_string(**options) assert ( result.strip() == """ [ [ "Field 1", "Field 3" ], { "Field 1": "value 1", "Field 3": "value3" }, { "Field 1": "value 4", "Field 3": "value6" }, { "Field 1": "value 7", "Field 3": "value9" } ]""".strip() ) def test_json_output_options(self, helper_table: PrettyTable) -> None: result = helper_table.get_json_string( header=False, indent=None, separators=(",", ":") ) assert ( result == """[{"":1,"Field 1":"value 1","Field 2":"value2","Field 3":"value3"},""" """{"":4,"Field 1":"value 4","Field 2":"value5","Field 3":"value6"},""" """{"":7,"Field 1":"value 7","Field 2":"value8","Field 3":"value9"}]""" )
TestJSONOutput
python
geekcomputers__Python
JsonParser.py
{ "start": 14, "end": 1452 }
class ____: """ this class to handle anything related to json file [as implementation of facade pattern] """ def convert_json_to_python(self, par_json_file): """ this function to convert any json file format to dictionary args: the json file return: dictionary contains json file data """ with open(par_json_file) as json_file: data_dic = json.load(json_file) return data_dic def convert_python_to_json(self, par_data_dic, par_json_file=""): """ this function converts dictionary of data to json string and store it in json file if json file pass provided if not it only returns the json string args: par_data_dic: dictionary of data par_json_file: the output json file return: json string """ if par_json_file: with open(par_json_file, "w") as outfile: return json.dump(par_data_dic, outfile) else: return json.dump(par_data_dic) def get_json_value(self, par_value, par_json_file): """ this function gets specific dictionary key value from json file args: par_value: dictionary key value par_json_file: json file return: value result """ data_dic = self.convert_json_to_python(par_json_file) return data_dic[par_value]
JsonParser
python
getsentry__sentry
tests/sentry/grouping/seer_similarity/test_seer_eligibility.py
{ "start": 730, "end": 12344 }
class ____(TestCase): def setUp(self) -> None: self.event_data = { "title": "FailedToFetchError('Charlie didn't bring the ball back')", "exception": { "values": [ { "type": "FailedToFetchError", "value": "Charlie didn't bring the ball back", "stacktrace": { "frames": [ { "function": "play_fetch", "filename": "dogpark.py", "context_line": "raise FailedToFetchError('Charlie didn't bring the ball back')", } ] }, } ] }, "platform": "python", } self.event = Event( project_id=self.project.id, event_id="11212012123120120415201309082013", data=self.event_data, ) self.variants = self.event.get_grouping_variants() self.primary_hashes = self.event.get_hashes() self.stacktrace_string = get_stacktrace_string( get_grouping_info_from_variants_legacy(self.variants) ) self.event_grouphash = GroupHash.objects.create(project_id=self.project.id, hash="908415") def test_obeys_feature_enablement_check(self) -> None: for backfill_completed_option, expected_result in [(None, False), (11211231, True)]: self.project.update_option( "sentry:similarity_backfill_completed", backfill_completed_option ) assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ), f"Case {backfill_completed_option} failed." def test_obeys_content_filter(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for content_eligibility, expected_result in [(True, True), (False, False)]: with patch( "sentry.grouping.ingest.seer._event_content_is_seer_eligible", return_value=content_eligibility, ): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) def test_obeys_global_seer_killswitch(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for killswitch_enabled, expected_result in [(True, False), (False, True)]: with override_options({"seer.global-killswitch.enabled": killswitch_enabled}): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) def test_obeys_similarity_service_killswitch(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for killswitch_enabled, expected_result in [(True, False), (False, True)]: with override_options({"seer.similarity-killswitch.enabled": killswitch_enabled}): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) def test_obeys_project_specific_killswitch(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for blocked_projects, expected_result in [([self.project.id], False), ([], True)]: with override_options( {"seer.similarity.grouping_killswitch_projects": blocked_projects} ): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) def test_obeys_global_ratelimit(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for ratelimit_enabled, expected_result in [(True, False), (False, True)]: with patch( "sentry.grouping.ingest.seer.ratelimiter.backend.is_limited", wraps=lambda key, is_enabled=ratelimit_enabled, **_kwargs: ( is_enabled if key == "seer:similarity:global-limit" else False ), ): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) def test_obeys_project_ratelimit(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for ratelimit_enabled, expected_result in [(True, False), (False, True)]: with patch( "sentry.grouping.ingest.seer.ratelimiter.backend.is_limited", wraps=lambda key, is_enabled=ratelimit_enabled, **_kwargs: ( is_enabled if key == f"seer:similarity:project-{self.project.id}-limit" else False ), ): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) def test_obeys_circuit_breaker(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for request_allowed, expected_result in [(True, True), (False, False)]: with patch( "sentry.grouping.ingest.seer.CircuitBreaker.should_allow_request", return_value=request_allowed, ): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) def test_obeys_customized_fingerprint_check(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) default_fingerprint_event = Event( project_id=self.project.id, event_id="11212012123120120415201309082013", data={**self.event_data, "fingerprint": ["{{ default }}"]}, ) hybrid_fingerprint_event = Event( project_id=self.project.id, event_id="12312012041520130908201311212012", data={**self.event_data, "fingerprint": ["{{ default }}", "maisey"]}, ) custom_fingerprint_event = Event( project_id=self.project.id, event_id="04152013090820131121201212312012", data={**self.event_data, "fingerprint": ["charlie"]}, ) built_in_fingerprint_event = Event( project_id=self.project.id, event_id="09082013112120121231201204152013", data={ **self.event_data, "fingerprint": ["failedtofetcherror"], "_fingerprint_info": { "matched_rule": { "is_builtin": True, "matchers": [["type", "FailedToFetchError"]], "fingerprint": ["failedtofetcherror"], "text": 'type:"FailedToFetchError" -> "failedtofetcherror"', } }, }, ) for event, expected_result in [ (default_fingerprint_event, True), (hybrid_fingerprint_event, True), (custom_fingerprint_event, False), (built_in_fingerprint_event, False), ]: grouphash = GroupHash( project_id=self.project.id, hash=hash_from_values(event.data["fingerprint"]) ) assert ( should_call_seer_for_grouping(event, event.get_grouping_variants(), grouphash) is expected_result ), f'Case with fingerprint {event.data["fingerprint"]} failed.' def test_obeys_excessive_frame_check(self) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) for frame_check_result, expected_result in [(True, False), (False, True)]: with patch( "sentry.grouping.ingest.seer._stacktrace_exceeds_limits", return_value=frame_check_result, ): assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is expected_result ) @patch("sentry.grouping.ingest.seer.record_did_call_seer_metric") def test_obeys_empty_stacktrace_string_check( self, mock_record_did_call_seer: MagicMock ) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) empty_frame_event = Event( project_id=self.project.id, event_id="12312012112120120908201304152013", data={ "title": "Dogs are great!", "platform": "python", "stacktrace": {"frames": [{}]}, }, ) empty_frame_variants = empty_frame_event.get_grouping_variants() empty_frame_grouphash = GroupHash(project_id=self.project.id, hash="415908") empty_frame_stacktrace_string = get_stacktrace_string( get_grouping_info_from_variants_legacy(empty_frame_variants) ) assert self.stacktrace_string != "" assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is True ) mock_record_did_call_seer.assert_not_called() assert empty_frame_stacktrace_string == "" assert ( should_call_seer_for_grouping( empty_frame_event, empty_frame_variants, empty_frame_grouphash ) is False ) mock_record_did_call_seer.assert_any_call( empty_frame_event, call_made=False, blocker="empty-stacktrace-string" ) @patch("sentry.grouping.ingest.seer.record_did_call_seer_metric") def test_obeys_race_condition_skip(self, mock_record_did_call_seer: MagicMock) -> None: self.project.update_option("sentry:similarity_backfill_completed", int(time())) assert self.event.should_skip_seer is False assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is True ) self.event.should_skip_seer = True assert ( should_call_seer_for_grouping(self.event, self.variants, self.event_grouphash) is False ) mock_record_did_call_seer.assert_any_call( self.event, call_made=False, blocker="race_condition" ) @patch("sentry.grouping.ingest.seer.get_similarity_data_from_seer", return_value=[]) def test_stacktrace_string_not_saved_in_event( self, mock_get_similarity_data: MagicMock ) -> None: self.project.update_option("sentry:similarity_backfill_completed", 1) event = save_new_event(self.event_data, self.project) assert mock_get_similarity_data.call_count == 1 assert "raise FailedToFetchError('Charlie didn't bring the ball back')" in ( mock_get_similarity_data.call_args.args[0]["stacktrace"] ) assert event.data.get("stacktrace_string") is None
ShouldCallSeerTest
python
jpadilla__pyjwt
jwt/types.py
{ "start": 2524, "end": 2772 }
class ____(TypedDict): verify_signature: bool require: list[str] strict_aud: bool verify_aud: bool verify_exp: bool verify_iat: bool verify_iss: bool verify_jti: bool verify_nbf: bool verify_sub: bool
FullOptions
python
pytorch__pytorch
torch/_inductor/codegen/multi_kernel.py
{ "start": 5284, "end": 11316 }
class ____: """ This class maintains the compile time state for multi kernels. Assume we do codegen for a MultiKernel encapsulating kernel1 and kernel2. The generated definition for the multi-kernel will looks like: ``` multi_kernel_kernel1 = MultiKernelCall( [kernel1, kernel2], multi_kernel_definition_code ) ``` Here is a concrete example: https://gist.github.com/shunting314/d9f3fb6bc6cee3dbae005825ca196d39 """ def __init__(self, kernels): assert len(kernels) >= 2 self.kernels = kernels self.kernel_name = V.graph.wrapper_code.multi_kernel_state.define_kernel( kernels ) # need this since some code in inductor check if the kernel object has an args # attribute to decide if it's a non-null kernel. self.args = object() @staticmethod def _merge_workspace_args(left: list[WorkspaceArg], right: list[WorkspaceArg]): if left == right: return left result = {x.inner_name: x for x in left} for arg in right: if arg.inner_name in result: result[arg.inner_name] = WorkspaceArg.maximum( result[arg.inner_name], arg ) else: result[arg.inner_name] = arg return [*result.values()] @staticmethod def merge_workspaces_inplace(kernels): if len(kernels) < 2: return # All kernels must share the same workspace workspace_args = functools.reduce( MultiKernel._merge_workspace_args, [kernel.args.workspace_args for kernel in kernels], ) for kernel in kernels: kernel.args.workspace_args = workspace_args return workspace_args def call_kernel(self, kernel_name): """ Collect the union of arguments from all subkernels as the arguments for the multi-kernel. """ # Prevent circular import from ..select_algorithm import TritonTemplateKernel assert kernel_name == self.kernel_name V.graph.wrapper_code.write_triton_header_once() _, call_args, _, arg_types = self.kernels[0].args.python_argdefs() for kernel in self.kernels[1:]: _, other_call_args, _, other_arg_types = kernel.args.python_argdefs() assert call_args == other_call_args, (call_args, other_call_args) assert arg_types == other_arg_types if V.graph.cpp_wrapper and not config.triton.autotune_at_compile_time: # for the second pass of cpp-wrapper codegen, we should call # the fast kernel directly kernel_name = MultiKernelCall.lookup_choice(self.kernel_name) if isinstance(self.kernels[0], TritonTemplateKernel) and isinstance( self.kernels[0].output_node, MultiTemplateBuffer ): # For matmuls the grid arguments are passed in as additional arguments # to the kernel run method. These grids change based on the various # parameters of the matmul. So we need to pass each kernel's grid into # the multi call kernel. multi_call_args = call_args multi_call_arg_types = arg_types for kernel in self.kernels: additional_call_args, additional_arg_types = ( kernel.additional_call_args_and_types() ) multi_call_args.extend(list(additional_call_args)) multi_call_arg_types.extend(list(additional_arg_types)) else: # numels for all subkernels should be the same. Use kernels[0] here self.kernels[0].add_numel_to_call_args(kernel_name, call_args, arg_types) multi_call_args = call_args multi_call_arg_types = arg_types for ws in self.kernels[0].args.workspace_args: V.graph.wrapper_code.generate_workspace_allocation(ws) if V.graph.cpp_wrapper: # We have already selected the best kernel at compile time # so we only have one set of call args. NB: this currently # doesn't work with MultiTemplateBuffer kernels. @bobrenjc93 # will add it in a subsequent PR. V.graph.wrapper_code.generate_kernel_call( kernel_name, call_args, arg_types=arg_types ) else: V.graph.wrapper_code.generate_kernel_call( kernel_name, multi_call_args, arg_types=multi_call_arg_types ) for ws in reversed(self.kernels[0].args.workspace_args): V.graph.wrapper_code.generate_workspace_deallocation(ws) def codegen_nan_check(self): wrapper = V.graph.wrapper_code seen: OrderedSet[str] = OrderedSet() for k in self.kernels: _, call_args, precompile_args, _ = k.args.python_argdefs() for arg, precompile_arg in zip(call_args, precompile_args): if arg in seen: continue seen.add(arg) if isinstance(precompile_arg, TensorArg): line = f"assert not {arg}.isnan().any().item()" wrapper.writeline(line) line = f"assert not {arg}.isinf().any().item()" wrapper.writeline(line) @property def removed_buffers(self): return OrderedSet.intersection(*[k.removed_buffers for k in self.kernels]) @property def inplaced_to_remove(self): return OrderedSet.intersection(*[k.inplaced_to_remove for k in self.kernels]) @property @cache_on_self def inplace_update_buffers(self): """ Make sure all kernels have the same inplace update mappings. """ for k in self.kernels[1:]: assert k.inplace_update_buffers == self.kernels[0].inplace_update_buffers return self.kernels[0].inplace_update_buffers def warn_mix_layout(self, kernel_name: str): pass
MultiKernel
python
dask__dask
dask/dataframe/dask_expr/_util.py
{ "start": 3700, "end": 6503 }
class ____: """Helper class to wrap backend data The primary purpose of this class is to provide caching outside the ``FromPandas`` class. """ def __init__(self, data): self._data = data self._division_info = LRU(10) @functools.cached_property def _token(self): from dask.tokenize import _tokenize_deterministic return _tokenize_deterministic(self._data) def __len__(self): return len(self._data) def __getattr__(self, key: str) -> Any: try: return object.__getattribute__(self, key) except AttributeError: # Return the underlying backend attribute return getattr(self._data, key) def __reduce__(self): return type(self), (self._data,) def __deepcopy__(self, memodict=None): return type(self)(self._data.copy()) @normalize_token.register(_BackendData) def normalize_data_wrapper(data): return data._token def _maybe_from_pandas(dfs): from dask.dataframe.dask_expr import from_pandas def _pd_series_or_dataframe(x): # `x` can be a cudf Series/DataFrame return not is_dask_collection(x) and (is_series_like(x) or is_dataframe_like(x)) dfs = [from_pandas(df, 1) if _pd_series_or_dataframe(df) else df for df in dfs] return dfs def _get_shuffle_preferring_order(shuffle): if shuffle is not None: return shuffle # Choose tasks over disk since it keeps the order shuffle = get_default_shuffle_method() if shuffle == "disk": return "tasks" return shuffle def _raise_if_object_series(x, funcname): """ Utility function to raise an error if an object column does not support a certain operation like `mean`. """ if x.ndim == 1 and hasattr(x, "dtype"): if x.dtype == object: raise ValueError(f"`{funcname}` not supported with object series") elif is_string_dtype(x): raise ValueError(f"`{funcname}` not supported with string series") def _is_any_real_numeric_dtype(arr_or_dtype): try: from pandas.api.types import is_any_real_numeric_dtype return is_any_real_numeric_dtype(arr_or_dtype) except ImportError: # Temporary/soft pandas<2 support to enable cudf dev # TODO: Remove `try` block after 4/2024 from pandas.api.types import is_bool_dtype, is_complex_dtype, is_numeric_dtype return ( is_numeric_dtype(arr_or_dtype) and not is_complex_dtype(arr_or_dtype) and not is_bool_dtype(arr_or_dtype) ) def get_specified_shuffle(shuffle_method): # Take the config shuffle if given, otherwise defer evaluation until optimize return shuffle_method or config.get("dataframe.shuffle.method", None)
_BackendData
python
dagster-io__dagster
python_modules/dagster/dagster_tests/components_tests/resolution_tests/test_resolvable_model.py
{ "start": 287, "end": 576 }
class ____(BaseModel, dg.Resolvable): val1_renamed: Annotated[ int, dg.Resolver( resolve_val1, model_field_type=str, model_field_name="val1", inject_before_resolve=False, ), ] val2: Optional[str]
InnerObject
python
weaviate__weaviate-python-client
weaviate/exceptions.py
{ "start": 8024, "end": 8276 }
class ____(WeaviateQueryError): """Is raised if a gRPC delete many request to Weaviate fails in any way.""" def __init__(self, message: str): super().__init__(message, "GRPC delete") self.message = message
WeaviateDeleteManyError
python
Netflix__metaflow
metaflow/plugins/aws/step_functions/step_functions.py
{ "start": 848, "end": 962 }
class ____(MetaflowException): headline = "AWS Step Functions scheduling error"
StepFunctionsSchedulingException
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/prefetch_test.py
{ "start": 5042, "end": 6652 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(index=[-1, 10, 11]))) def testInvalidIndex(self, index): dataset = dataset_ops.Dataset.range(10).prefetch(buffer_size=5) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, index=index)) @combinations.generate( combinations.times(test_base.default_test_combinations(), combinations.combine(index=[-2, 0, 1]))) def testEmptyDataset(self, index): dataset = dataset_ops.Dataset.from_tensor_slices([]).prefetch(buffer_size=5) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, index=index)) @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(elements=[10, 50, 100], buffer_size=[0, 5, 10]))) def testMultipleCombinations(self, elements, buffer_size): dataset = dataset_ops.Dataset.range(elements).prefetch( buffer_size=buffer_size) len_dataset = self.evaluate(dataset.cardinality()) expected_output = np.arange(elements) for i in range(len_dataset): self.assertEqual( self.evaluate(random_access.at(dataset, index=i)), expected_output[i]) with self.assertRaises(errors.OutOfRangeError): self.evaluate(random_access.at(dataset, index=len_dataset)) if __name__ == "__main__": test.main()
PrefetchRandomAccessTest
python
getsentry__sentry
src/sentry/issues/ignored.py
{ "start": 1200, "end": 5958 }
class ____(TypedDict, total=False): ignoreCount: int | None ignoreUntil: datetime | None ignoreUserCount: int | None ignoreUserWindow: int | None ignoreWindow: int | None actor: User | None def handle_archived_until_escalating( group_list: Sequence[Group], acting_user: RpcUser | User | None, projects: Sequence[Project], sender: Any, ) -> dict[str, bool]: """ Handle issues that are archived until escalating and create a forecast for them. Issues that are marked as ignored with `archiveDuration: until_escalating` in the statusDetail are treated as `archived_until_escalating`. """ metrics.incr("group.archived_until_escalating", skip_internal=True) for group in group_list: remove_group_from_inbox(group, action=GroupInboxRemoveAction.IGNORED, user=acting_user) generate_and_save_forecasts(group_list) logger.info( "archived_until_escalating.forecast_created", extra={ "detail": "Created forecast for groups", "group_ids": [group.id for group in group_list], }, ) groups_by_project_id = defaultdict(list) for group in group_list: groups_by_project_id[group.project_id].append(group) for project in projects: project_groups = groups_by_project_id.get(project.id) issue_archived.send_robust( project=project, user=acting_user, group_list=project_groups, activity_data={"until_escalating": True}, sender=sender, ) return {"ignoreUntilEscalating": True} def handle_ignored( group_list: Sequence[Group], status_details: dict[str, Any], acting_user: RpcUser | User | None, ) -> IgnoredStatusDetails: """ Handle issues that are ignored and create a snooze for them. Evaluate ignored issues according to the statusDetails and create a snooze as needed. Returns: a dict with the statusDetails for ignore conditions. """ metrics.incr("group.ignored", skip_internal=True) for group in group_list: remove_group_from_inbox(group, action=GroupInboxRemoveAction.IGNORED, user=acting_user) new_status_details: IgnoredStatusDetails = {} ignore_duration = ( status_details.pop("ignoreDuration", None) or status_details.pop("snoozeDuration", None) ) or None ignore_count = status_details.pop("ignoreCount", None) or None ignore_window = status_details.pop("ignoreWindow", None) or None ignore_user_count = status_details.pop("ignoreUserCount", None) or None ignore_user_window = status_details.pop("ignoreUserWindow", None) or None if ignore_duration or ignore_count or ignore_user_count: if ignore_duration: ignore_until = timezone.now() + timedelta(minutes=ignore_duration) else: ignore_until = None for group in group_list: state = {} if ignore_count and not ignore_window: state["times_seen"] = group.times_seen if ignore_user_count and not ignore_user_window: state["users_seen"] = group.count_users_seen( referrer=Referrer.TAGSTORE_GET_GROUPS_USER_COUNTS_IGNORED.value ) GroupSnooze.objects.create_or_update( group=group, values={ "until": ignore_until, "count": ignore_count, "window": ignore_window, "user_count": ignore_user_count, "user_window": ignore_user_window, "state": state, "actor_id": acting_user.id if acting_user else None, }, ) Group.objects.filter(id=group.id, status=GroupStatus.UNRESOLVED).update( substatus=GroupSubStatus.UNTIL_CONDITION_MET, status=GroupStatus.IGNORED ) with in_test_hide_transaction_boundary(): if acting_user: serialized_user = user_service.serialize_many( filter=dict(user_ids=[acting_user.id]), as_user=serialize_generic_user(acting_user), ) new_status_details = IgnoredStatusDetails( ignoreCount=ignore_count, ignoreUntil=ignore_until, ignoreUserCount=ignore_user_count, ignoreUserWindow=ignore_user_window, ignoreWindow=ignore_window, actor=serialized_user[0] if serialized_user else None, ) else: GroupSnooze.objects.filter(group__in=[group.id for group in group_list]).delete() return new_status_details
IgnoredStatusDetails
python
scipy__scipy
scipy/optimize/_root_scalar.py
{ "start": 409, "end": 20391 }
class ____: """Decorator that caches the value and derivative(s) of function each time it is called. This is a simplistic memoizer that calls and caches a single value of ``f(x, *args)``. It assumes that `args` does not change between invocations. It supports the use case of a root-finder where `args` is fixed, `x` changes, and only rarely, if at all, does x assume the same value more than once.""" def __init__(self, fun): self.fun = fun self.vals = None self.x = None self.n_calls = 0 def __call__(self, x, *args): r"""Calculate f or use cached value if available""" # Derivative may be requested before the function itself, always check if self.vals is None or x != self.x: fg = self.fun(x, *args) self.x = x self.n_calls += 1 self.vals = fg[:] return self.vals[0] def fprime(self, x, *args): r"""Calculate f' or use a cached value if available""" if self.vals is None or x != self.x: self(x, *args) return self.vals[1] def fprime2(self, x, *args): r"""Calculate f'' or use a cached value if available""" if self.vals is None or x != self.x: self(x, *args) return self.vals[2] def ncalls(self): return self.n_calls def root_scalar(f, args=(), method=None, bracket=None, fprime=None, fprime2=None, x0=None, x1=None, xtol=None, rtol=None, maxiter=None, options=None): """ Find a root of a scalar function. Parameters ---------- f : callable A function to find a root of. Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where ``my_args`` and ``my_kwargs`` are required positional and keyword arguments. Rather than passing ``f0`` as the callable, wrap it to accept only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been gathered before invoking this function. args : tuple, optional Extra arguments passed to the objective function and its derivative(s). method : str, optional Type of solver. Should be one of - 'bisect' :ref:`(see here) <optimize.root_scalar-bisect>` - 'brentq' :ref:`(see here) <optimize.root_scalar-brentq>` - 'brenth' :ref:`(see here) <optimize.root_scalar-brenth>` - 'ridder' :ref:`(see here) <optimize.root_scalar-ridder>` - 'toms748' :ref:`(see here) <optimize.root_scalar-toms748>` - 'newton' :ref:`(see here) <optimize.root_scalar-newton>` - 'secant' :ref:`(see here) <optimize.root_scalar-secant>` - 'halley' :ref:`(see here) <optimize.root_scalar-halley>` bracket: A sequence of 2 floats, optional An interval bracketing a root. ``f(x, *args)`` must have different signs at the two endpoints. x0 : float, optional Initial guess. x1 : float, optional A second guess. fprime : bool or callable, optional If `fprime` is a boolean and is True, `f` is assumed to return the value of the objective function and of the derivative. `fprime` can also be a callable returning the derivative of `f`. In this case, it must accept the same arguments as `f`. fprime2 : bool or callable, optional If `fprime2` is a boolean and is True, `f` is assumed to return the value of the objective function and of the first and second derivatives. `fprime2` can also be a callable returning the second derivative of `f`. In this case, it must accept the same arguments as `f`. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. options : dict, optional A dictionary of solver options. E.g., ``k``, see :obj:`show_options()` for details. Returns ------- sol : RootResults The solution represented as a ``RootResults`` object. Important attributes are: ``root`` the solution , ``converged`` a boolean flag indicating if the algorithm exited successfully and ``flag`` which describes the cause of the termination. See `RootResults` for a description of other attributes. See also -------- show_options : Additional options accepted by the solvers root : Find a root of a vector function. Notes ----- This section describes the available solvers that can be selected by the 'method' parameter. The default is to use the best method available for the situation presented. If a bracket is provided, it may use one of the bracketing methods. If a derivative and an initial value are specified, it may select one of the derivative-based methods. If no method is judged applicable, it will raise an Exception. Arguments for each method are as follows (x=required, o=optional). +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | method | f | args | bracket | x0 | x1 | fprime | fprime2 | xtol | rtol | maxiter | options | +===============================================+===+======+=========+====+====+========+=========+======+======+=========+=========+ | :ref:`bisect <optimize.root_scalar-bisect>` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`brentq <optimize.root_scalar-brentq>` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`brenth <optimize.root_scalar-brenth>` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`ridder <optimize.root_scalar-ridder>` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`toms748 <optimize.root_scalar-toms748>` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`secant <optimize.root_scalar-secant>` | x | o | | x | o | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`newton <optimize.root_scalar-newton>` | x | o | | x | | o | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`halley <optimize.root_scalar-halley>` | x | o | | x | | x | x | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ Examples -------- Find the root of a simple cubic >>> from scipy import optimize >>> def f(x): ... return (x**3 - 1) # only one real root at x = 1 >>> def fprime(x): ... return 3*x**2 The `brentq` method takes as input a bracket >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq') >>> sol.root, sol.iterations, sol.function_calls (1.0, 10, 11) The `newton` method takes as input a single point and uses the derivative(s). >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton') >>> sol.root, sol.iterations, sol.function_calls (1.0, 11, 22) The function can provide the value and derivative(s) in a single call. >>> def f_p_pp(x): ... return (x**3 - 1), 3*x**2, 6*x >>> sol = optimize.root_scalar( ... f_p_pp, x0=0.2, fprime=True, method='newton' ... ) >>> sol.root, sol.iterations, sol.function_calls (1.0, 11, 11) >>> sol = optimize.root_scalar( ... f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley' ... ) >>> sol.root, sol.iterations, sol.function_calls (1.0, 7, 8) """ # noqa: E501 if not isinstance(args, tuple): args = (args,) if options is None: options = {} # fun also returns the derivative(s) is_memoized = False if fprime2 is not None and not callable(fprime2): if bool(fprime2): f = MemoizeDer(f) is_memoized = True fprime2 = f.fprime2 fprime = f.fprime else: fprime2 = None if fprime is not None and not callable(fprime): if bool(fprime): f = MemoizeDer(f) is_memoized = True fprime = f.fprime else: fprime = None # respect solver-specific default tolerances - only pass in if actually set kwargs = {} for k in ['xtol', 'rtol', 'maxiter']: v = locals().get(k) if v is not None: kwargs[k] = v # Set any solver-specific options if options: kwargs.update(options) # Always request full_output from the underlying method as _root_scalar # always returns a RootResults object kwargs.update(full_output=True, disp=False) # Pick a method if not specified. # Use the "best" method available for the situation. if not method: if bracket is not None: method = 'brentq' elif x0 is not None: if fprime: if fprime2: method = 'halley' else: method = 'newton' elif x1 is not None: method = 'secant' else: method = 'newton' if not method: raise ValueError('Unable to select a solver as neither bracket ' 'nor starting point provided.') meth = method.lower() map2underlying = {'halley': 'newton', 'secant': 'newton'} try: methodc = getattr(optzeros, map2underlying.get(meth, meth)) except AttributeError as e: raise ValueError(f'Unknown solver {meth}') from e if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']: if not isinstance(bracket, list | tuple | np.ndarray): raise ValueError(f'Bracket needed for {method}') a, b = bracket[:2] try: r, sol = methodc(f, a, b, args=args, **kwargs) except ValueError as e: # gh-17622 fixed some bugs in low-level solvers by raising an error # (rather than returning incorrect results) when the callable # returns a NaN. It did so by wrapping the callable rather than # modifying compiled code, so the iteration count is not available. if hasattr(e, "_x"): sol = optzeros.RootResults(root=e._x, iterations=np.nan, function_calls=e._function_calls, flag=str(e), method=method) else: raise elif meth in ['secant']: if x0 is None: raise ValueError(f'x0 must not be None for {method}') if 'xtol' in kwargs: kwargs['tol'] = kwargs.pop('xtol') r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None, x1=x1, **kwargs) elif meth in ['newton']: if x0 is None: raise ValueError(f'x0 must not be None for {method}') if not fprime: # approximate fprime with finite differences def fprime(x, *args): # `root_scalar` doesn't actually seem to support vectorized # use of `newton`. In that case, `approx_derivative` will # always get scalar input. Nonetheless, it always returns an # array, so we extract the element to produce scalar output. # Similarly, `approx_derivative` always passes array input, so # we extract the element to ensure the user's function gets # scalar input. def f_wrapped(x, *args): return f(x[0], *args) return approx_derivative(f_wrapped, x, method='2-point', args=args)[0] if 'xtol' in kwargs: kwargs['tol'] = kwargs.pop('xtol') r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None, **kwargs) elif meth in ['halley']: if x0 is None: raise ValueError(f'x0 must not be None for {method}') if not fprime: raise ValueError(f'fprime must be specified for {method}') if not fprime2: raise ValueError(f'fprime2 must be specified for {method}') if 'xtol' in kwargs: kwargs['tol'] = kwargs.pop('xtol') r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs) else: raise ValueError(f'Unknown solver {method}') if is_memoized: # Replace the function_calls count with the memoized count. # Avoids double and triple-counting. n_calls = f.n_calls sol.function_calls = n_calls return sol def _root_scalar_brentq_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function. bracket: A sequence of 2 floats, optional An interval bracketing a root. ``f(x, *args)`` must have different signs at the two endpoints. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. options: dict, optional Specifies any method-specific options not covered above """ pass def _root_scalar_brenth_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function. bracket: A sequence of 2 floats, optional An interval bracketing a root. ``f(x, *args)`` must have different signs at the two endpoints. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. options: dict, optional Specifies any method-specific options not covered above. """ pass def _root_scalar_toms748_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function. bracket: A sequence of 2 floats, optional An interval bracketing a root. ``f(x, *args)`` must have different signs at the two endpoints. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. options: dict, optional Specifies any method-specific options not covered above. """ pass def _root_scalar_secant_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. x0 : float, required Initial guess. x1 : float, optional A second guess. Must be different from `x0`. If not specified, a value near `x0` will be chosen. options: dict, optional Specifies any method-specific options not covered above. """ pass def _root_scalar_newton_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function and its derivative. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. x0 : float, required Initial guess. fprime : bool or callable, optional If `fprime` is a boolean and is True, `f` is assumed to return the value of derivative along with the objective function. `fprime` can also be a callable returning the derivative of `f`. In this case, it must accept the same arguments as `f`. options: dict, optional Specifies any method-specific options not covered above. """ pass def _root_scalar_halley_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function and its derivatives. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. x0 : float, required Initial guess. fprime : bool or callable, required If `fprime` is a boolean and is True, `f` is assumed to return the value of derivative along with the objective function. `fprime` can also be a callable returning the derivative of `f`. In this case, it must accept the same arguments as `f`. fprime2 : bool or callable, required If `fprime2` is a boolean and is True, `f` is assumed to return the value of 1st and 2nd derivatives along with the objective function. `fprime2` can also be a callable returning the 2nd derivative of `f`. In this case, it must accept the same arguments as `f`. options: dict, optional Specifies any method-specific options not covered above. """ pass def _root_scalar_ridder_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function. bracket: A sequence of 2 floats, optional An interval bracketing a root. ``f(x, *args)`` must have different signs at the two endpoints. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. options: dict, optional Specifies any method-specific options not covered above. """ pass def _root_scalar_bisect_doc(): r""" Options ------- args : tuple, optional Extra arguments passed to the objective function. bracket: A sequence of 2 floats, optional An interval bracketing a root. ``f(x, *args)`` must have different signs at the two endpoints. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. options: dict, optional Specifies any method-specific options not covered above. """ pass
MemoizeDer
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 873412, "end": 874696 }
class ____(Geometry): """ Polygon schema wrapper. Polygon geometry object. https://tools.ietf.org/html/rfc7946#section-3.1.6 Parameters ---------- coordinates : Sequence[Sequence[Sequence[float], :class:`Position`]] type : Literal['Polygon'] Specifies the type of GeoJSON object. bbox : :class:`BBox`, Sequence[float] Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. The value of the bbox member is an array of length 2*n where n is the number of dimensions represented in the contained geometries, with all axes of the most southwesterly point followed by all axes of the more northeasterly point. The axes order of a bbox follows the axes order of geometries. https://tools.ietf.org/html/rfc7946#section-5 """ _schema = {"$ref": "#/definitions/Polygon"} def __init__( self, coordinates: Optional[ Sequence[Sequence[SchemaBase | Sequence[float]]] ] = Undefined, type: Optional[Literal["Polygon"]] = Undefined, bbox: Optional[SchemaBase | Sequence[float]] = Undefined, **kwds, ): super().__init__(coordinates=coordinates, type=type, bbox=bbox, **kwds)
Polygon
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 55306, "end": 55530 }
class ____(ToFrame): _parameters = ["frame", "index", "name"] _defaults = {"name": no_default, "index": True} _keyword_only = ["name", "index"] operation = M.to_frame _filter_passthrough = True
ToFrameIndex
python
facebook__pyre-check
client/commands/tests/pyre_server_options_test.py
{ "start": 940, "end": 2220 }
class ____(testslide.TestCase): def test_create(self) -> None: language_server_features = features.LanguageServerFeatures() start_arguments = start.Arguments( backend_arguments.BaseArguments( source_paths=backend_arguments.SimpleSourcePath(), log_path="/log/path", global_root="/global/root", ), socket_path=Path("irrelevant_socket_path.sock"), ) configuration = FakeFrontendConfiguration() result = pyre_server_options.PyreServerOptions.create_from_start_arguments( start_arguments, configuration, language_server_features, identifiers.PyreFlavor.CLASSIC, True, ) expected = pyre_server_options.PyreServerOptions( server_start_command=frontend_configuration.DefaultServerStartCommand( "/fake/binary" ), project_identifier="test//local", start_arguments=start_arguments, language_server_features=language_server_features, strict_default=False, excludes=[], flavor=identifiers.PyreFlavor.CLASSIC, ) self.assertEqual(result, expected)
ServerOptionsTest
python
huggingface__transformers
src/transformers/models/dia/processing_dia.py
{ "start": 1239, "end": 1843 }
class ____(ProcessingKwargs, total=False): audio_kwargs: DiaAudioKwargs _defaults = { "text_kwargs": { "padding": True, "padding_side": "right", "add_special_tokens": False, }, "audio_kwargs": { "eos_token_id": 1024, "pad_token_id": 1025, "bos_token_id": 1026, "delay_pattern": [0, 8, 9, 10, 11, 12, 13, 14, 15], "generation": True, "sampling_rate": 44100, }, "common_kwargs": { "return_tensors": "pt", }, }
DiaProcessorKwargs
python
django__django
tests/servers/tests.py
{ "start": 15214, "end": 15856 }
class ____(LiveServerBase): """If LiveServerTestCase isn't threaded, these tests will hang.""" def test_view_calls_subview(self): url = "/subview_calling_view/?%s" % urlencode({"url": self.live_server_url}) with self.urlopen(url) as f: self.assertEqual(f.read(), b"subview calling view: subview") def test_check_model_instance_from_subview(self): url = "/check_model_instance_from_subview/?%s" % urlencode( { "url": self.live_server_url, } ) with self.urlopen(url) as f: self.assertIn(b"emily", f.read())
LiveServerThreadedTests