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
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/test_response_format_integration.py
{ "start": 1651, "end": 4856 }
class ____(BaseModel): """Weather response.""" temperature: float = Field(description="The temperature in fahrenheit") condition: str = Field(description="Weather condition") def get_weather(city: str) -> str: # noqa: ARG001 """Get the weather for a city.""" return f"The weather in {city} is sunny and 75°F." @pytest.mark.requires("langchain_openai") @pytest.mark.vcr @pytest.mark.parametrize("use_responses_api", [False, True]) def test_inference_to_native_output(use_responses_api: bool) -> None: """Test that native output is inferred when a model supports it.""" from langchain_openai import ChatOpenAI model_kwargs = {"model": "gpt-5", "use_responses_api": use_responses_api} if "OPENAI_API_KEY" not in os.environ: model_kwargs["api_key"] = "foo" model = ChatOpenAI(**model_kwargs) agent = create_agent( model, system_prompt=( "You are a helpful weather assistant. Please call the get_weather tool " "once, then use the WeatherReport tool to generate the final response." ), tools=[get_weather], response_format=WeatherBaseModel, ) response = agent.invoke({"messages": [HumanMessage("What's the weather in Boston?")]}) assert isinstance(response["structured_response"], WeatherBaseModel) assert response["structured_response"].temperature == 75.0 assert response["structured_response"].condition.lower() == "sunny" assert len(response["messages"]) == 4 assert [m.type for m in response["messages"]] == [ "human", # "What's the weather?" "ai", # "What's the weather?" "tool", # "The weather is sunny and 75°F." "ai", # structured response ] @pytest.mark.requires("langchain_openai") @pytest.mark.vcr @pytest.mark.parametrize("use_responses_api", [False, True]) def test_inference_to_tool_output(use_responses_api: bool) -> None: """Test that tool output is inferred when a model supports it.""" from langchain_openai import ChatOpenAI model_kwargs = {"model": "gpt-5", "use_responses_api": use_responses_api} if "OPENAI_API_KEY" not in os.environ: model_kwargs["api_key"] = "foo" model = ChatOpenAI(**model_kwargs) agent = create_agent( model, system_prompt=( "You are a helpful weather assistant. Please call the get_weather tool " "once, then use the WeatherReport tool to generate the final response." ), tools=[get_weather], response_format=ToolStrategy(WeatherBaseModel), ) response = agent.invoke({"messages": [HumanMessage("What's the weather?")]}) assert isinstance(response["structured_response"], WeatherBaseModel) assert response["structured_response"].temperature == 75.0 assert response["structured_response"].condition.lower() == "sunny" assert len(response["messages"]) == 5 assert [m.type for m in response["messages"]] == [ "human", # "What's the weather?" "ai", # "What's the weather?" "tool", # "The weather is sunny and 75°F." "ai", # structured response "tool", # artificial tool message ]
WeatherBaseModel
python
getsentry__sentry
src/sentry/integrations/messaging/spec.py
{ "start": 1420, "end": 1786 }
class ____: """An integration's set of view classes for linking and unlinking identities.""" link_personal_identity: type[View] unlink_personal_identity: type[View] # Optional until supported on all messaging integrations link_team_identity: type[View] | None = None unlink_team_identity: type[View] | None = None
MessagingIdentityLinkViewSet
python
apache__airflow
providers/redis/tests/unit/redis/queues/test_redis.py
{ "start": 2411, "end": 2898 }
class ____: @pytest.mark.usefixtures("cleanup_providers_manager") def test_provider_integrations_with_scheme_param(self): from airflow.providers.common.messaging.triggers.msg_queue import MessageQueueTrigger from airflow.providers.redis.triggers.redis_await_message import AwaitMessageTrigger trigger = MessageQueueTrigger(scheme="redis+pubsub", channels="test_channel") assert isinstance(trigger.trigger, AwaitMessageTrigger)
TestMessageQueueTrigger
python
bokeh__bokeh
src/bokeh/models/sources.py
{ "start": 3347, "end": 4591 }
class ____(DataSource): ''' A base class for data source types, which can be mapped onto a columnar format. ''' # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) default_values = Dict(String, AnyRef, default={}, help=""" Defines the default value for each column. This is used when inserting rows into a data source, e.g. by edit tools, when a value for a given column is not explicitly provided. If a default value is missing, a tool will defer to its own configuration or will try to let the data source to infer a sensible default value. """) selection_policy = Instance(SelectionPolicy, default=InstanceDefault(UnionRenderers), help=""" An instance of a ``SelectionPolicy`` that determines how selections are set. """) def _cds_lengths_warning(_, __, data: dict[str, Any]) -> None: from ..util.warnings import BokehUserWarning, warn current_lengths = ', '.join(sorted(str((k, len(v))) for k, v in data.items())) warn( f"ColumnDataSource's columns must be of the same length. Current lengths: {current_lengths}", BokehUserWarning, )
ColumnarDataSource
python
py-pdf__pypdf
pypdf/generic/_base.py
{ "start": 26930, "end": 31862 }
class ____(str, PdfObject): # noqa: SLOT000 delimiter_pattern = re.compile(rb"\s+|[\(\)<>\[\]{}/%]") prefix = b"/" renumber_table: ClassVar[dict[str, bytes]] = { **{chr(i): f"#{i:02X}".encode() for i in b"#()<>[]{}/%"}, **{chr(i): f"#{i:02X}".encode() for i in range(33)}, } def clone( self, pdf_dest: Any, force_duplicate: bool = False, ignore_fields: Optional[Sequence[Union[str, int]]] = (), ) -> "NameObject": """Clone object into pdf_dest.""" return cast( "NameObject", self._reference_clone(NameObject(self), pdf_dest, force_duplicate), ) def hash_bin(self) -> int: """ Used to detect modified object. Returns: Hash considering type and value. """ return hash((self.__class__, self)) def write_to_stream( self, stream: StreamType, encryption_key: Union[None, str, bytes] = None ) -> None: if encryption_key is not None: # deprecated deprecation_no_replacement( "the encryption_key parameter of write_to_stream", "5.0.0" ) stream.write(self.renumber()) def renumber(self) -> bytes: out = self[0].encode("utf-8") if out != b"/": deprecation_no_replacement( f"Incorrect first char in NameObject, should start with '/': ({self})", "5.0.0", ) for c in self[1:]: if c > "~": for x in c.encode("utf-8"): out += f"#{x:02X}".encode() else: try: out += self.renumber_table[c] except KeyError: out += c.encode("utf-8") return out def _sanitize(self) -> "NameObject": """ Sanitize the NameObject's name to be a valid PDF name part (alphanumeric, underscore, hyphen). The _sanitize method replaces spaces and any non-alphanumeric/non-underscore/non-hyphen with underscores. Returns: NameObject with sanitized name. """ name = str(self).removeprefix("/") name = re.sub(r"\ ", "_", name) name = re.sub(r"[^a-zA-Z0-9_-]", "_", name) return NameObject("/" + name) @classproperty def surfix(cls) -> bytes: # noqa: N805 deprecation_with_replacement("surfix", "prefix", "5.0.0") return b"/" @staticmethod def unnumber(sin: bytes) -> bytes: i = sin.find(b"#", 0) while i >= 0: try: sin = sin[:i] + unhexlify(sin[i + 1 : i + 3]) + sin[i + 3 :] i = sin.find(b"#", i + 1) except ValueError: # if the 2 characters after # can not be converted to hex # we change nothing and carry on i = i + 1 return sin CHARSETS = ("utf-8", "gbk", "latin1") @staticmethod def read_from_stream(stream: StreamType, pdf: Any) -> "NameObject": # PdfReader name = stream.read(1) if name != NameObject.prefix: raise PdfReadError("Name read error") name += read_until_regex(stream, NameObject.delimiter_pattern) try: # Name objects should represent irregular characters # with a '#' followed by the symbol's hex number name = NameObject.unnumber(name) for enc in NameObject.CHARSETS: try: ret = name.decode(enc) return NameObject(ret) except Exception: pass raise UnicodeDecodeError("", name, 0, 0, "Code Not Found") except (UnicodeEncodeError, UnicodeDecodeError) as e: if not pdf.strict: logger_warning( f"Illegal character in NameObject ({name!r}), " "you may need to adjust NameObject.CHARSETS", __name__, ) return NameObject(name.decode("charmap")) raise PdfReadError( f"Illegal character in NameObject ({name!r}). " "You may need to adjust NameObject.CHARSETS.", ) from e def encode_pdfdocencoding(unicode_string: str) -> bytes: try: return bytes([_pdfdoc_encoding_rev[k] for k in unicode_string]) except KeyError: raise UnicodeEncodeError( "pdfdocencoding", unicode_string, -1, -1, "does not exist in translation table", ) def is_null_or_none(x: Any) -> TypeGuard[Union[None, NullObject, IndirectObject]]: """ Returns: True if x is None or NullObject. """ return x is None or ( isinstance(x, PdfObject) and (x.get_object() is None or isinstance(x.get_object(), NullObject)) )
NameObject
python
mlflow__mlflow
mlflow/tracking/request_header/abstract_request_header_provider.py
{ "start": 115, "end": 1061 }
class ____: """ Abstract base class for specifying custom request headers to add to outgoing requests (e.g. request headers specifying the environment from which mlflow is running). When a request is sent, MLflow will iterate through all registered RequestHeaderProviders. For each provider where ``in_context`` returns ``True``, MLflow calls the ``request_headers`` method on the provider to compute request headers. All resulting request headers will then be merged together and sent with the request. """ __metaclass__ = ABCMeta @abstractmethod def in_context(self): """Determine if MLflow is running in this context. Returns: bool indicating if in this context. """ @abstractmethod def request_headers(self): """Generate context-specific request headers. Returns: dict of request headers. """
RequestHeaderProvider
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 971, "end": 1042 }
class ____(TypedDict): collection: str tenant: str
PermissionData
python
gevent__gevent
src/gevent/tests/test__threading_2.py
{ "start": 1534, "end": 1773 }
class ____(object): # A trivial mutable counter. def __init__(self): self.value = 0 def inc(self): self.value += 1 def dec(self): self.value -= 1 def get(self): return self.value
Counter
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 481470, "end": 483736 }
class ____(VegaLiteSchema): """ ImputeParams schema wrapper. Parameters ---------- frame : Sequence[float, None] A frame specification as a two-element array used to control the window over which the specified method is applied. The array entries should either be a number indicating the offset from the current data object, or null to indicate unbounded rows preceding or following the current data object. For example, the value ``[-5, 5]`` indicates that the window should include five objects preceding and five objects following the current object. **Default value:**: ``[null, null]`` indicating that the window includes all objects. keyvals : dict, Sequence[Any], :class:`ImputeSequence` Defines the key values that should be considered for imputation. An array of key values or an object defining a `number sequence <https://vega.github.io/vega-lite/docs/impute.html#sequence-def>`__. If provided, this will be used in addition to the key values observed within the input data. If not provided, the values will be derived from all unique values of the ``key`` field. For ``impute`` in ``encoding``, the key field is the x-field if the y-field is imputed, or vice versa. If there is no impute grouping, this property *must* be specified. method : :class:`ImputeMethod`, Literal['value', 'median', 'max', 'min', 'mean'] The imputation method to use for the field value of imputed data objects. One of ``"value"``, ``"mean"``, ``"median"``, ``"max"`` or ``"min"``. **Default value:** ``"value"`` value : Any The field value to use when the imputation ``method`` is ``"value"``. """ _schema = {"$ref": "#/definitions/ImputeParams"} def __init__( self, frame: Optional[Sequence[float | None]] = Undefined, keyvals: Optional[SchemaBase | Sequence[Any] | Map] = Undefined, method: Optional[SchemaBase | ImputeMethod_T] = Undefined, value: Optional[Any] = Undefined, **kwds, ): super().__init__( frame=frame, keyvals=keyvals, method=method, value=value, **kwds )
ImputeParams
python
realpython__materials
python-guitar-synthesizer/source_code_final/src/tablature/models.py
{ "start": 1423, "end": 1927 }
class ____(BaseModel): url: Optional[HttpUrl] = None weight: Optional[NonNegativeFloat] = 1.0 instrument: Instrument tablature: Tablature @model_validator(mode="after") def check_frets(self) -> Self: num_strings = len(self.instrument.tuning) for measure in self.tablature.measures: for notes in measure.notes: if len(notes.frets) != num_strings: raise ValueError("Incorrect number of frets") return self
Track
python
plotly__plotly.py
plotly/graph_objs/streamtube/_starts.py
{ "start": 233, "end": 5446 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "streamtube" _path_str = "streamtube.starts" _valid_props = {"x", "xsrc", "y", "ysrc", "z", "zsrc"} @property def x(self): """ Sets the x components of the starting position of the streamtubes The 'x' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["x"] @x.setter def x(self, val): self["x"] = val @property def xsrc(self): """ Sets the source reference on Chart Studio Cloud for `x`. The 'xsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["xsrc"] @xsrc.setter def xsrc(self, val): self["xsrc"] = val @property def y(self): """ Sets the y components of the starting position of the streamtubes The 'y' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["y"] @y.setter def y(self, val): self["y"] = val @property def ysrc(self): """ Sets the source reference on Chart Studio Cloud for `y`. The 'ysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ysrc"] @ysrc.setter def ysrc(self, val): self["ysrc"] = val @property def z(self): """ Sets the z components of the starting position of the streamtubes The 'z' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["z"] @z.setter def z(self, val): self["z"] = val @property def zsrc(self): """ Sets the source reference on Chart Studio Cloud for `z`. The 'zsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["zsrc"] @zsrc.setter def zsrc(self, val): self["zsrc"] = val @property def _prop_descriptions(self): return """\ x Sets the x components of the starting position of the streamtubes xsrc Sets the source reference on Chart Studio Cloud for `x`. y Sets the y components of the starting position of the streamtubes ysrc Sets the source reference on Chart Studio Cloud for `y`. z Sets the z components of the starting position of the streamtubes zsrc Sets the source reference on Chart Studio Cloud for `z`. """ def __init__( self, arg=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, **kwargs, ): """ Construct a new Starts object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.streamtube.Starts` x Sets the x components of the starting position of the streamtubes xsrc Sets the source reference on Chart Studio Cloud for `x`. y Sets the y components of the starting position of the streamtubes ysrc Sets the source reference on Chart Studio Cloud for `y`. z Sets the z components of the starting position of the streamtubes zsrc Sets the source reference on Chart Studio Cloud for `z`. Returns ------- Starts """ super().__init__("starts") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.streamtube.Starts constructor must be a dict or an instance of :class:`plotly.graph_objs.streamtube.Starts`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("x", arg, x) self._set_property("xsrc", arg, xsrc) self._set_property("y", arg, y) self._set_property("ysrc", arg, ysrc) self._set_property("z", arg, z) self._set_property("zsrc", arg, zsrc) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Starts
python
kamyu104__LeetCode-Solutions
Python/minimum-cost-to-make-array-equal.py
{ "start": 1627, "end": 2486 }
class ____(object): def minCost(self, nums, cost): """ :type nums: List[int] :type cost: List[int] :rtype: int """ idxs = range(len(nums)) idxs.sort(key=lambda x: nums[x]) prefix = [0]*(len(cost)+1) left = 0 for i in xrange(len(cost)): if i-1 >= 0: left += prefix[i]*(nums[idxs[i]]-nums[idxs[i-1]]) prefix[i+1] = prefix[i]+cost[idxs[i]] result = float("inf") suffix = right = 0 for i in reversed(xrange(len(cost))): if i+1 < len(idxs): right += suffix*(nums[idxs[i+1]]-nums[idxs[i]]) result = min(result, left+right) if i-1 >= 0: left -= prefix[i]*(nums[idxs[i]]-nums[idxs[i-1]]) suffix += cost[idxs[i]] return result
Solution3
python
py-pdf__pypdf
pypdf/generic/_base.py
{ "start": 17993, "end": 19621 }
class ____(int, PdfObject): NumberPattern = re.compile(b"[^+-.0-9]") def __new__(cls, value: Any) -> "NumberObject": try: return int.__new__(cls, int(value)) except ValueError: logger_warning(f"NumberObject({value}) invalid; use 0 instead", __name__) return int.__new__(cls, 0) def clone( self, pdf_dest: Any, force_duplicate: bool = False, ignore_fields: Optional[Sequence[Union[str, int]]] = (), ) -> "NumberObject": """Clone object into pdf_dest.""" return cast( "NumberObject", self._reference_clone(NumberObject(self), pdf_dest, force_duplicate), ) def hash_bin(self) -> int: """ Used to detect modified object. Returns: Hash considering type and value. """ return hash((self.__class__, self.as_numeric())) def as_numeric(self) -> int: return int(repr(self).encode("utf8")) def write_to_stream( self, stream: StreamType, encryption_key: Union[None, str, bytes] = None ) -> None: if encryption_key is not None: # deprecated deprecation_no_replacement( "the encryption_key parameter of write_to_stream", "5.0.0" ) stream.write(repr(self).encode("utf8")) @staticmethod def read_from_stream(stream: StreamType) -> Union["NumberObject", "FloatObject"]: num = read_until_regex(stream, NumberObject.NumberPattern) if b"." in num: return FloatObject(num) return NumberObject(num)
NumberObject
python
encode__httpx
httpx/_transports/default.py
{ "start": 9161, "end": 13984 }
class ____(AsyncBaseTransport): def __init__( self, verify: ssl.SSLContext | str | bool = True, cert: CertTypes | None = None, trust_env: bool = True, http1: bool = True, http2: bool = False, limits: Limits = DEFAULT_LIMITS, proxy: ProxyTypes | None = None, uds: str | None = None, local_address: str | None = None, retries: int = 0, socket_options: typing.Iterable[SOCKET_OPTION] | None = None, ) -> None: import httpcore proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) if proxy is None: self._pool = httpcore.AsyncConnectionPool( ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, uds=uds, local_address=local_address, retries=retries, socket_options=socket_options, ) elif proxy.url.scheme in ("http", "https"): self._pool = httpcore.AsyncHTTPProxy( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, port=proxy.url.port, target=proxy.url.raw_path, ), proxy_auth=proxy.raw_auth, proxy_headers=proxy.headers.raw, proxy_ssl_context=proxy.ssl_context, ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, socket_options=socket_options, ) elif proxy.url.scheme in ("socks5", "socks5h"): try: import socksio # noqa except ImportError: # pragma: no cover raise ImportError( "Using SOCKS proxy, but the 'socksio' package is not installed. " "Make sure to install httpx using `pip install httpx[socks]`." ) from None self._pool = httpcore.AsyncSOCKSProxy( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, port=proxy.url.port, target=proxy.url.raw_path, ), proxy_auth=proxy.raw_auth, ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, keepalive_expiry=limits.keepalive_expiry, http1=http1, http2=http2, ) else: # pragma: no cover raise ValueError( "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," f" but got {proxy.url.scheme!r}." ) async def __aenter__(self: A) -> A: # Use generics for subclass support. await self._pool.__aenter__() return self async def __aexit__( self, exc_type: type[BaseException] | None = None, exc_value: BaseException | None = None, traceback: TracebackType | None = None, ) -> None: with map_httpcore_exceptions(): await self._pool.__aexit__(exc_type, exc_value, traceback) async def handle_async_request( self, request: Request, ) -> Response: assert isinstance(request.stream, AsyncByteStream) import httpcore req = httpcore.Request( method=request.method, url=httpcore.URL( scheme=request.url.raw_scheme, host=request.url.raw_host, port=request.url.port, target=request.url.raw_path, ), headers=request.headers.raw, content=request.stream, extensions=request.extensions, ) with map_httpcore_exceptions(): resp = await self._pool.handle_async_request(req) assert isinstance(resp.stream, typing.AsyncIterable) return Response( status_code=resp.status, headers=resp.headers, stream=AsyncResponseStream(resp.stream), extensions=resp.extensions, ) async def aclose(self) -> None: await self._pool.aclose()
AsyncHTTPTransport
python
tensorflow__tensorflow
tensorflow/python/ops/init_ops_v2.py
{ "start": 5633, "end": 7359 }
class ____(Initializer): """Initializer that generates tensors initialized to 1. Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized. Examples: >>> def make_variables(k, initializer): ... return (tf.Variable(initializer(shape=[k], dtype=tf.float32)), ... tf.Variable(initializer(shape=[k, k], dtype=tf.float32))) >>> v1, v2 = make_variables(3, tf.ones_initializer()) >>> v1 <tf.Variable ... shape=(3,) ... numpy=array([1., 1., 1.], dtype=float32)> >>> v2 <tf.Variable ... shape=(3, 3) ... numpy= array([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], dtype=float32)> >>> make_variables(4, tf.random_uniform_initializer(minval=-1., maxval=1.)) (<tf.Variable...shape=(4,) dtype=float32...>, <tf.Variable...shape=(4, 4) ... """ def __call__(self, shape, dtype=dtypes.float32, **kwargs): """Returns a tensor object initialized as specified by the initializer. Args: shape: Shape of the tensor. dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are supported. **kwargs: Additional keyword arguments. Raises: ValuesError: If the dtype is not numeric or boolean. """ self._validate_kwargs(kwargs) dtype = dtypes.as_dtype(dtype) if not dtype.is_numpy_compatible or dtype == dtypes.string: raise ValueError("Argument `dtype` expected to be numeric or boolean. " f"Received {dtype}.") if _PARTITION_SHAPE in kwargs: shape = kwargs[_PARTITION_SHAPE] return array_ops.ones(shape, dtype) @tf_export("constant_initializer", v1=[])
Ones
python
mlflow__mlflow
mlflow/server/graphql/autogenerated_graphql_schema.py
{ "start": 5859, "end": 6250 }
class ____(graphene.ObjectType): run_id = graphene.String() run_uuid = graphene.String() run_name = graphene.String() experiment_id = graphene.String() user_id = graphene.String() status = graphene.Field(MlflowRunStatus) start_time = LongString() end_time = LongString() artifact_uri = graphene.String() lifecycle_stage = graphene.String()
MlflowRunInfo
python
GoogleCloudPlatform__python-docs-samples
logging/redaction/log_redaction.py
{ "start": 1048, "end": 1229 }
class ____(DoFn): """Convert PubSub message payload to UTF-8 and return as JSON""" def process(self, element): yield json.loads(element.decode("utf-8"))
PayloadAsJson
python
kamyu104__LeetCode-Solutions
Python/count-nice-pairs-in-an-array.py
{ "start": 72, "end": 611 }
class ____(object): def countNicePairs(self, nums): """ :type nums: List[int] :rtype: int """ MOD = 10**9 + 7 def rev(x): result = 0 while x: x, r = divmod(x, 10) result = result*10+r return result result = 0 lookup = collections.defaultdict(int) for num in nums: result = (result + lookup[num-rev(num)])%MOD lookup[num-rev(num)] += 1 return result
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/namedTuple6.py
{ "start": 172, "end": 662 }
class ____(NamedTuple): val1: str val2: int nt1 = NT1("x", 0) # This should generate an error. nt1.val1 = "" # This should generate an error. nt1[0] = "" # This should generate an error. del nt1.val1 # This should generate an error. del nt1[0] NT2 = NamedTuple("NT2", [("val1", str), ("val2", int)]) nt2 = NT2("x", 0) # This should generate an error. nt2.val2 = 3 NT3 = namedtuple("NT3", ["val1", "val2"]) nt3 = NT3("x", 0) # This should generate an error. nt3.val1 = ""
NT1
python
pypa__setuptools
setuptools/_vendor/importlib_metadata/__init__.py
{ "start": 25464, "end": 26717 }
class ____: """ A prepared search query for metadata on a possibly-named package. Pre-calculates the normalization to prevent repeated operations. >>> none = Prepared(None) >>> none.normalized >>> none.legacy_normalized >>> bool(none) False >>> sample = Prepared('Sample__Pkg-name.foo') >>> sample.normalized 'sample_pkg_name_foo' >>> sample.legacy_normalized 'sample__pkg_name.foo' >>> bool(sample) True """ normalized = None legacy_normalized = None def __init__(self, name: Optional[str]): self.name = name if name is None: return self.normalized = self.normalize(name) self.legacy_normalized = self.legacy_normalize(name) @staticmethod def normalize(name): """ PEP 503 normalization plus dashes as underscores. """ return re.sub(r"[-_.]+", "-", name).lower().replace('-', '_') @staticmethod def legacy_normalize(name): """ Normalize the package name as found in the convention in older packaging tools versions and specs. """ return name.lower().replace('-', '_') def __bool__(self): return bool(self.name) @install
Prepared
python
huggingface__transformers
src/transformers/models/falcon_h1/modular_falcon_h1.py
{ "start": 54956, "end": 61067 }
class ____(LlamaForCausalLM): 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[FalconHybridMambaAttentionDynamicCache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs, ) -> Union[tuple, CausalLMOutputWithPast]: r""" Example: ```python >>> from transformers import AutoTokenizer, FalconH1ForCausalLM >>> model = FalconH1ForCausalLM.from_pretrained("...") >>> tokenizer = AutoTokenizer.from_pretrained("...") >>> 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_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = 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_attentions=output_attentions, output_hidden_states=output_hidden_states, cache_position=cache_position, **kwargs, ) hidden_states = outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) * self.model.lm_head_multiplier loss = None if labels is not None: loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs) return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, cache_position=None, position_ids=None, use_cache=True, **kwargs, ): # Overwritten -- has a unique cache type, `FalconHybridMambaAttentionDynamicCache` empty_past_kv = past_key_values is None # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens # Exception 1: when passing input_embeds, input_ids may be missing entries # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case. # (we can't check exception 3 while compiling) if not empty_past_kv: if ( inputs_embeds is not None # Exception 1 or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3 ): input_ids = input_ids[:, -cache_position.shape[0] :] elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2) input_ids = input_ids[:, cache_position] else: past_key_values = FalconHybridMambaAttentionDynamicCache( self.config, input_ids.shape[0], self.dtype, devices=[ self.model.layers[i].mamba.conv1d.weight.device for i in range(self.config.num_hidden_layers) ], ) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if not empty_past_kv: position_ids = position_ids[:, -input_ids.shape[1] :] # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and empty_past_kv: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "use_cache": use_cache, "attention_mask": attention_mask, "logits_to_keep": self.config.num_logits_to_keep, "cache_position": cache_position, } ) # Forward ALL kwargs that are uninitialized (e.g. `use_cache`). for key, value in kwargs.items(): if key not in model_inputs: model_inputs[key] = value return model_inputs __all__ = ["FalconH1Model", "FalconH1ForCausalLM", "FalconH1PreTrainedModel"]
FalconH1ForCausalLM
python
cython__cython
Cython/Compiler/Nodes.py
{ "start": 359147, "end": 368025 }
class ____(Node): # Part of try ... except statement. # # pattern [ExprNode] # target ExprNode or None # body StatNode # excinfo_target TupleNode(3*ResultRefNode) or None optional target for exception info (not owned here!) # match_flag string result of exception match # exc_value ExcValueNode used internally # function_name string qualified name of enclosing function # exc_vars (string * 3) local exception variables # is_except_as bool Py3-style "except ... as xyz" # excinfo_target is never set by the parser, but can be set by a transform # in order to extract more extensive information about the exception as a # sys.exc_info()-style tuple into a target variable child_attrs = ["pattern", "target", "body", "exc_value"] exc_value = None excinfo_target = None is_except_as = False def analyse_declarations(self, env): if self.target: self.target.analyse_target_declaration(env) from .ExprNodes import ExcValueNode self.exc_value = ExcValueNode(self.pos, self.infer_exception_type(env)) self.body.analyse_declarations(env) def analyse_expressions(self, env): self.function_name = env.qualified_name if self.pattern: # normalise/unpack self.pattern into a list for i, pattern in enumerate(self.pattern): pattern = pattern.analyse_expressions(env) self.pattern[i] = pattern.coerce_to_pyobject(env) if self.target: self.target = self.target.analyse_target_expression(env, self.exc_value) self.body = self.body.analyse_expressions(env) return self def infer_exception_type(self, env): if self.pattern and len(self.pattern) == 1: # Infer target type for simple "except XyzError as exc". pattern = self.pattern[0] if pattern.is_name: entry = env.lookup(pattern.name) if entry and entry.is_type and entry.scope.is_builtin_scope: return entry.type return Builtin.builtin_types["BaseException"] def body_may_need_exception(self): from .ParseTreeTransforms import HasNoExceptionHandlingVisitor tree_has_no_exceptions = HasNoExceptionHandlingVisitor() return not tree_has_no_exceptions(self.body) def generate_handling_code(self, code, end_label): code.mark_pos(self.pos) if self.pattern: has_non_literals = not all( pattern.is_literal or pattern.is_simple() and not pattern.result_in_temp() for pattern in self.pattern) if has_non_literals: # For non-trivial exception check expressions, hide the live exception from C-API calls. exc_vars = [code.funcstate.allocate_temp(py_object_type, manage_ref=True) for _ in range(3)] code.globalstate.use_utility_code(UtilityCode.load_cached("PyErrFetchRestore", "Exceptions.c")) code.putln("__Pyx_ErrFetch(&%s, &%s, &%s);" % tuple(exc_vars)) exc_type = exc_vars[0] else: exc_vars = exc_type = None for pattern in self.pattern: pattern.generate_evaluation_code(code) patterns = [pattern.py_result() for pattern in self.pattern] exc_tests = [] if exc_type: code.globalstate.use_utility_code( UtilityCode.load_cached("FastTypeChecks", "ModuleSetupCode.c")) if len(patterns) == 2: exc_tests.append("__Pyx_PyErr_GivenExceptionMatches2(%s, %s, %s)" % ( exc_type, patterns[0], patterns[1], )) else: exc_tests.extend( "__Pyx_PyErr_GivenExceptionMatches(%s, %s)" % (exc_type, pattern) for pattern in patterns ) elif len(patterns) == 2: code.globalstate.use_utility_code( UtilityCode.load_cached("FastTypeChecks", "ModuleSetupCode.c")) exc_tests.append("__Pyx_PyErr_ExceptionMatches2(%s, %s)" % ( patterns[0], patterns[1], )) else: code.globalstate.use_utility_code( UtilityCode.load_cached("PyErrExceptionMatches", "Exceptions.c")) exc_tests.extend( "__Pyx_PyErr_ExceptionMatches(%s)" % pattern for pattern in patterns ) match_flag = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False) code.putln("%s = %s;" % (match_flag, ' || '.join(exc_tests))) for pattern in self.pattern: pattern.generate_disposal_code(code) pattern.free_temps(code) if exc_vars: code.putln("__Pyx_ErrRestore(%s, %s, %s);" % tuple(exc_vars)) code.putln(' '.join(["%s = 0;" % var for var in exc_vars])) for temp in exc_vars: code.funcstate.release_temp(temp) code.putln( "if (%s) {" % match_flag) code.funcstate.release_temp(match_flag) else: code.putln("/*except:*/ {") tracing = code.is_tracing() needs_exception = ( self.target is not None or self.excinfo_target is not None or self.body_may_need_exception() ) if needs_exception or tracing: code.put_add_traceback(self.function_name) if tracing: code.put_trace_exception_handled(self.pos) if needs_exception: # We always have to fetch the exception value even if # there is no target, because this also normalises the # exception and stores it in the thread state. code.globalstate.use_utility_code(get_exception_utility_code) exc_vars = [code.funcstate.allocate_temp(py_object_type, manage_ref=True) for _ in range(3)] exc_args = "&%s, &%s, &%s" % tuple(exc_vars) code.putln("if (__Pyx_GetException(%s) < 0) %s" % ( exc_args, code.error_goto(self.pos))) for var in exc_vars: code.put_xgotref(var, py_object_type) else: code.globalstate.use_utility_code(UtilityCode.load_cached("PyErrFetchRestore", "Exceptions.c")) code.putln("__Pyx_ErrRestore(0,0,0);") if tracing: code.putln("__Pyx_TraceExceptionDone();") if self.target: self.exc_value.set_var(exc_vars[1]) self.exc_value.generate_evaluation_code(code) self.target.generate_assignment_code(self.exc_value, code) if self.excinfo_target is not None: for tempvar, node in zip(exc_vars, self.excinfo_target.args): node.set_var(tempvar) old_loop_labels = code.new_loop_labels("except_") if needs_exception: old_exc_vars = code.funcstate.exc_vars code.funcstate.exc_vars = exc_vars self.body.generate_execution_code(code) if needs_exception: code.funcstate.exc_vars = old_exc_vars if not self.body.is_terminator: if needs_exception: for var in exc_vars: # FIXME: XDECREF() is needed to allow re-raising (which clears the exc_vars), # but I don't think it's the right solution. code.put_xdecref_clear(var, py_object_type) code.put_goto(end_label) if needs_exception: for _ in code.label_interceptor(code.get_loop_labels(), old_loop_labels): code.put_decref_clear(exc_vars[0], py_object_type) code.put_decref_clear(exc_vars[1], py_object_type) # Traceback may be NULL. code.put_xdecref_clear(exc_vars[2], py_object_type) for temp in exc_vars: code.funcstate.release_temp(temp) code.set_loop_labels(old_loop_labels) code.putln( "}") def generate_function_definitions(self, env, code): if self.target is not None: self.target.generate_function_definitions(env, code) self.body.generate_function_definitions(env, code) def annotate(self, code): if self.pattern: for pattern in self.pattern: pattern.annotate(code) if self.target: self.target.annotate(code) self.body.annotate(code)
ExceptClauseNode
python
pallets__werkzeug
src/werkzeug/_internal.py
{ "start": 1364, "end": 2870 }
class ____(logging.StreamHandler): # type: ignore[type-arg] """On Windows, wrap stream with Colorama for ANSI style support.""" def __init__(self) -> None: try: import colorama except ImportError: stream = None else: stream = colorama.AnsiToWin32(sys.stderr) super().__init__(stream) def _log(type: str, message: str, *args: t.Any, **kwargs: t.Any) -> None: """Log a message to the 'werkzeug' logger. The logger is created the first time it is needed. If there is no level set, it is set to :data:`logging.INFO`. If there is no handler for the logger's effective level, a :class:`logging.StreamHandler` is added. """ global _logger if _logger is None: _logger = logging.getLogger("werkzeug") if _logger.level == logging.NOTSET: _logger.setLevel(logging.INFO) if not _has_level_handler(_logger): _logger.addHandler(_ColorStreamHandler()) getattr(_logger, type)(message.rstrip(), *args, **kwargs) @t.overload def _dt_as_utc(dt: None) -> None: ... @t.overload def _dt_as_utc(dt: datetime) -> datetime: ... def _dt_as_utc(dt: datetime | None) -> datetime | None: if dt is None: return dt if dt.tzinfo is None: return dt.replace(tzinfo=timezone.utc) elif dt.tzinfo != timezone.utc: return dt.astimezone(timezone.utc) return dt _TAccessorValue = t.TypeVar("_TAccessorValue")
_ColorStreamHandler
python
scrapy__scrapy
tests/test_spider.py
{ "start": 7694, "end": 8318 }
class ____(TestSpider): spider_class = CSVFeedSpider def test_parse_rows(self): body = get_testdata("feeds", "feed-sample6.csv") response = Response("http://example.org/dummy.csv", body=body) class _CrawlSpider(self.spider_class): name = "test" delimiter = "," quotechar = "'" def parse_row(self, response, row): return row spider = _CrawlSpider() rows = list(spider.parse_rows(response)) assert rows[0] == {"id": "1", "name": "alpha", "value": "foobar"} assert len(rows) == 4
TestCSVFeedSpider
python
apache__airflow
providers/apache/kafka/src/airflow/providers/apache/kafka/operators/produce.py
{ "start": 1533, "end": 5233 }
class ____(BaseOperator): """ An operator that produces messages to a Kafka topic. Registers a producer to a kafka topic and publishes messages to the log. :param kafka_config_id: The connection object to use, defaults to "kafka_default" :param topic: The topic the producer should produce to, defaults to None :param producer_function: The function that generates key/value pairs as messages for production, defaults to None :param producer_function_args: Additional arguments to be applied to the producer callable, defaults to None :param producer_function_kwargs: Additional keyword arguments to be applied to the producer callable, defaults to None :param delivery_callback: The callback to apply after delivery(or failure) of a message, defaults to None :param synchronous: If writes to kafka should be fully synchronous, defaults to True :param poll_timeout: How long of a delay should be applied when calling poll after production to kafka, defaults to 0 :raises AirflowException: _description_ .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ProduceToTopicOperator` """ template_fields = ( "topic", "producer_function_args", "producer_function_kwargs", "kafka_config_id", ) def __init__( self, topic: str, producer_function: str | Callable[..., Any], kafka_config_id: str = "kafka_default", producer_function_args: Sequence[Any] | None = None, producer_function_kwargs: dict[Any, Any] | None = None, delivery_callback: str | None = None, synchronous: bool = True, poll_timeout: float = 0, **kwargs: Any, ) -> None: super().__init__(**kwargs) if delivery_callback: dc = import_string(delivery_callback) else: dc = acked self.kafka_config_id = kafka_config_id self.topic = topic self.producer_function = producer_function self.producer_function_args = producer_function_args or () self.producer_function_kwargs = producer_function_kwargs or {} self.delivery_callback = dc self.synchronous = synchronous self.poll_timeout = poll_timeout if not (self.topic and self.producer_function): raise AirflowException( "topic and producer_function must be provided. Got topic=" f"{self.topic} and producer_function={self.producer_function}" ) return def execute(self, context) -> None: # Get producer and callable producer = KafkaProducerHook(kafka_config_id=self.kafka_config_id).get_producer() if isinstance(self.producer_function, str): self.producer_function = import_string(self.producer_function) if self.producer_function is not None and not callable(self.producer_function): raise TypeError( f"producer_function is not a callable, got {type(self.producer_function)} instead." ) producer_callable = partial( self.producer_function, *self.producer_function_args, **self.producer_function_kwargs, ) # For each returned k/v in the callable : publish and flush if needed. for k, v in producer_callable(): producer.produce(self.topic, key=k, value=v, on_delivery=self.delivery_callback) producer.poll(self.poll_timeout) if self.synchronous: producer.flush() producer.flush()
ProduceToTopicOperator
python
tensorflow__tensorflow
tensorflow/python/data/ops/readers.py
{ "start": 5104, "end": 6673 }
class ____(dataset_ops.DatasetSource): """A `Dataset` comprising records from one or more text files.""" def __init__(self, filenames, compression_type=None, buffer_size=None, name=None): """Creates a `TextLineDataset`. Args: filenames: A `tf.string` tensor containing one or more filenames. compression_type: (Optional.) A `tf.string` scalar evaluating to one of `""` (no compression), `"ZLIB"`, or `"GZIP"`. buffer_size: (Optional.) A `tf.int64` scalar denoting the number of bytes to buffer. A value of 0 results in the default buffering values chosen based on the compression type. name: (Optional.) A name for the tf.data operation. """ self._filenames = filenames self._compression_type = convert.optional_param_to_tensor( "compression_type", compression_type, argument_default="", argument_dtype=dtypes.string) self._buffer_size = convert.optional_param_to_tensor( "buffer_size", buffer_size, argument_default=_DEFAULT_READER_BUFFER_SIZE_BYTES) self._name = name variant_tensor = gen_dataset_ops.text_line_dataset( self._filenames, self._compression_type, self._buffer_size, metadata=self._metadata.SerializeToString()) super(_TextLineDataset, self).__init__(variant_tensor) @property def element_spec(self): return tensor_spec.TensorSpec([], dtypes.string) @tf_export("data.TextLineDataset", v1=[])
_TextLineDataset
python
plotly__plotly.py
plotly/graph_objs/layout/_title.py
{ "start": 235, "end": 15391 }
class ____(_BaseLayoutHierarchyType): _parent_path_str = "layout" _path_str = "layout.title" _valid_props = { "automargin", "font", "pad", "subtitle", "text", "x", "xanchor", "xref", "y", "yanchor", "yref", } @property def automargin(self): """ Determines whether the title can automatically push the figure margins. If `yref='paper'` then the margin will expand to ensure that the title doesn’t overlap with the edges of the container. If `yref='container'` then the margins will ensure that the title doesn’t overlap with the plot area, tick labels, and axis titles. If `automargin=true` and the margins need to be expanded, then y will be set to a default 1 and yanchor will be set to an appropriate default to ensure that minimal margin space is needed. Note that when `yref='paper'`, only 1 or 0 are allowed y values. Invalid values will be reset to the default 1. The 'automargin' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["automargin"] @automargin.setter def automargin(self, val): self["automargin"] = val @property def font(self): """ Sets the title font. The 'font' property is an instance of Font that may be specified as: - An instance of :class:`plotly.graph_objs.layout.title.Font` - A dict of string/value properties that will be passed to the Font constructor Returns ------- plotly.graph_objs.layout.title.Font """ return self["font"] @font.setter def font(self, val): self["font"] = val @property def pad(self): """ Sets the padding of the title. Each padding value only applies when the corresponding `xanchor`/`yanchor` value is set accordingly. E.g. for left padding to take effect, `xanchor` must be set to "left". The same rule applies if `xanchor`/`yanchor` is determined automatically. Padding is muted if the respective anchor value is "middle*/*center". The 'pad' property is an instance of Pad that may be specified as: - An instance of :class:`plotly.graph_objs.layout.title.Pad` - A dict of string/value properties that will be passed to the Pad constructor Returns ------- plotly.graph_objs.layout.title.Pad """ return self["pad"] @pad.setter def pad(self, val): self["pad"] = val @property def subtitle(self): """ The 'subtitle' property is an instance of Subtitle that may be specified as: - An instance of :class:`plotly.graph_objs.layout.title.Subtitle` - A dict of string/value properties that will be passed to the Subtitle constructor Returns ------- plotly.graph_objs.layout.title.Subtitle """ return self["subtitle"] @subtitle.setter def subtitle(self, val): self["subtitle"] = val @property def text(self): """ Sets the plot's title. The 'text' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def x(self): """ Sets the x position with respect to `xref` in normalized coordinates from 0 (left) to 1 (right). The 'x' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["x"] @x.setter def x(self, val): self["x"] = val @property def xanchor(self): """ Sets the title's horizontal alignment with respect to its x position. "left" means that the title starts at x, "right" means that the title ends at x and "center" means that the title's center is at x. "auto" divides `xref` by three and calculates the `xanchor` value automatically based on the value of `x`. The 'xanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'left', 'center', 'right'] Returns ------- Any """ return self["xanchor"] @xanchor.setter def xanchor(self, val): self["xanchor"] = val @property def xref(self): """ Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. The 'xref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["xref"] @xref.setter def xref(self, val): self["xref"] = val @property def y(self): """ Sets the y position with respect to `yref` in normalized coordinates from 0 (bottom) to 1 (top). "auto" places the baseline of the title onto the vertical center of the top margin. The 'y' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["y"] @y.setter def y(self, val): self["y"] = val @property def yanchor(self): """ Sets the title's vertical alignment with respect to its y position. "top" means that the title's cap line is at y, "bottom" means that the title's baseline is at y and "middle" means that the title's midline is at y. "auto" divides `yref` by three and calculates the `yanchor` value automatically based on the value of `y`. The 'yanchor' property is an enumeration that may be specified as: - One of the following enumeration values: ['auto', 'top', 'middle', 'bottom'] Returns ------- Any """ return self["yanchor"] @yanchor.setter def yanchor(self, val): self["yanchor"] = val @property def yref(self): """ Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. The 'yref' property is an enumeration that may be specified as: - One of the following enumeration values: ['container', 'paper'] Returns ------- Any """ return self["yref"] @yref.setter def yref(self, val): self["yref"] = val @property def _prop_descriptions(self): return """\ automargin Determines whether the title can automatically push the figure margins. If `yref='paper'` then the margin will expand to ensure that the title doesn’t overlap with the edges of the container. If `yref='container'` then the margins will ensure that the title doesn’t overlap with the plot area, tick labels, and axis titles. If `automargin=true` and the margins need to be expanded, then y will be set to a default 1 and yanchor will be set to an appropriate default to ensure that minimal margin space is needed. Note that when `yref='paper'`, only 1 or 0 are allowed y values. Invalid values will be reset to the default 1. font Sets the title font. pad Sets the padding of the title. Each padding value only applies when the corresponding `xanchor`/`yanchor` value is set accordingly. E.g. for left padding to take effect, `xanchor` must be set to "left". The same rule applies if `xanchor`/`yanchor` is determined automatically. Padding is muted if the respective anchor value is "middle*/*center". subtitle :class:`plotly.graph_objects.layout.title.Subtitle` instance or dict with compatible properties text Sets the plot's title. x Sets the x position with respect to `xref` in normalized coordinates from 0 (left) to 1 (right). xanchor Sets the title's horizontal alignment with respect to its x position. "left" means that the title starts at x, "right" means that the title ends at x and "center" means that the title's center is at x. "auto" divides `xref` by three and calculates the `xanchor` value automatically based on the value of `x`. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` in normalized coordinates from 0 (bottom) to 1 (top). "auto" places the baseline of the title onto the vertical center of the top margin. yanchor Sets the title's vertical alignment with respect to its y position. "top" means that the title's cap line is at y, "bottom" means that the title's baseline is at y and "middle" means that the title's midline is at y. "auto" divides `yref` by three and calculates the `yanchor` value automatically based on the value of `y`. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. """ def __init__( self, arg=None, automargin=None, font=None, pad=None, subtitle=None, text=None, x=None, xanchor=None, xref=None, y=None, yanchor=None, yref=None, **kwargs, ): """ Construct a new Title object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.layout.Title` automargin Determines whether the title can automatically push the figure margins. If `yref='paper'` then the margin will expand to ensure that the title doesn’t overlap with the edges of the container. If `yref='container'` then the margins will ensure that the title doesn’t overlap with the plot area, tick labels, and axis titles. If `automargin=true` and the margins need to be expanded, then y will be set to a default 1 and yanchor will be set to an appropriate default to ensure that minimal margin space is needed. Note that when `yref='paper'`, only 1 or 0 are allowed y values. Invalid values will be reset to the default 1. font Sets the title font. pad Sets the padding of the title. Each padding value only applies when the corresponding `xanchor`/`yanchor` value is set accordingly. E.g. for left padding to take effect, `xanchor` must be set to "left". The same rule applies if `xanchor`/`yanchor` is determined automatically. Padding is muted if the respective anchor value is "middle*/*center". subtitle :class:`plotly.graph_objects.layout.title.Subtitle` instance or dict with compatible properties text Sets the plot's title. x Sets the x position with respect to `xref` in normalized coordinates from 0 (left) to 1 (right). xanchor Sets the title's horizontal alignment with respect to its x position. "left" means that the title starts at x, "right" means that the title ends at x and "center" means that the title's center is at x. "auto" divides `xref` by three and calculates the `xanchor` value automatically based on the value of `x`. xref Sets the container `x` refers to. "container" spans the entire `width` of the plot. "paper" refers to the width of the plotting area only. y Sets the y position with respect to `yref` in normalized coordinates from 0 (bottom) to 1 (top). "auto" places the baseline of the title onto the vertical center of the top margin. yanchor Sets the title's vertical alignment with respect to its y position. "top" means that the title's cap line is at y, "bottom" means that the title's baseline is at y and "middle" means that the title's midline is at y. "auto" divides `yref` by three and calculates the `yanchor` value automatically based on the value of `y`. yref Sets the container `y` refers to. "container" spans the entire `height` of the plot. "paper" refers to the height of the plotting area only. Returns ------- Title """ super().__init__("title") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.layout.Title constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.Title`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("automargin", arg, automargin) self._set_property("font", arg, font) self._set_property("pad", arg, pad) self._set_property("subtitle", arg, subtitle) self._set_property("text", arg, text) self._set_property("x", arg, x) self._set_property("xanchor", arg, xanchor) self._set_property("xref", arg, xref) self._set_property("y", arg, y) self._set_property("yanchor", arg, yanchor) self._set_property("yref", arg, yref) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Title
python
python-pillow__Pillow
src/PIL/ImageShow.py
{ "start": 9568, "end": 10106 }
class ____(Viewer): """The viewer for IPython frontends.""" def show_image(self, image: Image.Image, **options: Any) -> int: ipython_display(image) return 1 try: from IPython.display import display as ipython_display except ImportError: pass else: register(IPythonViewer) if __name__ == "__main__": if len(sys.argv) < 2: print("Syntax: python3 ImageShow.py imagefile [title]") sys.exit() with Image.open(sys.argv[1]) as im: print(show(im, *sys.argv[2:]))
IPythonViewer
python
getsentry__sentry
src/sentry/integrations/pagerduty/integration.py
{ "start": 2713, "end": 2930 }
class ____(TypedDict): name: str type: str label: str help: str addButtonText: str columnLabels: dict[str, str] columnKeys: list[str] confirmDeleteMessage: str
PagerDutyOrganizationConfig
python
google__jax
jax/_src/pallas/fuser/fusible_dtype.py
{ "start": 2527, "end": 2614 }
class ____(dtypes.extended): """Scalar dtype for fusible dtypes."""
FusibleElementDType
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/operator1.py
{ "start": 1788, "end": 1909 }
class ____: def __add__(self, other: object) -> NoReturn: ... f = F() + "" reveal_type(f, expected_text="NoReturn")
F
python
ray-project__ray
release/llm_tests/benchmark/configs.py
{ "start": 253, "end": 378 }
class ____(str, Enum): CONSTANT = "constant" UNIFORM = "uniform" EXPONENTIAL = "exponential"
TokensDistributionType
python
openai__openai-python
src/openai/types/responses/response_input_item.py
{ "start": 3779, "end": 4528 }
class ____(BaseModel): call_id: str """The unique ID of the function tool call generated by the model.""" output: Union[str, ResponseFunctionCallOutputItemList] """Text, image, or file output of the function tool call.""" type: Literal["function_call_output"] """The type of the function tool call output. Always `function_call_output`.""" id: Optional[str] = None """The unique ID of the function tool call output. Populated when this item is returned via API. """ status: Optional[Literal["in_progress", "completed", "incomplete"]] = None """The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. """
FunctionCallOutput
python
huggingface__transformers
examples/pytorch/translation/run_translation.py
{ "start": 4255, "end": 29547 }
class ____: """ Arguments pertaining to what data we are going to input our model for training and eval. """ source_lang: str = field(default=None, metadata={"help": "Source language id for translation."}) target_lang: str = field(default=None, metadata={"help": "Target language id for translation."}) dataset_name: Optional[str] = field( default=None, metadata={"help": "The name of the dataset to use (via the datasets library)."} ) dataset_config_name: Optional[str] = field( default=None, metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) train_file: Optional[str] = field(default=None, metadata={"help": "The input training data file (a jsonlines)."}) validation_file: Optional[str] = field( default=None, metadata={ "help": "An optional input evaluation data file to evaluate the metrics (sacrebleu) on a jsonlines file." }, ) test_file: Optional[str] = field( default=None, metadata={"help": "An optional input test data file to evaluate the metrics (sacrebleu) on a jsonlines file."}, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached training and evaluation sets"} ) preprocessing_num_workers: Optional[int] = field( default=None, metadata={"help": "The number of processes to use for the preprocessing."}, ) max_source_length: Optional[int] = field( default=1024, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) max_target_length: Optional[int] = field( default=128, metadata={ "help": ( "The maximum total sequence length for target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) val_max_target_length: Optional[int] = field( default=None, metadata={ "help": ( "The maximum total sequence length for validation target text after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded. Will default to `max_target_length`. " "This argument is also used to override the ``max_length`` param of ``model.generate``, which is used " "during ``evaluate`` and ``predict``." ) }, ) pad_to_max_length: bool = field( default=False, metadata={ "help": ( "Whether to pad all samples to model maximum sentence length. " "If False, will pad the samples dynamically when batching to the maximum length in the batch. More " "efficient on GPU but very bad for TPU." ) }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) max_eval_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) }, ) max_predict_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of prediction examples to this " "value if set." ) }, ) num_beams: Optional[int] = field( default=1, metadata={ "help": ( "Number of beams to use for evaluation. This argument will be passed to ``model.generate``, " "which is used during ``evaluate`` and ``predict``." ) }, ) ignore_pad_token_for_loss: bool = field( default=True, metadata={ "help": "Whether to ignore the tokens corresponding to padded labels in the loss computation or not." }, ) source_prefix: Optional[str] = field( default=None, metadata={"help": "A prefix to add before every source text (useful for T5 models)."} ) forced_bos_token: Optional[str] = field( default=None, metadata={ "help": ( "The token to force as the first generated token after the :obj:`decoder_start_token_id`.Useful for" " multilingual models like :doc:`mBART <../model_doc/mbart>` where the first generated token needs to" " be the target language token.(Usually it is the target language token)" ) }, ) def __post_init__(self): if self.dataset_name is None and self.train_file is None and self.validation_file is None: raise ValueError("Need either a dataset name or a training/validation file.") elif self.source_lang is None or self.target_lang is None: raise ValueError("Need to specify the source language and the target language.") # accepting both json and jsonl file extensions, as # many jsonlines files actually have a .json extension valid_extensions = ["json", "jsonl"] if self.train_file is not None: extension = self.train_file.split(".")[-1] assert extension in valid_extensions, "`train_file` should be a jsonlines file." if self.validation_file is not None: extension = self.validation_file.split(".")[-1] assert extension in valid_extensions, "`validation_file` should be a jsonlines file." if self.val_max_target_length is None: self.val_max_target_length = self.max_target_length def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, Seq2SeqTrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() log_level = training_args.get_process_log_level() logger.setLevel(log_level) datasets.utils.logging.set_verbosity(log_level) transformers.utils.logging.set_verbosity(log_level) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_process_index}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " + f"distributed training: {training_args.parallel_mode.value == 'distributed'}, 16-bits training: {training_args.fp16}" ) logger.info(f"Training/evaluation parameters {training_args}") if data_args.source_prefix is None and model_args.model_name_or_path in [ "google-t5/t5-small", "google-t5/t5-base", "google-t5/t5-large", "google-t5/t5-3b", "google-t5/t5-11b", ]: logger.warning( "You're running a t5 model but didn't provide a source prefix, which is expected, e.g. with " "`--source_prefix 'translate English to German: ' `" ) # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own JSON training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For translation, only JSON files are supported, with one field named "translation" containing two keys for the # source and target languages (unless you adapt what follows). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. raw_datasets = load_dataset( data_args.dataset_name, data_args.dataset_config_name, cache_dir=model_args.cache_dir, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) else: data_files = {} if data_args.train_file is not None: data_files["train"] = data_args.train_file extension = data_args.train_file.split(".")[-1] if data_args.validation_file is not None: data_files["validation"] = data_args.validation_file extension = data_args.validation_file.split(".")[-1] if data_args.test_file is not None: data_files["test"] = data_args.test_file extension = data_args.test_file.split(".")[-1] if extension == "jsonl": builder_name = "json" # the "json" builder reads both .json and .jsonl files else: builder_name = extension # e.g. "parquet" raw_datasets = load_dataset( builder_name, data_files=data_files, cache_dir=model_args.cache_dir, token=model_args.token, ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) model = AutoModelForSeq2SeqLM.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=model_args.token, trust_remote_code=model_args.trust_remote_code, ) # We resize the embeddings only when necessary to avoid index errors. If you are creating a model from scratch # on a small vocab and want a smaller embedding size, remove this test. embedding_size = model.get_input_embeddings().weight.shape[0] if len(tokenizer) > embedding_size: model.resize_token_embeddings(len(tokenizer)) # Set decoder_start_token_id if model.config.decoder_start_token_id is None and isinstance( tokenizer, (MBartTokenizer, MBartTokenizerFast, SentencePieceBackend) ): if isinstance(tokenizer, MBartTokenizer): model.config.decoder_start_token_id = tokenizer.lang_code_to_id[data_args.target_lang] else: model.config.decoder_start_token_id = tokenizer.convert_tokens_to_ids(data_args.target_lang) if model.config.decoder_start_token_id is None: raise ValueError("Make sure that `config.decoder_start_token_id` is correctly defined") prefix = data_args.source_prefix if data_args.source_prefix is not None else "" # Preprocessing the datasets. # We need to tokenize inputs and targets. if training_args.do_train: column_names = raw_datasets["train"].column_names elif training_args.do_eval: column_names = raw_datasets["validation"].column_names elif training_args.do_predict: column_names = raw_datasets["test"].column_names else: logger.info("There is nothing to do. Please pass `do_train`, `do_eval` and/or `do_predict`.") return # For translation we set the codes of our source and target languages (only useful for mBART, the others will # ignore those attributes). if isinstance(tokenizer, tuple(MULTILINGUAL_TOKENIZERS)): assert data_args.target_lang is not None and data_args.source_lang is not None, ( f"{tokenizer.__class__.__name__} is a multilingual tokenizer which requires --source_lang and " "--target_lang arguments." ) tokenizer.src_lang = data_args.source_lang tokenizer.tgt_lang = data_args.target_lang # For multilingual translation models like mBART-50 and M2M100 we need to force the target language token # as the first generated token. We ask the user to explicitly provide this as --forced_bos_token argument. forced_bos_token_id = ( tokenizer.lang_code_to_id[data_args.forced_bos_token] if data_args.forced_bos_token is not None else None ) model.config.forced_bos_token_id = forced_bos_token_id # Get the language codes for input/target. source_lang = data_args.source_lang.split("_")[0] target_lang = data_args.target_lang.split("_")[0] # Check the whether the source target length fits in the model, if it has absolute positional embeddings if ( hasattr(model.config, "max_position_embeddings") and not hasattr(model.config, "relative_attention_max_distance") and model.config.max_position_embeddings < data_args.max_source_length ): raise ValueError( f"`--max_source_length` is set to {data_args.max_source_length}, but the model only has" f" {model.config.max_position_embeddings} position encodings. Consider either reducing" f" `--max_source_length` to {model.config.max_position_embeddings} or using a model with larger position " "embeddings" ) # Temporarily set max_target_length for training. max_target_length = data_args.max_target_length padding = "max_length" if data_args.pad_to_max_length else False if training_args.label_smoothing_factor > 0 and not hasattr(model, "prepare_decoder_input_ids_from_labels"): logger.warning( "label_smoothing is enabled but the `prepare_decoder_input_ids_from_labels` method is not defined for " f"`{model.__class__.__name__}`. This will lead to loss being calculated twice and will take up more memory" ) def preprocess_function(examples): inputs = [ex[source_lang] for ex in examples["translation"]] targets = [ex[target_lang] for ex in examples["translation"]] inputs = [prefix + inp for inp in inputs] model_inputs = tokenizer(inputs, max_length=data_args.max_source_length, padding=padding, truncation=True) # Tokenize targets with the `text_target` keyword argument labels = tokenizer(text_target=targets, max_length=max_target_length, padding=padding, truncation=True) # If we are padding here, replace all tokenizer.pad_token_id in the labels by -100 when we want to ignore # padding in the loss. if padding == "max_length" and data_args.ignore_pad_token_for_loss: labels["input_ids"] = [ [(l if l != tokenizer.pad_token_id else -100) for l in label] for label in labels["input_ids"] ] model_inputs["labels"] = labels["input_ids"] return model_inputs if training_args.do_train: if "train" not in raw_datasets: raise ValueError("--do_train requires a train dataset") train_dataset = raw_datasets["train"] if data_args.max_train_samples is not None: max_train_samples = min(len(train_dataset), data_args.max_train_samples) train_dataset = train_dataset.select(range(max_train_samples)) with training_args.main_process_first(desc="train dataset map pre-processing"): train_dataset = train_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on train dataset", ) if training_args.do_eval: max_target_length = data_args.val_max_target_length if "validation" not in raw_datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = raw_datasets["validation"] if data_args.max_eval_samples is not None: max_eval_samples = min(len(eval_dataset), data_args.max_eval_samples) eval_dataset = eval_dataset.select(range(max_eval_samples)) with training_args.main_process_first(desc="validation dataset map pre-processing"): eval_dataset = eval_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on validation dataset", ) if training_args.do_predict: max_target_length = data_args.val_max_target_length if "test" not in raw_datasets: raise ValueError("--do_predict requires a test dataset") predict_dataset = raw_datasets["test"] if data_args.max_predict_samples is not None: max_predict_samples = min(len(predict_dataset), data_args.max_predict_samples) predict_dataset = predict_dataset.select(range(max_predict_samples)) with training_args.main_process_first(desc="prediction dataset map pre-processing"): predict_dataset = predict_dataset.map( preprocess_function, batched=True, num_proc=data_args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not data_args.overwrite_cache, desc="Running tokenizer on prediction dataset", ) # Data collator label_pad_token_id = -100 if data_args.ignore_pad_token_for_loss else tokenizer.pad_token_id if data_args.pad_to_max_length: data_collator = default_data_collator else: data_collator = DataCollatorForSeq2Seq( tokenizer, model=model, label_pad_token_id=label_pad_token_id, pad_to_multiple_of=8 if training_args.fp16 else None, ) # Metric metric = evaluate.load("sacrebleu", cache_dir=model_args.cache_dir) def postprocess_text(preds, labels): preds = [pred.strip() for pred in preds] labels = [[label.strip()] for label in labels] return preds, labels def compute_metrics(eval_preds): preds, labels = eval_preds if isinstance(preds, tuple): preds = preds[0] # Replace -100s used for padding as we can't decode them preds = np.where(preds != -100, preds, tokenizer.pad_token_id) decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True) labels = np.where(labels != -100, labels, tokenizer.pad_token_id) decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True) # Some simple post-processing decoded_preds, decoded_labels = postprocess_text(decoded_preds, decoded_labels) result = metric.compute(predictions=decoded_preds, references=decoded_labels) result = {"bleu": result["score"]} prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in preds] result["gen_len"] = np.mean(prediction_lens) result = {k: round(v, 4) for k, v in result.items()} return result # Initialize our Trainer trainer = Seq2SeqTrainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, processing_class=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics if training_args.predict_with_generate else None, ) # Training if training_args.do_train: checkpoint = None if training_args.resume_from_checkpoint is not None: checkpoint = training_args.resume_from_checkpoint train_result = trainer.train(resume_from_checkpoint=checkpoint) trainer.save_model() # Saves the tokenizer too for easy upload metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation results = {} max_length = ( training_args.generation_max_length if training_args.generation_max_length is not None else data_args.val_max_target_length ) num_beams = data_args.num_beams if data_args.num_beams is not None else training_args.generation_num_beams if training_args.do_eval: logger.info("*** Evaluate ***") metrics = trainer.evaluate(max_length=max_length, num_beams=num_beams, metric_key_prefix="eval") max_eval_samples = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(eval_dataset) metrics["eval_samples"] = min(max_eval_samples, len(eval_dataset)) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) if training_args.do_predict: logger.info("*** Predict ***") predict_results = trainer.predict( predict_dataset, metric_key_prefix="predict", max_length=max_length, num_beams=num_beams ) metrics = predict_results.metrics max_predict_samples = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(predict_dataset) ) metrics["predict_samples"] = min(max_predict_samples, len(predict_dataset)) trainer.log_metrics("predict", metrics) trainer.save_metrics("predict", metrics) if trainer.is_world_process_zero(): if training_args.predict_with_generate: predictions = predict_results.predictions predictions = np.where(predictions != -100, predictions, tokenizer.pad_token_id) predictions = tokenizer.batch_decode( predictions, skip_special_tokens=True, clean_up_tokenization_spaces=True ) predictions = [pred.strip() for pred in predictions] output_prediction_file = os.path.join(training_args.output_dir, "generated_predictions.txt") with open(output_prediction_file, "w", encoding="utf-8") as writer: writer.write("\n".join(predictions)) kwargs = {"finetuned_from": model_args.model_name_or_path, "tasks": "translation"} if data_args.dataset_name is not None: kwargs["dataset_tags"] = data_args.dataset_name if data_args.dataset_config_name is not None: kwargs["dataset_args"] = data_args.dataset_config_name kwargs["dataset"] = f"{data_args.dataset_name} {data_args.dataset_config_name}" else: kwargs["dataset"] = data_args.dataset_name languages = [l for l in [data_args.source_lang, data_args.target_lang] if l is not None] if len(languages) > 0: kwargs["language"] = languages if training_args.push_to_hub: trainer.push_to_hub(**kwargs) else: trainer.create_model_card(**kwargs) return results def _mp_fn(index): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
DataTrainingArguments
python
huggingface__transformers
src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py
{ "start": 105474, "end": 105752 }
class ____(CausalLMOutputWithPast): r""" generation_steps (`int`, *optional*) Current generation step of code predictor model. """ generation_steps: Optional[int] = None @use_kernel_forward_from_hub("RMSNorm")
Qwen3OmniMoeTalkerCodePredictorOutputWithPast
python
weaviate__weaviate-python-client
weaviate/collections/batch/base.py
{ "start": 56099, "end": 56824 }
class ____: def __init__(self, connection: ConnectionSync): self._connection = connection def get_nodes_status( self, ) -> List[Node]: try: response = executor.result(self._connection.get(path="/nodes")) except ConnectError as conn_err: raise ConnectError("Get nodes status failed due to connection error") from conn_err response_typed = _decode_json_response_dict(response, "Nodes status") assert response_typed is not None nodes = response_typed.get("nodes") if nodes is None or nodes == []: raise EmptyResponseException("Nodes status response returned empty") return cast(List[Node], nodes)
_ClusterBatch
python
realpython__materials
python-class/mro.py
{ "start": 125, "end": 189 }
class ____(A): def method(self): print("C.method()")
C
python
getsentry__sentry
src/sentry/notifications/types.py
{ "start": 7712, "end": 8068 }
class ____(StrEnum): ALL_MEMBERS = "AllMembers" ACTIVE_MEMBERS = "ActiveMembers" NO_ONE = "NoOne" FALLTHROUGH_CHOICES = [ (FallthroughChoiceType.ACTIVE_MEMBERS.value, "Recently Active Members"), (FallthroughChoiceType.ALL_MEMBERS.value, "All Project Members"), (FallthroughChoiceType.NO_ONE.value, "No One"), ]
FallthroughChoiceType
python
pypa__warehouse
warehouse/captcha/recaptcha.py
{ "start": 327, "end": 385 }
class ____(RecaptchaError): pass
MissingInputSecretError
python
walkccc__LeetCode
solutions/1937. Maximum Number of Points with Cost/1937.py
{ "start": 0, "end": 686 }
class ____: def maxPoints(self, points: list[list[int]]) -> int: n = len(points[0]) # dp[j] := the maximum number of points you can have if points[i][j] is the # most recent cell you picked dp = [0] * n for row in points: leftToRight = [0] * n runningMax = 0 for j in range(n): runningMax = max(runningMax - 1, dp[j]) leftToRight[j] = runningMax rightToLeft = [0] * n runningMax = 0 for j in range(n - 1, - 1, -1): runningMax = max(runningMax - 1, dp[j]) rightToLeft[j] = runningMax for j in range(n): dp[j] = max(leftToRight[j], rightToLeft[j]) + row[j] return max(dp)
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/classes3.py
{ "start": 1167, "end": 1397 }
class ____: def method1(self) -> str: # This should generate an error. return self.__name__ _T = TypeVar("_T") def func1(cls: type[_T]) -> _T: x1 = cls.__dict__ x2 = cls.__mro__ return cls()
NonMeta
python
kamyu104__LeetCode-Solutions
Python/longest-balanced-subarray-i.py
{ "start": 3018, "end": 3562 }
class ____(object): def longestBalanced(self, nums): """ :type nums: List[int] :rtype: int """ result = 0 for left in xrange(len(nums)): curr = 0 lookup = set() for right in xrange(left, len(nums)): if nums[right] not in lookup: lookup.add(nums[right]) curr += 1 if nums[right]&1 else -1 if curr == 0: result = max(result, right-left+1) return result
Solution2
python
crytic__slither
slither/detectors/statements/unprotected_upgradeable.py
{ "start": 2521, "end": 5404 }
class ____(AbstractDetector): ARGUMENT = "unprotected-upgrade" HELP = "Unprotected upgradeable contract" IMPACT = DetectorClassification.HIGH CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#unprotected-upgradeable-contract" WIKI_TITLE = "Unprotected upgradeable contract" WIKI_DESCRIPTION = """Detects logic contract that can be destructed.""" # region wiki_exploit_scenario WIKI_EXPLOIT_SCENARIO = """ ```solidity contract Buggy is Initializable{ address payable owner; function initialize() external initializer{ require(owner == address(0)); owner = msg.sender; } function kill() external{ require(msg.sender == owner); selfdestruct(owner); } } ``` Buggy is an upgradeable contract. Anyone can call initialize on the logic contract, and destruct the contract. """ # endregion wiki_exploit_scenario WIKI_RECOMMENDATION = ( """Add a constructor to ensure `initialize` cannot be called on the logic contract.""" ) def _detect(self) -> List[Output]: results = [] for contract in self.compilation_unit.contracts_derived: if contract.is_upgradeable: if not _has_initializing_protection(contract.constructors): functions_that_can_destroy = _can_be_destroyed(contract) if functions_that_can_destroy: initialize_functions = _initialize_functions(contract) vars_init_ = [ init.all_state_variables_written() for init in initialize_functions ] vars_init = [item for sublist in vars_init_ for item in sublist] vars_init_in_constructors_ = [ f.all_state_variables_written() for f in contract.constructors ] vars_init_in_constructors = [ item for sublist in vars_init_in_constructors_ for item in sublist ] if vars_init and (set(vars_init) - set(vars_init_in_constructors)): info: DETECTOR_INFO = [ contract, " is an upgradeable contract that does not protect its initialize functions: ", ] info += initialize_functions info += [ ". Anyone can delete the contract with: ", ] info += functions_that_can_destroy res = self.generate_result(info) results.append(res) return results
UnprotectedUpgradeable
python
coleifer__peewee
tests/libs/mock.py
{ "start": 34319, "end": 51663 }
class ____(object): attribute_name = None _active_patches = set() def __init__( self, getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ): if new_callable is not None: if new is not DEFAULT: raise ValueError( "Cannot use 'new' and 'new_callable' together" ) if autospec is not None: raise ValueError( "Cannot use 'autospec' and 'new_callable' together" ) self.getter = getter self.attribute = attribute self.new = new self.new_callable = new_callable self.spec = spec self.create = create self.has_local = False self.spec_set = spec_set self.autospec = autospec self.kwargs = kwargs self.additional_patchers = [] def copy(self): patcher = _patch( self.getter, self.attribute, self.new, self.spec, self.create, self.spec_set, self.autospec, self.new_callable, self.kwargs ) patcher.attribute_name = self.attribute_name patcher.additional_patchers = [ p.copy() for p in self.additional_patchers ] return patcher def __call__(self, func): if isinstance(func, ClassTypes): return self.decorate_class(func) return self.decorate_callable(func) def decorate_class(self, klass): for attr in dir(klass): if not attr.startswith(patch.TEST_PREFIX): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue patcher = self.copy() setattr(klass, attr, patcher(attr_value)) return klass def decorate_callable(self, func): if hasattr(func, 'patchings'): func.patchings.append(self) return func @wraps(func) def patched(*args, **keywargs): # don't use a with here (backwards compatibility with Python 2.4) extra_args = [] entered_patchers = [] # can't use try...except...finally because of Python 2.4 # compatibility exc_info = tuple() try: try: for patching in patched.patchings: arg = patching.__enter__() entered_patchers.append(patching) if patching.attribute_name is not None: keywargs.update(arg) elif patching.new is DEFAULT: extra_args.append(arg) args += tuple(extra_args) return func(*args, **keywargs) except: if (patching not in entered_patchers and _is_started(patching)): # the patcher may have been started, but an exception # raised whilst entering one of its additional_patchers entered_patchers.append(patching) # Pass the exception to __exit__ exc_info = sys.exc_info() # re-raise the exception raise finally: for patching in reversed(entered_patchers): patching.__exit__(*exc_info) patched.patchings = [self] if hasattr(func, 'func_code'): # not in Python 3 patched.compat_co_firstlineno = getattr( func, "compat_co_firstlineno", func.func_code.co_firstlineno ) return patched def get_original(self): target = self.getter() name = self.attribute original = DEFAULT local = False try: original = target.__dict__[name] except (AttributeError, KeyError): original = getattr(target, name, DEFAULT) else: local = True if not self.create and original is DEFAULT: raise AttributeError( "%s does not have the attribute %r" % (target, name) ) return original, local def __enter__(self): """Perform the patch.""" new, spec, spec_set = self.new, self.spec, self.spec_set autospec, kwargs = self.autospec, self.kwargs new_callable = self.new_callable self.target = self.getter() # normalise False to None if spec is False: spec = None if spec_set is False: spec_set = None if autospec is False: autospec = None if spec is not None and autospec is not None: raise TypeError("Can't specify spec and autospec") if ((spec is not None or autospec is not None) and spec_set not in (True, None)): raise TypeError("Can't provide explicit spec_set *and* spec or autospec") original, local = self.get_original() if new is DEFAULT and autospec is None: inherit = False if spec is True: # set spec to the object we are replacing spec = original if spec_set is True: spec_set = original spec = None elif spec is not None: if spec_set is True: spec_set = spec spec = None elif spec_set is True: spec_set = original if spec is not None or spec_set is not None: if original is DEFAULT: raise TypeError("Can't use 'spec' with create=True") if isinstance(original, ClassTypes): # If we're patching out a class and there is a spec inherit = True Klass = MagicMock _kwargs = {} if new_callable is not None: Klass = new_callable elif spec is not None or spec_set is not None: this_spec = spec if spec_set is not None: this_spec = spec_set if _is_list(this_spec): not_callable = '__call__' not in this_spec else: not_callable = not _callable(this_spec) if not_callable: Klass = NonCallableMagicMock if spec is not None: _kwargs['spec'] = spec if spec_set is not None: _kwargs['spec_set'] = spec_set # add a name to mocks if (isinstance(Klass, type) and issubclass(Klass, NonCallableMock) and self.attribute): _kwargs['name'] = self.attribute _kwargs.update(kwargs) new = Klass(**_kwargs) if inherit and _is_instance_mock(new): # we can only tell if the instance should be callable if the # spec is not a list this_spec = spec if spec_set is not None: this_spec = spec_set if (not _is_list(this_spec) and not _instance_callable(this_spec)): Klass = NonCallableMagicMock _kwargs.pop('name') new.return_value = Klass(_new_parent=new, _new_name='()', **_kwargs) elif autospec is not None: # spec is ignored, new *must* be default, spec_set is treated # as a boolean. Should we check spec is not None and that spec_set # is a bool? if new is not DEFAULT: raise TypeError( "autospec creates the mock for you. Can't specify " "autospec and new." ) if original is DEFAULT: raise TypeError("Can't use 'autospec' with create=True") spec_set = bool(spec_set) if autospec is True: autospec = original new = create_autospec(autospec, spec_set=spec_set, _name=self.attribute, **kwargs) elif kwargs: # can't set keyword args when we aren't creating the mock # XXXX If new is a Mock we could call new.configure_mock(**kwargs) raise TypeError("Can't pass kwargs to a mock we aren't creating") new_attr = new self.temp_original = original self.is_local = local setattr(self.target, self.attribute, new_attr) if self.attribute_name is not None: extra_args = {} if self.new is DEFAULT: extra_args[self.attribute_name] = new for patching in self.additional_patchers: arg = patching.__enter__() if patching.new is DEFAULT: extra_args.update(arg) return extra_args return new def __exit__(self, *exc_info): """Undo the patch.""" if not _is_started(self): raise RuntimeError('stop called on unstarted patcher') if self.is_local and self.temp_original is not DEFAULT: setattr(self.target, self.attribute, self.temp_original) else: delattr(self.target, self.attribute) if not self.create and not hasattr(self.target, self.attribute): # needed for proxy objects like django settings setattr(self.target, self.attribute, self.temp_original) del self.temp_original del self.is_local del self.target for patcher in reversed(self.additional_patchers): if _is_started(patcher): patcher.__exit__(*exc_info) def start(self): """Activate a patch, returning any created mock.""" result = self.__enter__() self._active_patches.add(self) return result def stop(self): """Stop an active patch.""" self._active_patches.discard(self) return self.__exit__() def _get_target(target): try: target, attribute = target.rsplit('.', 1) except (TypeError, ValueError): raise TypeError("Need a valid target to patch. You supplied: %r" % (target,)) getter = lambda: _importer(target) return getter, attribute def _patch_object( target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs ): """ patch.object(target, attribute, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs) patch the named member (`attribute`) on an object (`target`) with a mock object. `patch.object` can be used as a decorator, class decorator or a context manager. Arguments `new`, `spec`, `create`, `spec_set`, `autospec` and `new_callable` have the same meaning as for `patch`. Like `patch`, `patch.object` takes arbitrary keyword arguments for configuring the mock object it creates. When used as a class decorator `patch.object` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ getter = lambda: target return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs ) def _patch_multiple(target, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs): """Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): ... Use `DEFAULT` as the value if you want `patch.multiple` to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when `patch.multiple` is used as a context manager. `patch.multiple` can be used as a decorator, class decorator or a context manager. The arguments `spec`, `spec_set`, `create`, `autospec` and `new_callable` have the same meaning as for `patch`. These arguments will be applied to *all* patches done by `patch.multiple`. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ if type(target) in (unicode, str): getter = lambda: _importer(target) else: getter = lambda: target if not kwargs: raise ValueError( 'Must supply at least one keyword argument with patch.multiple' ) # need to wrap in a list for python 3, where items is a view items = list(kwargs.items()) attribute, new = items[0] patcher = _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, {} ) patcher.attribute_name = attribute for attribute, new in items[1:]: this_patcher = _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, {} ) this_patcher.attribute_name = attribute patcher.additional_patchers.append(this_patcher) return patcher def patch( target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs ): """ `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with a `MagicMock`. If `patch` is used as a decorator and `new` is omitted, the created mock is passed in as an extra argument to the decorated function. If `patch` is used as a context manager the created mock is returned by the context manager. `target` should be a string in the form `'package.module.ClassName'`. The `target` is imported and the specified object replaced with the `new` object, so the `target` must be importable from the environment you are calling `patch` from. The target is imported when the decorated function is executed, not at decoration time. The `spec` and `spec_set` keyword arguments are passed to the `MagicMock` if patch is creating one for you. In addition you can pass `spec=True` or `spec_set=True`, which causes patch to pass in the object being mocked as the spec/spec_set object. `new_callable` allows you to specify a different class, or callable object, that will be called to create the `new` object. By default `MagicMock` is used. A more powerful form of `spec` is `autospec`. If you set `autospec=True` then the mock with be created with a spec from the object being replaced. All attributes of the mock will also have the spec of the corresponding attribute of the object being replaced. Methods and functions being mocked will have their arguments checked and will raise a `TypeError` if they are called with the wrong signature. For mocks replacing a class, their return value (the 'instance') will have the same spec as the class. Instead of `autospec=True` you can pass `autospec=some_object` to use an arbitrary object as the spec instead of the one being replaced. By default `patch` will fail to replace attributes that don't exist. If you pass in `create=True`, and the attribute doesn't exist, patch will create the attribute for you when the patched function is called, and delete it again afterwards. This is useful for writing tests against attributes that your production code creates at runtime. It is off by by default because it can be dangerous. With it switched on you can write passing tests against APIs that don't actually exist! Patch can be used as a `TestCase` class decorator. It works by decorating each test method in the class. This reduces the boilerplate code when your test methods share a common patchings set. `patch` finds tests by looking for method names that start with `patch.TEST_PREFIX`. By default this is `test`, which matches the way `unittest` finds tests. You can specify an alternative prefix by setting `patch.TEST_PREFIX`. Patch can be used as a context manager, with the with statement. Here the patching applies to the indented block after the with statement. If you use "as" then the patched object will be bound to the name after the "as"; very useful if `patch` is creating a mock object for you. `patch` takes arbitrary keyword arguments. These will be passed to the `Mock` (or `new_callable`) on construction. `patch.dict(...)`, `patch.multiple(...)` and `patch.object(...)` are available for alternate use-cases. """ getter, attribute = _get_target(target) return _patch( getter, attribute, new, spec, create, spec_set, autospec, new_callable, kwargs )
_patch
python
pandas-dev__pandas
asv_bench/benchmarks/algorithms.py
{ "start": 3295, "end": 3864 }
class ____: params = [ [True, False], ["first", "last", False], ["Int64", "Float64"], ] param_names = ["unique", "keep", "dtype"] def setup(self, unique, keep, dtype): N = 10**5 data = pd.Series(np.arange(N), dtype=dtype) data[list(range(1, N, 100))] = pd.NA if not unique: data = data.repeat(5) self.ser = data # cache is_unique self.ser.is_unique def time_duplicated(self, unique, keep, dtype): self.ser.duplicated(keep=keep)
DuplicatedMaskedArray
python
ray-project__ray
rllib/examples/envs/classes/multi_agent/footsies/fixed_rlmodules.py
{ "start": 1037, "end": 1357 }
class ____(FixedRLModule): def _fixed_forward(self, batch, **kwargs): obs_batch_size = len(tree.flatten(batch[sample_batch.SampleBatch.OBS])[0]) actions = batch_func([constants.EnvActions.NONE for _ in range(obs_batch_size)]) return {sample_batch.SampleBatch.ACTIONS: actions}
NoopFixedRLModule
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 221901, "end": 222192 }
class ____(VegaLiteSchema): """ConditionalAxisPropertyFontWeightnull schema wrapper.""" _schema = {"$ref": "#/definitions/ConditionalAxisProperty<(FontWeight|null)>"} def __init__(self, *args, **kwds): super().__init__(*args, **kwds)
ConditionalAxisPropertyFontWeightnull
python
huggingface__transformers
src/transformers/models/llava_onevision/modeling_llava_onevision.py
{ "start": 5234, "end": 6258 }
class ____(PreTrainedModel): config: LlavaOnevisionConfig base_model_prefix = "model" input_modalities = ("image", "video", "text") supports_gradient_checkpointing = True _no_split_modules = ["LlamaDecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn = True _supports_sdpa = True _can_compile_fullgraph = True _supports_flex_attn = True _supports_attention_backend = True @torch.no_grad() def _init_weights(self, module): std = getattr(self.config, "initializer_range", self.config.get_text_config().initializer_range) if isinstance(module, nn.Linear): init.normal_(module.weight, mean=0.0, std=std) if module.bias is not None: init.zeros_(module.bias) elif isinstance(module, LlavaOnevisionModel): embed_std = 1 / math.sqrt(self.config.text_config.hidden_size) init.normal_(module.image_newline, mean=0.0, std=embed_std)
LlavaOnevisionPreTrainedModel
python
django__django
tests/model_fields/test_charfield.py
{ "start": 157, "end": 1398 }
class ____(TestCase): def test_max_length_passed_to_formfield(self): """ CharField passes its max_length attribute to form fields created using the formfield() method. """ cf1 = models.CharField() cf2 = models.CharField(max_length=1234) self.assertIsNone(cf1.formfield().max_length) self.assertEqual(1234, cf2.formfield().max_length) def test_lookup_integer_in_charfield(self): self.assertEqual(Post.objects.filter(title=9).count(), 0) def test_emoji(self): p = Post.objects.create(title="Smile 😀", body="Whatever.") p.refresh_from_db() self.assertEqual(p.title, "Smile 😀") def test_assignment_from_choice_enum(self): class Event(models.TextChoices): C = "Carnival!" F = "Festival!" p1 = Post.objects.create(title=Event.C, body=Event.F) p1.refresh_from_db() self.assertEqual(p1.title, "Carnival!") self.assertEqual(p1.body, "Festival!") self.assertEqual(p1.title, Event.C) self.assertEqual(p1.body, Event.F) p2 = Post.objects.get(title="Carnival!") self.assertEqual(p1, p2) self.assertEqual(p2.title, Event.C)
TestCharField
python
coleifer__peewee
tests/pwiz_integration.py
{ "start": 1522, "end": 1590 }
class ____(object): def __init__(self, *_, **__): pass
UnknownField
python
xlwings__xlwings
xlwings/constants.py
{ "start": 115477, "end": 115587 }
class ____: xlAscending = 1 # from enum XlSortOrder xlDescending = 2 # from enum XlSortOrder
SortOrder
python
dagster-io__dagster
python_modules/dagster/dagster/_core/events/__init__.py
{ "start": 67697, "end": 68950 }
class ____( NamedTuple( "_ObjectStoreOperationResultData", [ ("op", ObjectStoreOperationType), ("value_name", Optional[str]), ("metadata", Mapping[str, MetadataValue]), ("address", Optional[str]), ("version", Optional[str]), ("mapping_key", Optional[str]), ], ) ): def __new__( cls, op: ObjectStoreOperationType, value_name: Optional[str] = None, metadata: Optional[Mapping[str, MetadataValue]] = None, address: Optional[str] = None, version: Optional[str] = None, mapping_key: Optional[str] = None, ): return super().__new__( cls, op=cast("ObjectStoreOperationType", check.str_param(op, "op")), value_name=check.opt_str_param(value_name, "value_name"), metadata=normalize_metadata( check.opt_mapping_param(metadata, "metadata", key_type=str) ), address=check.opt_str_param(address, "address"), version=check.opt_str_param(version, "version"), mapping_key=check.opt_str_param(mapping_key, "mapping_key"), ) @whitelist_for_serdes
ObjectStoreOperationResultData
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1586097, "end": 1586256 }
class ____(sgqlc.types.Union): """The object which triggered a `ClosedEvent`.""" __schema__ = github_schema __types__ = (Commit, PullRequest)
Closer
python
great-expectations__great_expectations
contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_kentucky_zip.py
{ "start": 747, "end": 1751 }
class ____(ColumnMapMetricProvider): # This is the id string that will be used to reference your metric. condition_metric_name = "column_values.valid_kentucky_zip" # This method implements the core logic for the PandasExecutionEngine @column_condition_partial(engine=PandasExecutionEngine) def _pandas(cls, column, **kwargs): return column.apply(lambda x: is_valid_kentucky_zip(x)) # This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine # @column_condition_partial(engine=SqlAlchemyExecutionEngine) # def _sqlalchemy(cls, column, _dialect, **kwargs): # raise NotImplementedError # This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine # @column_condition_partial(engine=SparkDFExecutionEngine) # def _spark(cls, column, **kwargs): # raise NotImplementedError # This class defines the Expectation itself
ColumnValuesToBeValidKentuckyZip
python
openai__openai-python
src/openai/types/beta/assistant_stream_event.py
{ "start": 4287, "end": 4448 }
class ____(BaseModel): data: RunStep """Represents a step in execution of a run.""" event: Literal["thread.run.step.completed"]
ThreadRunStepCompleted
python
run-llama__llama_index
llama-index-integrations/node_parser/llama-index-node-parser-relational-dashscope/llama_index/node_parser/dashscope/base.py
{ "start": 326, "end": 4641 }
class ____(BaseElementNodeParser): """ DashScope Json format element node parser. Splits a json format document from DashScope Parse into Text Nodes and Index Nodes corresponding to embedded objects (e.g. tables). """ try_count_limit: int = Field( default=10, description="Maximum number of retry attempts." ) chunk_size: int = Field(default=500, description="Size of each chunk to process.") overlap_size: int = Field( default=100, description="Overlap size between consecutive chunks." ) separator: str = Field( default=" |,|,|。|?|!|\n|\\?|\\!", description="Separator characters for splitting texts.", ) input_type: str = Field(default="idp", description="parse format type.") language: str = Field( default="cn", description="language of tokenizor, accept cn, en, any. Notice that <any> mode will be slow.", ) @classmethod def class_name(cls) -> str: return "DashScopeJsonNodeParser" def get_nodes_from_node(self, node: TextNode) -> List[BaseNode]: """Get nodes from node.""" ftype = node.metadata.get("parse_fmt_type", self.input_type) assert ftype in [ "DASHSCOPE_DOCMIND", "idp", ], f"Unexpected parse_fmt_type: {node.metadata.get('parse_fmt_type', '')}" ftype_map = { "DASHSCOPE_DOCMIND": "idp", } my_input = { "text": json.loads(node.get_content()), "file_type": ftype_map.get(ftype, ftype), "chunk_size": self.chunk_size, "overlap_size": self.overlap_size, "language": "cn", "separator": self.separator, } try_count = 0 response_text = self.post_service(my_input) while response_text is None and try_count < self.try_count_limit: try_count += 1 response_text = self.post_service(my_input) if response_text is None: logging.error("DashScopeJsonNodeParser Failed to get response from service") return [] return self.parse_result(response_text, node) def post_service(self, my_input: Dict[str, Any]) -> Optional[Dict[str, Any]]: DASHSCOPE_API_KEY = os.environ.get("DASHSCOPE_API_KEY", None) if DASHSCOPE_API_KEY is None: logging.error("DASHSCOPE_API_KEY is not set") raise ValueError("DASHSCOPE_API_KEY is not set") headers = { "Content-Type": "application/json", "Accept-Encoding": "utf-8", "Authorization": "Bearer " + DASHSCOPE_API_KEY, } service_url = ( os.getenv("DASHSCOPE_BASE_URL", "https://dashscope.aliyuncs.com") + "/api/v1/indices/component/configed_transformations/spliter" ) try: response = requests.post( service_url, data=json.dumps(my_input), headers=headers ) response_text = response.json() if "chunkService" in response_text: return response_text["chunkService"]["chunkResult"] else: logging.error(f"{response_text}, try again.") return None except Exception as e: logging.error(f"{e}, try again.") return None def parse_result( self, content_json: List[Dict[str, Any]], document: TextNode ) -> List[BaseNode]: nodes = [] for data in content_json: text = "\n".join( [data["title"], data.get("hier_title", ""), data["content"]] ) nodes.append( TextNode( metadata=document.metadata, text=text, excluded_embed_metadata_keys=document.excluded_embed_metadata_keys, excluded_llm_metadata_keys=document.excluded_llm_metadata_keys, ) ) return nodes def extract_elements( self, text: str, mode: Optional[str] = "json", node_id: Optional[str] = None, node_metadata: Optional[Dict[str, Any]] = None, table_filters: Optional[List[Callable]] = None, **kwargs: Any, ) -> List[Element]: return []
DashScopeJsonNodeParser
python
sqlalchemy__sqlalchemy
test/ext/test_compiler.py
{ "start": 1277, "end": 15201 }
class ____(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def test_column(self): class MyThingy(ColumnClause): inherit_cache = False def __init__(self, arg=None): super().__init__(arg or "MYTHINGY!") @compiles(MyThingy) def visit_thingy(thingy, compiler, **kw): return ">>%s<<" % thingy.name self.assert_compile( select(column("foo"), MyThingy()), "SELECT foo, >>MYTHINGY!<<" ) self.assert_compile( select(MyThingy("x"), MyThingy("y")).where(MyThingy() == 5), "SELECT >>x<<, >>y<< WHERE >>MYTHINGY!<< = :MYTHINGY!_1", ) def test_create_column_skip(self): @compiles(CreateColumn) def skip_xmin(element, compiler, **kw): if element.element.name == "xmin": return None else: return compiler.visit_create_column(element, **kw) t = Table( "t", MetaData(), Column("a", Integer), Column("xmin", Integer), Column("c", Integer), ) self.assert_compile( CreateTable(t), "CREATE TABLE t (a INTEGER, c INTEGER)" ) def test_types(self): class MyType(TypeEngine): pass @compiles(MyType, "sqlite") def visit_sqlite_type(type_, compiler, **kw): return "SQLITE_FOO" @compiles(MyType, "postgresql") def visit_pg_type(type_, compiler, **kw): return "POSTGRES_FOO" from sqlalchemy.dialects.sqlite import base as sqlite from sqlalchemy.dialects.postgresql import base as postgresql self.assert_compile(MyType(), "SQLITE_FOO", dialect=sqlite.dialect()) self.assert_compile( MyType(), "POSTGRES_FOO", dialect=postgresql.dialect() ) def test_no_compile_for_col_label(self): class MyThingy(FunctionElement): inherit_cache = True @compiles(MyThingy) def visit_thingy(thingy, compiler, **kw): raise Exception( "unfriendly exception, dont catch this, dont run this" ) @compiles(MyThingy, "postgresql") def visit_thingy_pg(thingy, compiler, **kw): return "mythingy" subq = select(MyThingy("text")).subquery() stmt = select(subq) self.assert_compile( stmt, "SELECT anon_2.anon_1 FROM (SELECT mythingy AS anon_1) AS anon_2", dialect="postgresql", ) def test_stateful(self): class MyThingy(ColumnClause): inherit_cache = False def __init__(self): super().__init__("MYTHINGY!") @compiles(MyThingy) def visit_thingy(thingy, compiler, **kw): if not hasattr(compiler, "counter"): compiler.counter = 0 compiler.counter += 1 return str(compiler.counter) self.assert_compile( select(column("foo"), MyThingy()).order_by(desc(MyThingy())), "SELECT foo, 1 ORDER BY 2 DESC", ) self.assert_compile( select(MyThingy(), MyThingy()).where(MyThingy() == 5), "SELECT 1, 2 WHERE 3 = :MYTHINGY!_1", ) def test_callout_to_compiler(self): class InsertFromSelect(ClauseElement): inherit_cache = False def __init__(self, table, select): self.table = table self.select = select @compiles(InsertFromSelect) def visit_insert_from_select(element, compiler, **kw): return "INSERT INTO %s (%s)" % ( compiler.process(element.table, asfrom=True), compiler.process(element.select), ) t1 = table("mytable", column("x"), column("y"), column("z")) self.assert_compile( InsertFromSelect(t1, select(t1).where(t1.c.x > 5)), "INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z " "FROM mytable WHERE mytable.x > :x_1)", ) def test_no_default_but_has_a_visit(self): class MyThingy(ColumnClause): inherit_cache = False @compiles(MyThingy, "postgresql") def visit_thingy(thingy, compiler, **kw): return "mythingy" eq_(str(MyThingy("x")), "x") def test_no_default_has_no_visit(self): class MyThingy(TypeEngine): inherit_cache = False @compiles(MyThingy, "postgresql") def visit_thingy(thingy, compiler, **kw): return "mythingy" assert_raises_message( exc.UnsupportedCompilationError, "<class 'test.ext.test_compiler..*MyThingy'> " "construct has no default compilation handler.", str, MyThingy(), ) @testing.combinations((True,), (False,)) def test_no_default_proxy_generation(self, named): class my_function(FunctionElement): inherit_cache = False if named: name = "my_function" type = Numeric() @compiles(my_function, "sqlite") def sqlite_my_function(element, compiler, **kw): return "my_function(%s)" % compiler.process(element.clauses, **kw) t1 = table("t1", column("q")) stmt = select(my_function(t1.c.q)) self.assert_compile( stmt, ( "SELECT my_function(t1.q) AS my_function_1 FROM t1" if named else "SELECT my_function(t1.q) AS anon_1 FROM t1" ), dialect="sqlite", ) if named: eq_(stmt.selected_columns.keys(), ["my_function"]) else: eq_(stmt.selected_columns.keys(), ["_no_label"]) def test_no_default_message(self): class MyThingy(ClauseElement): inherit_cache = False @compiles(MyThingy, "postgresql") def visit_thingy(thingy, compiler, **kw): return "mythingy" assert_raises_message( exc.UnsupportedCompilationError, "Compiler .*StrSQLCompiler.* can't .* " "<class 'test.ext.test_compiler..*MyThingy'> " "construct has no default compilation handler.", str, MyThingy(), ) def test_default_subclass(self): from sqlalchemy.types import ARRAY class MyArray(ARRAY): pass @compiles(MyArray, "sqlite") def sl_array(elem, compiler, **kw): return "array" self.assert_compile( MyArray(Integer), "INTEGER[]", dialect="postgresql" ) def test_annotations(self): """test that annotated clause constructs use the decorated class' compiler. """ t1 = table("t1", column("c1"), column("c2")) dispatch = Select._compiler_dispatch try: @compiles(Select) def compile_(element, compiler, **kw): return "OVERRIDE" s1 = select(t1) self.assert_compile(s1, "OVERRIDE") self.assert_compile(s1._annotate({}), "OVERRIDE") finally: Select._compiler_dispatch = dispatch if hasattr(Select, "_compiler_dispatcher"): del Select._compiler_dispatcher def test_dialect_specific(self): class AddThingy(ExecutableDDLElement): __visit_name__ = "add_thingy" class DropThingy(ExecutableDDLElement): __visit_name__ = "drop_thingy" @compiles(AddThingy, "sqlite") def visit_add_thingy_sqlite(thingy, compiler, **kw): return "ADD SPECIAL SL THINGY" @compiles(AddThingy) def visit_add_thingy(thingy, compiler, **kw): return "ADD THINGY" @compiles(DropThingy) def visit_drop_thingy(thingy, compiler, **kw): return "DROP THINGY" self.assert_compile(AddThingy(), "ADD THINGY") self.assert_compile(DropThingy(), "DROP THINGY") from sqlalchemy.dialects.sqlite import base self.assert_compile( AddThingy(), "ADD SPECIAL SL THINGY", dialect=base.dialect() ) self.assert_compile( DropThingy(), "DROP THINGY", dialect=base.dialect() ) @compiles(DropThingy, "sqlite") def visit_drop_thingy_sqlite(thingy, compiler, **kw): return "DROP SPECIAL SL THINGY" self.assert_compile( DropThingy(), "DROP SPECIAL SL THINGY", dialect=base.dialect() ) self.assert_compile(DropThingy(), "DROP THINGY") def test_functions(self): from sqlalchemy.dialects import postgresql class MyUtcFunction(FunctionElement): inherit_cache = True @compiles(MyUtcFunction) def visit_myfunc(element, compiler, **kw): return "utcnow()" @compiles(MyUtcFunction, "postgresql") def visit_myfunc_pg(element, compiler, **kw): return "timezone('utc', current_timestamp)" self.assert_compile( MyUtcFunction(), "utcnow()", use_default_dialect=True ) self.assert_compile( MyUtcFunction(), "timezone('utc', current_timestamp)", dialect=postgresql.dialect(), ) def test_functions_args_noname(self): class myfunc(FunctionElement): inherit_cache = True @compiles(myfunc) def visit_myfunc(element, compiler, **kw): return "myfunc%s" % (compiler.process(element.clause_expr, **kw),) self.assert_compile(myfunc(), "myfunc()") self.assert_compile(myfunc(column("x"), column("y")), "myfunc(x, y)") def test_function_calls_base(self): from sqlalchemy.dialects import mssql class greatest(FunctionElement): type = Numeric() name = "greatest" inherit_cache = True @compiles(greatest) def default_greatest(element, compiler, **kw): return compiler.visit_function(element) @compiles(greatest, "mssql") def case_greatest(element, compiler, **kw): arg1, arg2 = list(element.clauses) return "CASE WHEN %s > %s THEN %s ELSE %s END" % ( compiler.process(arg1), compiler.process(arg2), compiler.process(arg1), compiler.process(arg2), ) self.assert_compile( greatest("a", "b"), "greatest(:greatest_1, :greatest_2)", use_default_dialect=True, ) self.assert_compile( greatest("a", "b"), "CASE WHEN :greatest_1 > :greatest_2 " "THEN :greatest_1 ELSE :greatest_2 END", dialect=mssql.dialect(), ) def test_function_subclasses_one(self): class Base(FunctionElement): inherit_cache = True name = "base" class Sub1(Base): inherit_cache = True name = "sub1" class Sub2(Base): inherit_cache = True name = "sub2" @compiles(Base) def visit_base(element, compiler, **kw): return element.name @compiles(Sub1) def visit_sub1(element, compiler, **kw): return "FOO" + element.name self.assert_compile( select(Sub1(), Sub2()), "SELECT FOOsub1 AS sub1_1, sub2 AS sub2_1", use_default_dialect=True, ) def test_function_subclasses_two(self): class Base(FunctionElement): name = "base" class Sub1(Base): inherit_cache = True name = "sub1" @compiles(Base) def visit_base(element, compiler, **kw): return element.name class Sub2(Base): inherit_cache = True name = "sub2" class SubSub1(Sub1): inherit_cache = True name = "subsub1" self.assert_compile( select(Sub1(), Sub2(), SubSub1()), "SELECT sub1 AS sub1_1, sub2 AS sub2_1, subsub1 AS subsub1_1", use_default_dialect=True, ) @compiles(Sub1) def visit_sub1(element, compiler, **kw): return "FOO" + element.name self.assert_compile( select(Sub1(), Sub2(), SubSub1()), "SELECT FOOsub1 AS sub1_1, sub2 AS sub2_1, " "FOOsubsub1 AS subsub1_1", use_default_dialect=True, ) def _test_result_map_population(self, expression): lc1 = literal_column("1") lc2 = literal_column("2") stmt = select(lc1, expression, lc2) compiled = stmt.compile() eq_( compiled._result_columns, [ ("1", "1", (lc1, "1", "1"), NULLTYPE), (None, None, (expression,), NULLTYPE), ("2", "2", (lc2, "2", "2"), NULLTYPE), ], ) def test_result_map_population_explicit(self): class not_named_max(ColumnElement): name = "not_named_max" @compiles(not_named_max) def visit_max(element, compiler, **kw): # explicit add kw["add_to_result_map"](None, None, (element,), NULLTYPE) return "max(a)" nnm = not_named_max() self._test_result_map_population(nnm) def test_result_map_population_implicit(self): class not_named_max(ColumnElement): name = "not_named_max" @compiles(not_named_max) def visit_max(element, compiler, **kw): # we don't add to keymap here; compiler should be doing it return "max(a)" nnm = not_named_max() self._test_result_map_population(nnm)
UserDefinedTest
python
scipy__scipy
scipy/spatial/tests/test_distance.py
{ "start": 82528, "end": 84726 }
class ____: def test_pdist_chebyshev_random(self): eps = 1e-8 X = eo['pdist-double-inp'] Y_right = eo['pdist-chebyshev'] Y_test1 = pdist(X, 'chebyshev') assert_allclose(Y_test1, Y_right, rtol=eps) def test_pdist_chebyshev_random_float32(self): eps = 1e-7 X = np.float32(eo['pdist-double-inp']) Y_right = eo['pdist-chebyshev'] Y_test1 = pdist(X, 'chebyshev') assert_allclose(Y_test1, Y_right, rtol=eps, verbose=verbose > 2) def test_pdist_chebyshev_random_nonC(self): eps = 1e-8 X = eo['pdist-double-inp'] Y_right = eo['pdist-chebyshev'] Y_test2 = pdist(X, 'test_chebyshev') assert_allclose(Y_test2, Y_right, rtol=eps) def test_pdist_chebyshev_iris(self): eps = 1e-14 X = eo['iris'] Y_right = eo['pdist-chebyshev-iris'] Y_test1 = pdist(X, 'chebyshev') assert_allclose(Y_test1, Y_right, rtol=eps) def test_pdist_chebyshev_iris_float32(self): eps = 1e-5 X = np.float32(eo['iris']) Y_right = eo['pdist-chebyshev-iris'] Y_test1 = pdist(X, 'chebyshev') assert_allclose(Y_test1, Y_right, rtol=eps, verbose=verbose > 2) def test_pdist_chebyshev_iris_nonC(self): eps = 1e-14 X = eo['iris'] Y_right = eo['pdist-chebyshev-iris'] Y_test2 = pdist(X, 'test_chebyshev') assert_allclose(Y_test2, Y_right, rtol=eps) def test_weighted(self): # Basic test for weighted Chebyshev. Only components with non-zero # weight participate in the 'max'. x = [1, 2, 3] y = [6, 5, 4] w = [0, 1, 5] assert_equal(chebyshev(x, y, w), 3) assert_equal(pdist([x, y], 'chebyshev', w=w), [3]) assert_equal(cdist([x], [y], 'chebyshev', w=w), [[3]]) def test_zero_weight(self): # If the weight is identically zero, the distance should be zero. x = [1, 2, 3] y = [6, 5, 4] w = [0, 0, 0] assert_equal(chebyshev(x, y, w), 0) assert_equal(pdist([x, y], 'chebyshev', w=w), [0]) assert_equal(cdist([x], [y], 'chebyshev', w=w), [[0]])
TestChebyshev
python
sphinx-doc__sphinx
sphinx/ext/doctest.py
{ "start": 6255, "end": 6673 }
class ____(TestDirective): option_spec: ClassVar[OptionSpec] = { 'hide': directives.flag, 'no-trim-doctest-flags': directives.flag, 'options': directives.unchanged, 'pyversion': directives.unchanged_required, 'skipif': directives.unchanged_required, 'trim-doctest-flags': directives.flag, } parser = doctest.DocTestParser() # helper classes
TestoutputDirective
python
marshmallow-code__marshmallow
tests/test_registry.py
{ "start": 5871, "end": 7328 }
class ____(Schema): _id = fields.Integer() def test_multiple_classes_with_same_name_raises_error(): # Import a class with the same name from .foo_serializer import FooSerializer as FooSerializer1 # noqa: PLC0415, F401 class MySchema(Schema): foo = fields.Nested("FooSerializer") # Using a nested field with the class name fails because there are # two defined classes with the same name sch = MySchema() msg = "Multiple classes with name {!r} were found.".format("FooSerializer") with pytest.raises(RegistryError, match=msg): sch.dump({"foo": {"_id": 1}}) def test_multiple_classes_with_all(): # Import a class with the same name from .foo_serializer import FooSerializer as FooSerializer1 # noqa: PLC0415, F401 classes = class_registry.get_class("FooSerializer", all=True) assert len(classes) == 2 def test_can_use_full_module_path_to_class(): from .foo_serializer import FooSerializer as FooSerializer1 # noqa: PLC0415, F401 # Using full paths is ok class Schema1(Schema): foo = fields.Nested("tests.foo_serializer.FooSerializer") sch = Schema1() # Note: The arguments here don't matter. What matters is that no # error is raised assert sch.dump({"foo": {"_id": 42}}) class Schema2(Schema): foo = fields.Nested("tests.test_registry.FooSerializer") sch2 = Schema2() assert sch2.dump({"foo": {"_id": 42}})
FooSerializer
python
facebookresearch__faiss
tests/test_rabitq.py
{ "start": 67354, "end": 70686 }
class ____(unittest.TestCase): """Test index factory support for multi-bit RaBitQ.""" def test_factory_default_nb_bits(self): """Test that 'RaBitQ' creates 1-bit index by default.""" index = faiss.index_factory(128, "RaBitQ") self.assertIsInstance(index, faiss.IndexRaBitQ) self.assertEqual(index.rabitq.nb_bits, 1) expected_size = compute_expected_code_size(128, 1) self.assertEqual(index.code_size, expected_size) def test_factory_multibit_specifications(self): """Test that 'RaBitQ{nb_bits}' creates correct multi-bit indexes.""" d = 128 for nb_bits in [2, 4, 8]: factory_str = f"RaBitQ{nb_bits}" index = faiss.index_factory(d, factory_str) self.assertIsInstance(index, faiss.IndexRaBitQ) self.assertEqual(index.rabitq.nb_bits, nb_bits) expected_size = compute_expected_code_size(d, nb_bits) self.assertEqual(index.code_size, expected_size) def test_factory_ivf_default_nb_bits(self): """Test that 'IVF{nlist},RaBitQ' creates 1-bit IVF index.""" nlist = 16 index = faiss.index_factory(128, f"IVF{nlist},RaBitQ") self.assertIsInstance(index, faiss.IndexIVFRaBitQ) self.assertEqual(index.rabitq.nb_bits, 1) expected_size = compute_expected_code_size(128, 1) self.assertEqual(index.code_size, expected_size) def test_factory_ivf_multibit_specifications(self): """Test that 'IVF{nlist},RaBitQ{nb_bits}' creates multi-bit indexes.""" d = 128 nlist = 16 for nb_bits in [2, 4, 8]: factory_str = f"IVF{nlist},RaBitQ{nb_bits}" index = faiss.index_factory(d, factory_str) self.assertIsInstance(index, faiss.IndexIVFRaBitQ) self.assertEqual(index.rabitq.nb_bits, nb_bits) expected_size = compute_expected_code_size(d, nb_bits) self.assertEqual(index.code_size, expected_size) def test_factory_end_to_end(self): """Test complete workflow: factory creation, train, add, search.""" ds = create_test_dataset(d=64, nb=200, nq=10, nt=150) k = 5 # Test both non-IVF and IVF with multi-bit for nb_bits in [1, 4]: # Non-IVF factory_str = f"RaBitQ{nb_bits}" if nb_bits > 1 else "RaBitQ" index = faiss.index_factory(ds.d, factory_str) index.train(ds.get_train()) index.add(ds.get_database()) D, I = index.search(ds.get_queries(), k) self.assertEqual(D.shape, (ds.nq, k)) self.assertEqual(I.shape, (ds.nq, k)) self.assertTrue(np.all(I >= 0)) self.assertTrue(np.all(I < ds.nb)) # IVF ivf_str = ( f"IVF16,RaBitQ{nb_bits}" if nb_bits > 1 else "IVF16,RaBitQ" ) ivf_index = faiss.index_factory(ds.d, ivf_str) ivf_index.train(ds.get_train()) ivf_index.add(ds.get_database()) D_ivf, I_ivf = ivf_index.search(ds.get_queries(), k) self.assertEqual(D_ivf.shape, (ds.nq, k)) self.assertEqual(I_ivf.shape, (ds.nq, k)) self.assertTrue(np.all(I_ivf >= 0)) self.assertTrue(np.all(I_ivf < ds.nb))
TestMultiBitRaBitQIndexFactory
python
getsentry__sentry
tests/sentry/grouping/enhancements/test_hints.py
{ "start": 260, "end": 29655 }
class ____: hint: str | None contributes: bool | None = None in_app_hint = "marked in-app by (...)" client_in_app_hint = "marked in-app by the client" out_of_app_hint = "marked out of app by (...)" client_out_of_app_hint = "marked out of app by the client" ignored_hint = "ignored by (...)" ignored_because_hint = "ignored because ..." unignored_hint = "un-ignored by (...)" default_system_frame_hint = "non app frame" @pytest.mark.parametrize( [ "variant_name", "final_in_app", "client_in_app", "rust_hint", "incoming_hint", "desired_hint_type", "expected_result", ], # This represents every combo of: # # variant_name: app or system # final_in_app: True or False # client_in_app: None, True, or False # rust_hint: in_app_hint, out_of_app_hint, ignored_hint, unignored_hint, or None # incoming_hint: None or ignored_because_hint (the only kind of hint that gets set ahead of time) # desired_hint_type: In-app or contributes # # Some of the combos will never happen in real life, and those that won't are marked. They're still # in the list because it's much easier to ensure every case is covered that way. # # No formatting so that we can keep all the cases as single lines # fmt: off [ ("app", True, None, in_app_hint, None, "in-app", in_app_hint), ("app", True, None, in_app_hint, None, "contributes", None), ("app", True, None, in_app_hint, ignored_because_hint, "in-app", in_app_hint), ("app", True, None, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("app", True, None, out_of_app_hint, None, "in-app", out_of_app_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, None, out_of_app_hint, None, "contributes", None), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, None, out_of_app_hint, ignored_because_hint, "in-app", out_of_app_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, None, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, None, ignored_hint, None, "in-app", None), ("app", True, None, ignored_hint, None, "contributes", ignored_hint), ("app", True, None, ignored_hint, ignored_because_hint, "in-app", None), ("app", True, None, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("app", True, None, unignored_hint, None, "in-app", None), ("app", True, None, unignored_hint, None, "contributes", unignored_hint), ("app", True, None, unignored_hint, ignored_because_hint, "in-app", None), ("app", True, None, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("app", True, None, None, None, "in-app", None), ("app", True, None, None, None, "contributes", None), ("app", True, None, None, ignored_because_hint, "in-app", None), ("app", True, None, None, ignored_because_hint, "contributes", ignored_because_hint), ("app", True, True, in_app_hint, None, "in-app", client_in_app_hint), ("app", True, True, in_app_hint, None, "contributes", None), ("app", True, True, in_app_hint, ignored_because_hint, "in-app", client_in_app_hint), ("app", True, True, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("app", True, True, out_of_app_hint, None, "in-app", client_in_app_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, True, out_of_app_hint, None, "contributes", None), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, True, out_of_app_hint, ignored_because_hint, "in-app", client_in_app_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, True, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, True, ignored_hint, None, "in-app", client_in_app_hint), ("app", True, True, ignored_hint, None, "contributes", ignored_hint), ("app", True, True, ignored_hint, ignored_because_hint, "in-app", client_in_app_hint), ("app", True, True, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("app", True, True, unignored_hint, None, "in-app", client_in_app_hint), ("app", True, True, unignored_hint, None, "contributes", unignored_hint), ("app", True, True, unignored_hint, ignored_because_hint, "in-app", client_in_app_hint), ("app", True, True, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("app", True, True, None, None, "in-app", client_in_app_hint), ("app", True, True, None, None, "contributes", None), ("app", True, True, None, ignored_because_hint, "in-app", client_in_app_hint), ("app", True, True, None, ignored_because_hint, "contributes", ignored_because_hint), ("app", True, False, in_app_hint, None, "in-app", in_app_hint), ("app", True, False, in_app_hint, None, "contributes", None), ("app", True, False, in_app_hint, ignored_because_hint, "in-app", in_app_hint), ("app", True, False, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("app", True, False, out_of_app_hint, None, "in-app", out_of_app_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, False, out_of_app_hint, None, "contributes", None), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, False, out_of_app_hint, ignored_because_hint, "in-app", out_of_app_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, False, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("app", True, False, ignored_hint, None, "in-app", None), ("app", True, False, ignored_hint, None, "contributes", ignored_hint), ("app", True, False, ignored_hint, ignored_because_hint, "in-app", None), ("app", True, False, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("app", True, False, unignored_hint, None, "in-app", None), ("app", True, False, unignored_hint, None, "contributes", unignored_hint), ("app", True, False, unignored_hint, ignored_because_hint, "in-app", None), ("app", True, False, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("app", True, False, None, None, "in-app", None), # impossible - can't have no rust hint if client in-app is changed ("app", True, False, None, None, "contributes", None), # impossible - can't have no rust hint if client in-app is changed ("app", True, False, None, ignored_because_hint, "in-app", None), # impossible - can't have no rust hint if client in-app is changed ("app", True, False, None, ignored_because_hint, "contributes", ignored_because_hint), # impossible - can't have no rust hint if client in-app is changed ("app", False, None, in_app_hint, None, "in-app", in_app_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, None, in_app_hint, None, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, None, in_app_hint, ignored_because_hint, "in-app", in_app_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, None, in_app_hint, ignored_because_hint, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, None, out_of_app_hint, None, "in-app", out_of_app_hint), ("app", False, None, out_of_app_hint, None, "contributes", None), ("app", False, None, out_of_app_hint, ignored_because_hint, "in-app", out_of_app_hint), ("app", False, None, out_of_app_hint, ignored_because_hint, "contributes", None), ("app", False, None, ignored_hint, None, "in-app", default_system_frame_hint), ("app", False, None, ignored_hint, None, "contributes", None), ("app", False, None, ignored_hint, ignored_because_hint, "in-app", default_system_frame_hint), ("app", False, None, ignored_hint, ignored_because_hint, "contributes", None), ("app", False, None, unignored_hint, None, "in-app", default_system_frame_hint), ("app", False, None, unignored_hint, None, "contributes", None), ("app", False, None, unignored_hint, ignored_because_hint, "in-app", default_system_frame_hint), ("app", False, None, unignored_hint, ignored_because_hint, "contributes", None), ("app", False, None, None, None, "in-app", default_system_frame_hint), ("app", False, None, None, None, "contributes", None), ("app", False, None, None, ignored_because_hint, "in-app", default_system_frame_hint), ("app", False, None, None, ignored_because_hint, "contributes", None), ("app", False, True, in_app_hint, None, "in-app", in_app_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, True, in_app_hint, None, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, True, in_app_hint, ignored_because_hint, "in-app", in_app_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, True, in_app_hint, ignored_because_hint, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, True, out_of_app_hint, None, "in-app", out_of_app_hint), ("app", False, True, out_of_app_hint, None, "contributes", None), ("app", False, True, out_of_app_hint, ignored_because_hint, "in-app", out_of_app_hint), ("app", False, True, out_of_app_hint, ignored_because_hint, "contributes", None), ("app", False, True, ignored_hint, None, "in-app", default_system_frame_hint), ("app", False, True, ignored_hint, None, "contributes", None), ("app", False, True, ignored_hint, ignored_because_hint, "in-app", default_system_frame_hint), ("app", False, True, ignored_hint, ignored_because_hint, "contributes", None), ("app", False, True, unignored_hint, None, "in-app", default_system_frame_hint), ("app", False, True, unignored_hint, None, "contributes", None), ("app", False, True, unignored_hint, ignored_because_hint, "in-app", default_system_frame_hint), ("app", False, True, unignored_hint, ignored_because_hint, "contributes", None), ("app", False, True, None, None, "in-app", default_system_frame_hint), # impossible - can't have no rust hint if client in-app is changed ("app", False, True, None, None, "contributes", None), # impossible - can't have no rust hint if client in-app is changed ("app", False, True, None, ignored_because_hint, "in-app", default_system_frame_hint), # impossible - can't have no rust hint if client in-app is changed ("app", False, True, None, ignored_because_hint, "contributes", None), # impossible - can't have no rust hint if client in-app is changed ("app", False, False, in_app_hint, None, "in-app", client_out_of_app_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, False, in_app_hint, None, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, False, in_app_hint, ignored_because_hint, "in-app", client_out_of_app_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, False, in_app_hint, ignored_because_hint, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("app", False, False, out_of_app_hint, None, "in-app", client_out_of_app_hint), ("app", False, False, out_of_app_hint, None, "contributes", None), ("app", False, False, out_of_app_hint, ignored_because_hint, "in-app", client_out_of_app_hint), ("app", False, False, out_of_app_hint, ignored_because_hint, "contributes", None), ("app", False, False, ignored_hint, None, "in-app", client_out_of_app_hint), ("app", False, False, ignored_hint, None, "contributes", None), ("app", False, False, ignored_hint, ignored_because_hint, "in-app", client_out_of_app_hint), ("app", False, False, ignored_hint, ignored_because_hint, "contributes", None), ("app", False, False, unignored_hint, None, "in-app", client_out_of_app_hint), ("app", False, False, unignored_hint, None, "contributes", None), ("app", False, False, unignored_hint, ignored_because_hint, "in-app", client_out_of_app_hint), ("app", False, False, unignored_hint, ignored_because_hint, "contributes", None), ("app", False, False, None, None, "in-app", client_out_of_app_hint), ("app", False, False, None, None, "contributes", None), ("app", False, False, None, ignored_because_hint, "in-app", client_out_of_app_hint), ("app", False, False, None, ignored_because_hint, "contributes", None), ("system", True, None, in_app_hint, None, "in-app", None), ("system", True, None, in_app_hint, None, "contributes", None), ("system", True, None, in_app_hint, ignored_because_hint, "in-app", None), ("system", True, None, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("system", True, None, out_of_app_hint, None, "in-app", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, None, out_of_app_hint, None, "contributes", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, None, out_of_app_hint, ignored_because_hint, "in-app", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, None, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, None, ignored_hint, None, "in-app", None), ("system", True, None, ignored_hint, None, "contributes", ignored_hint), ("system", True, None, ignored_hint, ignored_because_hint, "in-app", None), ("system", True, None, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("system", True, None, unignored_hint, None, "in-app", None), ("system", True, None, unignored_hint, None, "contributes", unignored_hint), ("system", True, None, unignored_hint, ignored_because_hint, "in-app", None), ("system", True, None, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("system", True, None, None, None, "in-app", None), ("system", True, None, None, None, "contributes", None), ("system", True, None, None, ignored_because_hint, "in-app", None), ("system", True, None, None, ignored_because_hint, "contributes", ignored_because_hint), ("system", True, True, in_app_hint, None, "in-app", None), ("system", True, True, in_app_hint, None, "contributes", None), ("system", True, True, in_app_hint, ignored_because_hint, "in-app", None), ("system", True, True, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("system", True, True, out_of_app_hint, None, "in-app", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, True, out_of_app_hint, None, "contributes", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, True, out_of_app_hint, ignored_because_hint, "in-app", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, True, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, True, ignored_hint, None, "in-app", None), ("system", True, True, ignored_hint, None, "contributes", ignored_hint), ("system", True, True, ignored_hint, ignored_because_hint, "in-app", None), ("system", True, True, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("system", True, True, unignored_hint, None, "in-app", None), ("system", True, True, unignored_hint, None, "contributes", unignored_hint), ("system", True, True, unignored_hint, ignored_because_hint, "in-app", None), ("system", True, True, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("system", True, True, None, None, "in-app", None), ("system", True, True, None, None, "contributes", None), ("system", True, True, None, ignored_because_hint, "in-app", None), ("system", True, True, None, ignored_because_hint, "contributes", ignored_because_hint), ("system", True, False, in_app_hint, None, "in-app", None), ("system", True, False, in_app_hint, None, "contributes", None), ("system", True, False, in_app_hint, ignored_because_hint, "in-app", None), ("system", True, False, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("system", True, False, out_of_app_hint, None, "in-app", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, False, out_of_app_hint, None, "contributes", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, False, out_of_app_hint, ignored_because_hint, "in-app", None), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, False, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return out of app hint if it marks frame in-app ("system", True, False, ignored_hint, None, "in-app", None), ("system", True, False, ignored_hint, None, "contributes", ignored_hint), ("system", True, False, ignored_hint, ignored_because_hint, "in-app", None), ("system", True, False, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("system", True, False, unignored_hint, None, "in-app", None), ("system", True, False, unignored_hint, None, "contributes", unignored_hint), ("system", True, False, unignored_hint, ignored_because_hint, "in-app", None), ("system", True, False, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("system", True, False, None, None, "in-app", None), # impossible - can't have no rust hint if client in-app is changed ("system", True, False, None, None, "contributes", None), # impossible - can't have no rust hint if client in-app is changed ("system", True, False, None, ignored_because_hint, "in-app", None), # impossible - can't have no rust hint if client in-app is changed ("system", True, False, None, ignored_because_hint, "contributes", ignored_because_hint), # impossible - can't have no rust hint if client in-app is changed ("system", False, None, in_app_hint, None, "in-app", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, None, in_app_hint, None, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, None, in_app_hint, ignored_because_hint, "in-app", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, None, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, None, out_of_app_hint, None, "in-app", None), ("system", False, None, out_of_app_hint, None, "contributes", None), ("system", False, None, out_of_app_hint, ignored_because_hint, "in-app", None), ("system", False, None, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("system", False, None, ignored_hint, None, "in-app", None), ("system", False, None, ignored_hint, None, "contributes", ignored_hint), ("system", False, None, ignored_hint, ignored_because_hint, "in-app", None), ("system", False, None, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("system", False, None, unignored_hint, None, "in-app", None), ("system", False, None, unignored_hint, None, "contributes", unignored_hint), ("system", False, None, unignored_hint, ignored_because_hint, "in-app", None), ("system", False, None, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("system", False, None, None, None, "in-app", None), ("system", False, None, None, None, "contributes", None), ("system", False, None, None, ignored_because_hint, "in-app", None), ("system", False, None, None, ignored_because_hint, "contributes", ignored_because_hint), ("system", False, True, in_app_hint, None, "in-app", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, True, in_app_hint, None, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, True, in_app_hint, ignored_because_hint, "in-app", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, True, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, True, out_of_app_hint, None, "in-app", None), ("system", False, True, out_of_app_hint, None, "contributes", None), ("system", False, True, out_of_app_hint, ignored_because_hint, "in-app", None), ("system", False, True, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("system", False, True, ignored_hint, None, "in-app", None), ("system", False, True, ignored_hint, None, "contributes", ignored_hint), ("system", False, True, ignored_hint, ignored_because_hint, "in-app", None), ("system", False, True, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("system", False, True, unignored_hint, None, "in-app", None), ("system", False, True, unignored_hint, None, "contributes", unignored_hint), ("system", False, True, unignored_hint, ignored_because_hint, "in-app", None), ("system", False, True, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("system", False, True, None, None, "in-app", None), # impossible - can't have no rust hint if client in-app is changed ("system", False, True, None, None, "contributes", None), # impossible - can't have no rust hint if client in-app is changed ("system", False, True, None, ignored_because_hint, "in-app", None), # impossible - can't have no rust hint if client in-app is changed ("system", False, True, None, ignored_because_hint, "contributes", ignored_because_hint), # impossible - can't have no rust hint if client in-app is changed ("system", False, False, in_app_hint, None, "in-app", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, False, in_app_hint, None, "contributes", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, False, in_app_hint, ignored_because_hint, "in-app", None), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, False, in_app_hint, ignored_because_hint, "contributes", ignored_because_hint), # impossible - rust can't return in-app hint if it marks frame out of app ("system", False, False, out_of_app_hint, None, "in-app", None), ("system", False, False, out_of_app_hint, None, "contributes", None), ("system", False, False, out_of_app_hint, ignored_because_hint, "in-app", None), ("system", False, False, out_of_app_hint, ignored_because_hint, "contributes", ignored_because_hint), ("system", False, False, ignored_hint, None, "in-app", None), ("system", False, False, ignored_hint, None, "contributes", ignored_hint), ("system", False, False, ignored_hint, ignored_because_hint, "in-app", None), ("system", False, False, ignored_hint, ignored_because_hint, "contributes", ignored_hint), ("system", False, False, unignored_hint, None, "in-app", None), ("system", False, False, unignored_hint, None, "contributes", unignored_hint), ("system", False, False, unignored_hint, ignored_because_hint, "in-app", None), ("system", False, False, unignored_hint, ignored_because_hint, "contributes", unignored_hint), ("system", False, False, None, None, "in-app", None), ("system", False, False, None, None, "contributes", None), ("system", False, False, None, ignored_because_hint, "in-app", None), ("system", False, False, None, ignored_because_hint, "contributes", ignored_because_hint), ] # fmt: on, ) def test_get_hint_for_frame( variant_name: str, final_in_app: bool, client_in_app: bool | None, rust_hint: str | None, incoming_hint: str | None, desired_hint_type: Literal["in-app", "contributes"], expected_result: str | None, ) -> None: frame = {"in_app": final_in_app, "data": {"client_in_app": client_in_app}} frame_component = FrameGroupingComponent(in_app=final_in_app, hint=incoming_hint, values=[]) rust_frame = DummyRustFrame(hint=rust_hint) assert ( _get_hint_for_frame( variant_name, frame, frame_component, rust_frame, # type: ignore[arg-type] # rust frame mock fails typecheck desired_hint_type, set(), ) == expected_result ) @pytest.mark.parametrize( ["variant_name", "in_app", "contributes", "in_app_hint", "contributes_hint", "expected_result"], [ ("app", True, True, in_app_hint, None, in_app_hint), ("app", True, True, in_app_hint, unignored_hint, f"{in_app_hint} and {unignored_hint}"), ("app", True, False, in_app_hint, ignored_hint, f"{in_app_hint} but {ignored_hint}"), ("app", False, True, out_of_app_hint, None, out_of_app_hint), ("app", False, True, out_of_app_hint, unignored_hint, out_of_app_hint), ("app", False, False, out_of_app_hint, ignored_hint, out_of_app_hint), ("system", True, True, None, None, None), ("system", True, True, None, unignored_hint, unignored_hint), ("system", True, False, None, ignored_hint, ignored_hint), ("system", False, True, None, None, None), ("system", False, True, None, unignored_hint, unignored_hint), ("system", False, False, None, ignored_hint, ignored_hint), ], ) def test_combining_hints( variant_name: str, in_app: bool, contributes: bool, in_app_hint: str | None, contributes_hint: str | None, expected_result: str | None, ) -> None: frame_component = FrameGroupingComponent(in_app=in_app, contributes=contributes, values=[]) assert ( _combine_hints(variant_name, frame_component, in_app_hint, contributes_hint) == expected_result ) def test_adds_rule_source_to_stacktrace_rule_hints() -> None: frame = {"in_app": True} frame_component = FrameGroupingComponent(in_app=True, values=[]) custom_rules = {"function:roll_over +app"} built_in_rule_rust_frame = DummyRustFrame( hint="marked in-app by stack trace rule (function:shake +app)" ) custom_rule_rust_frame = DummyRustFrame( hint="marked in-app by stack trace rule (function:roll_over +app)" ) assert ( _get_hint_for_frame( "app", frame, frame_component, built_in_rule_rust_frame, # type: ignore[arg-type] # rust frame mock fails typecheck "in-app", custom_rules, ) == "marked in-app by built-in stack trace rule (function:shake +app)" ) assert ( _get_hint_for_frame( "app", frame, frame_component, custom_rule_rust_frame, # type: ignore[arg-type] # rust frame mock fails typecheck "in-app", custom_rules, ) == "marked in-app by custom stack trace rule (function:roll_over +app)" )
DummyRustFrame
python
huggingface__transformers
src/transformers/models/blenderbot/tokenization_blenderbot.py
{ "start": 1125, "end": 7382 }
class ____(TokenizersBackend): """ Construct a "fast" Blenderbot tokenizer (backed by HuggingFace's *tokenizers* library), derived from the GPT-2 tokenizer, using byte-level Byte-Pair-Encoding. This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will be encoded differently whether it is at the beginning of the sentence (without space) or not: ```python >>> from transformers import BlenderbotTokenizerFast >>> tokenizer = BlenderbotTokenizerFast.from_pretrained("facebook/blenderbot-3B") >>> tokenizer("Hello world")["input_ids"] [6950, 1085, 2] >>> tokenizer(" Hello world")["input_ids"] [6950, 1085, 2] ``` You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance. <Tip> When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`. </Tip> This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: bos_token (`str`, *optional*, defaults to `"<s>"`): The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. <Tip> When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the `cls_token`. </Tip> eos_token (`str`, *optional*, defaults to `"</s>"`): The end of sequence token. <Tip> When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the `sep_token`. </Tip> sep_token (`str`, *optional*, defaults to `"</s>"`): The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens. cls_token (`str`, *optional*, defaults to `"<s>"`): The classifier token which is used when doing sequence classification (classification of the whole sequence instead of per-token classification). It is the first token of the sequence when built with special tokens. unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. pad_token (`str`, *optional*, defaults to `"<pad>"`): The token used for padding, for example when batching sequences of different lengths. mask_token (`str`, *optional*, defaults to `"<mask>"`): The token used for masking values. This is the token used when training this model with masked language modeling. This is the token which the model will try to predict. add_prefix_space (`bool`, *optional*, defaults to `True`): Whether or not to add an initial space to the input. This allows to treat the leading word just as any other word. (Blenderbot tokenizer detect beginning of words by the preceding space). vocab (`dict`, *optional*): Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file. merges (`list`, *optional*): Custom merges list. If not provided, merges are loaded from merges_file. """ vocab_files_names = VOCAB_FILES_NAMES model_input_names = ["input_ids", "attention_mask"] def __init__( self, bos_token="<s>", eos_token="</s>", sep_token="</s>", cls_token="<s>", unk_token="<unk>", pad_token="<pad>", mask_token="<mask>", add_prefix_space=True, vocab=None, merges=None, **kwargs, ): self.add_prefix_space = add_prefix_space mask_token = ( AddedToken(mask_token, lstrip=True, rstrip=False, normalized=False) if isinstance(mask_token, str) else mask_token ) if vocab is not None and merges is not None: self._vocab = ( {token: idx for idx, (token, _score) in enumerate(vocab)} if isinstance(vocab, list) else vocab ) self._merges = merges else: # Initialize with minimal vocab self._vocab = { str(bos_token): 0, str(pad_token): 1, str(eos_token): 2, str(unk_token): 3, str(mask_token): 4, } self._merges = [] self._tokenizer = Tokenizer( BPE( vocab=self._vocab, merges=self._merges, dropout=None, continuing_subword_prefix="", end_of_word_suffix="", fuse_unk=False, ) ) self._tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=add_prefix_space) self._tokenizer.decoder = decoders.ByteLevel() self._tokenizer.post_processor = processors.RobertaProcessing( sep=(str(eos_token), self._vocab.get(str(eos_token), 2)), cls=(str(bos_token), self._vocab.get(str(bos_token), 0)), add_prefix_space=add_prefix_space, trim_offsets=True, ) tokenizer_object = self._tokenizer super().__init__( tokenizer_object=tokenizer_object, bos_token=bos_token, eos_token=eos_token, sep_token=sep_token, cls_token=cls_token, unk_token=unk_token, pad_token=pad_token, mask_token=mask_token, add_prefix_space=add_prefix_space, **kwargs, ) __all__ = ["BlenderbotTokenizer"]
BlenderbotTokenizer
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B014.py
{ "start": 326, "end": 1644 }
class ____(Exception): pass try: pass except (MyError, MyError): # Detect duplicate non-builtin errors pass try: pass except (MyError, Exception) as e: # Don't assume that we're all subclasses of Exception pass try: pass except (MyError, BaseException) as e: # But we *can* assume that everything is a subclass of BaseException pass try: pass except (re.error, re.error): # Duplicate exception types as attributes pass try: pass except (IOError, EnvironmentError, OSError): # Detect if a primary exception and any its aliases are present. # # Since Python 3.3, IOError, EnvironmentError, WindowsError, mmap.error, # socket.error and select.error are aliases of OSError. See PEP 3151 for # more info. pass try: pass except (MyException, NotImplemented): # NotImplemented is not an exception, let's not crash on it. pass try: pass except (ValueError, binascii.Error): # binascii.Error is a subclass of ValueError. pass # Regression test for: https://github.com/astral-sh/ruff/issues/6412 try: pass except (ValueError, ValueError, TypeError): pass # Regression test for: https://github.com/astral-sh/ruff/issues/7455#issuecomment-1739801758 try: pas except(re.error, re.error): p
MyError
python
run-llama__llama_index
llama-index-integrations/storage/index_store/llama-index-storage-index-store-azurecosmosnosql/llama_index/storage/index_store/azurecosmosnosql/base.py
{ "start": 275, "end": 3255 }
class ____(BaseKVStore): """Creates an Azure Cosmos DB NoSql Index Store.""" def __init__( self, azure_cosmos_nosql_kvstore: AzureCosmosNoSqlKVStore, namespace: Optional[str] = None, collection_suffix: Optional[str] = None, ) -> None: """Initializes the Azure Cosmos NoSql Index Store.""" super().__init__(azure_cosmos_nosql_kvstore, namespace, collection_suffix) @classmethod def from_connection_string( cls, connection_string: str, index_db_name: str = DEFAULT_INDEX_DATABASE, index_container_name: str = DEFAULT_INDEX_CONTAINER, cosmos_container_properties: Dict[str, Any] = None, cosmos_database_properties: Dict[str, Any] = None, ) -> "AzureCosmosNoSqlIndexStore": """Creates an instance of Azure Cosmos DB NoSql KV Store using a connection string.""" azure_cosmos_nosql_kvstore = AzureCosmosNoSqlKVStore.from_connection_string( connection_string, index_db_name, index_container_name, cosmos_container_properties, cosmos_database_properties, ) namespace = index_db_name + "." + index_container_name return cls(azure_cosmos_nosql_kvstore, namespace) @classmethod def from_account_and_key( cls, endpoint: str, key: str, index_db_name: str = DEFAULT_INDEX_DATABASE, index_container_name: str = DEFAULT_INDEX_CONTAINER, cosmos_container_properties: Dict[str, Any] = None, cosmos_database_properties: Dict[str, Any] = None, ) -> "AzureCosmosNoSqlIndexStore": """Creates an instance of Azure Cosmos DB NoSql KV Store using an account endpoint and key.""" azure_cosmos_nosql_kvstore = AzureCosmosNoSqlKVStore.from_account_and_key( endpoint, key, index_db_name, index_container_name, cosmos_container_properties, cosmos_database_properties, ) namespace = index_db_name + "." + index_container_name return cls(azure_cosmos_nosql_kvstore, namespace) @classmethod def from_aad_token( cls, endpoint: str, index_db_name: str = DEFAULT_INDEX_DATABASE, index_container_name: str = DEFAULT_INDEX_CONTAINER, cosmos_container_properties: Dict[str, Any] = None, cosmos_database_properties: Dict[str, Any] = None, ) -> "AzureCosmosNoSqlIndexStore": """Creates an instance of Azure Cosmos DB NoSql KV Store using an aad token.""" azure_cosmos_nosql_kvstore = AzureCosmosNoSqlKVStore.from_aad_token( endpoint, index_db_name, index_container_name, cosmos_container_properties, cosmos_database_properties, ) namespace = index_db_name + "." + index_container_name return cls(azure_cosmos_nosql_kvstore, namespace)
AzureCosmosNoSqlIndexStore
python
jazzband__django-oauth-toolkit
oauth2_provider/forms.py
{ "start": 734, "end": 1450 }
class ____(forms.Form): allow = forms.BooleanField(required=False) id_token_hint = forms.CharField(required=False, widget=forms.HiddenInput()) logout_hint = forms.CharField(required=False, widget=forms.HiddenInput()) client_id = forms.CharField(required=False, widget=forms.HiddenInput()) post_logout_redirect_uri = forms.CharField(required=False, widget=forms.HiddenInput()) state = forms.CharField(required=False, widget=forms.HiddenInput()) ui_locales = forms.CharField(required=False, widget=forms.HiddenInput()) def __init__(self, *args, **kwargs): self.request = kwargs.pop("request", None) super(ConfirmLogoutForm, self).__init__(*args, **kwargs)
ConfirmLogoutForm
python
pypa__setuptools
setuptools/tests/test_windows_wrappers.py
{ "start": 1894, "end": 6658 }
class ____(WrapperTester): script_name = 'foo-script.py' wrapper_name = 'foo.exe' wrapper_source = win_launcher_exe('cli') script_tmpl = textwrap.dedent( """ #!%(python_exe)s import sys input = repr(sys.stdin.read()) print(sys.argv[0][-14:]) print(sys.argv[1:]) print(input) if __debug__: print('non-optimized') """ ).lstrip() def test_basic(self, tmpdir): """ When the copy of cli.exe, foo.exe in this example, runs, it examines the path name it was run with and computes a Python script path name by removing the '.exe' suffix and adding the '-script.py' suffix. (For GUI programs, the suffix '-script.pyw' is added.) This is why we named out script the way we did. Now we can run out script by running the wrapper: This example was a little pathological in that it exercised windows (MS C runtime) quoting rules: - Strings containing spaces are surrounded by double quotes. - Double quotes in strings need to be escaped by preceding them with back slashes. - One or more backslashes preceding double quotes need to be escaped by preceding each of them with back slashes. """ self.create_script(tmpdir) cmd = [ str(tmpdir / 'foo.exe'), 'arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b', ] proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True, encoding="utf-8", ) stdout, _stderr = proc.communicate('hello\nworld\n') actual = stdout.replace('\r\n', '\n') expected = textwrap.dedent( r""" \foo-script.py ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] 'hello\nworld\n' non-optimized """ ).lstrip() assert actual == expected def test_symlink(self, tmpdir): """ Ensure that symlink for the foo.exe is working correctly. """ script_dir = tmpdir / "script_dir" script_dir.mkdir() self.create_script(script_dir) symlink = pathlib.Path(tmpdir / "foo.exe") symlink.symlink_to(script_dir / "foo.exe") cmd = [ str(tmpdir / 'foo.exe'), 'arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b', ] proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, text=True, encoding="utf-8", ) stdout, _stderr = proc.communicate('hello\nworld\n') actual = stdout.replace('\r\n', '\n') expected = textwrap.dedent( r""" \foo-script.py ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] 'hello\nworld\n' non-optimized """ ).lstrip() assert actual == expected def test_with_options(self, tmpdir): """ Specifying Python Command-line Options -------------------------------------- You can specify a single argument on the '#!' line. This can be used to specify Python options like -O, to run in optimized mode or -i to start the interactive interpreter. You can combine multiple options as usual. For example, to run in optimized mode and enter the interpreter after running the script, you could use -Oi: """ self.create_script(tmpdir) tmpl = textwrap.dedent( """ #!%(python_exe)s -Oi import sys input = repr(sys.stdin.read()) print(sys.argv[0][-14:]) print(sys.argv[1:]) print(input) if __debug__: print('non-optimized') sys.ps1 = '---' """ ).lstrip() with (tmpdir / 'foo-script.py').open('w') as f: f.write(self.prep_script(tmpl)) cmd = [str(tmpdir / 'foo.exe')] proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", ) stdout, _stderr = proc.communicate() actual = stdout.replace('\r\n', '\n') expected = textwrap.dedent( r""" \foo-script.py [] '' --- """ ).lstrip() assert actual == expected
TestCLI
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 222368, "end": 229156 }
class ____(multi_rv_generic): r"""A Dirichlet multinomial random variable. The Dirichlet multinomial distribution is a compound probability distribution: it is the multinomial distribution with number of trials `n` and class probabilities ``p`` randomly sampled from a Dirichlet distribution with concentration parameters ``alpha``. Methods ------- logpmf(x, alpha, n): Log of the probability mass function. pmf(x, alpha, n): Probability mass function. mean(alpha, n): Mean of the Dirichlet multinomial distribution. var(alpha, n): Variance of the Dirichlet multinomial distribution. cov(alpha, n): The covariance of the Dirichlet multinomial distribution. Parameters ---------- %(_dirichlet_mn_doc_default_callparams)s %(_doc_random_state)s See Also -------- scipy.stats.dirichlet : The dirichlet distribution. scipy.stats.multinomial : The multinomial distribution. References ---------- .. [1] Dirichlet-multinomial distribution, Wikipedia, https://www.wikipedia.org/wiki/Dirichlet-multinomial_distribution Examples -------- >>> from scipy.stats import dirichlet_multinomial Get the PMF >>> n = 6 # number of trials >>> alpha = [3, 4, 5] # concentration parameters >>> x = [1, 2, 3] # counts >>> dirichlet_multinomial.pmf(x, alpha, n) 0.08484162895927604 If the sum of category counts does not equal the number of trials, the probability mass is zero. >>> dirichlet_multinomial.pmf(x, alpha, n=7) 0.0 Get the log of the PMF >>> dirichlet_multinomial.logpmf(x, alpha, n) -2.4669689491013327 Get the mean >>> dirichlet_multinomial.mean(alpha, n) array([1.5, 2. , 2.5]) Get the variance >>> dirichlet_multinomial.var(alpha, n) array([1.55769231, 1.84615385, 2.01923077]) Get the covariance >>> dirichlet_multinomial.cov(alpha, n) array([[ 1.55769231, -0.69230769, -0.86538462], [-0.69230769, 1.84615385, -1.15384615], [-0.86538462, -1.15384615, 2.01923077]]) Alternatively, the object may be called (as a function) to fix the `alpha` and `n` parameters, returning a "frozen" Dirichlet multinomial random variable. >>> dm = dirichlet_multinomial(alpha, n) >>> dm.pmf(x) 0.08484162895927579 All methods are fully vectorized. Each element of `x` and `alpha` is a vector (along the last axis), each element of `n` is an integer (scalar), and the result is computed element-wise. >>> x = [[1, 2, 3], [4, 5, 6]] >>> alpha = [[1, 2, 3], [4, 5, 6]] >>> n = [6, 15] >>> dirichlet_multinomial.pmf(x, alpha, n) array([0.06493506, 0.02626937]) >>> dirichlet_multinomial.cov(alpha, n).shape # both covariance matrices (2, 3, 3) Broadcasting according to standard NumPy conventions is supported. Here, we have four sets of concentration parameters (each a two element vector) for each of three numbers of trials (each a scalar). >>> alpha = [[3, 4], [4, 5], [5, 6], [6, 7]] >>> n = [[6], [7], [8]] >>> dirichlet_multinomial.mean(alpha, n).shape (3, 4, 2) """ def __init__(self, seed=None): super().__init__(seed) self.__doc__ = doccer.docformat(self.__doc__, dirichlet_mn_docdict_params) def __call__(self, alpha, n, seed=None): return dirichlet_multinomial_frozen(alpha, n, seed=seed) def logpmf(self, x, alpha, n): """The log of the probability mass function. Parameters ---------- x: ndarray Category counts (non-negative integers). Must be broadcastable with shape parameter ``alpha``. If multidimensional, the last axis must correspond with the categories. %(_dirichlet_mn_doc_default_callparams)s Returns ------- out: ndarray or scalar Log of the probability mass function. """ a, Sa, n, x = _dirichlet_multinomial_check_parameters(alpha, n, x) out = np.asarray(loggamma(Sa) + loggamma(n + 1) - loggamma(n + Sa)) out += (loggamma(x + a) - (loggamma(a) + loggamma(x + 1))).sum(axis=-1) np.place(out, n != x.sum(axis=-1), -np.inf) return out[()] def pmf(self, x, alpha, n): """Probability mass function for a Dirichlet multinomial distribution. Parameters ---------- x: ndarray Category counts (non-negative integers). Must be broadcastable with shape parameter ``alpha``. If multidimensional, the last axis must correspond with the categories. %(_dirichlet_mn_doc_default_callparams)s Returns ------- out: ndarray or scalar Probability mass function. """ return np.exp(self.logpmf(x, alpha, n)) def mean(self, alpha, n): """Mean of a Dirichlet multinomial distribution. Parameters ---------- %(_dirichlet_mn_doc_default_callparams)s Returns ------- out: ndarray Mean of a Dirichlet multinomial distribution. """ a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n) n, Sa = n[..., np.newaxis], Sa[..., np.newaxis] return n * a / Sa def var(self, alpha, n): """The variance of the Dirichlet multinomial distribution. Parameters ---------- %(_dirichlet_mn_doc_default_callparams)s Returns ------- out: array_like The variances of the components of the distribution. This is the diagonal of the covariance matrix of the distribution. """ a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n) n, Sa = n[..., np.newaxis], Sa[..., np.newaxis] return n * a / Sa * (1 - a/Sa) * (n + Sa) / (1 + Sa) def cov(self, alpha, n): """Covariance matrix of a Dirichlet multinomial distribution. Parameters ---------- %(_dirichlet_mn_doc_default_callparams)s Returns ------- out : array_like The covariance matrix of the distribution. """ a, Sa, n = _dirichlet_multinomial_check_parameters(alpha, n) var = dirichlet_multinomial.var(a, n) n, Sa = n[..., np.newaxis, np.newaxis], Sa[..., np.newaxis, np.newaxis] aiaj = a[..., :, np.newaxis] * a[..., np.newaxis, :] cov = -n * aiaj / Sa ** 2 * (n + Sa) / (1 + Sa) ii = np.arange(cov.shape[-1]) cov[..., ii, ii] = var return cov dirichlet_multinomial = dirichlet_multinomial_gen()
dirichlet_multinomial_gen
python
huggingface__transformers
src/transformers/models/seamless_m4t_v2/modeling_seamless_m4t_v2.py
{ "start": 22739, "end": 27860 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.dropout = nn.Dropout(config.speech_encoder_dropout) self.layers = nn.ModuleList( [SeamlessM4Tv2ConformerEncoderLayer(config) for _ in range(config.speech_encoder_layers)] ) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.gradient_checkpointing = False def _apply_chunk_attention(self, attention_mask, hidden_states): """ Creates a chunk attention mask. It creates a mask to prevent attention across chunks, ensuring that each position attends only to positions within its own chunk. If a left chunk overlap is specified (`speech_encoder_chunk_size` in the configuration), the attention mask is adjusted accordingly to allow each position to also attends the `speech_encoder_chunk_size - 1` previous chunks. """ sequence_len = hidden_states.shape[1] chunk_indices = torch.arange(sequence_len, device=hidden_states.device) chunk_indices = torch.div(chunk_indices, self.config.speech_encoder_chunk_size).long() start_indices = torch.full_like(chunk_indices, 0) if self.config.speech_encoder_left_chunk_num >= 0: start_indices = (chunk_indices - self.config.speech_encoder_left_chunk_num).clamp_(min=0) start_indices = start_indices * self.config.speech_encoder_chunk_size start_indices = start_indices.unsqueeze(1).expand(-1, sequence_len) end_indices = ((chunk_indices + 1) * self.config.speech_encoder_chunk_size).clamp_(max=sequence_len) end_indices = end_indices.unsqueeze(1).expand(-1, sequence_len) indices = torch.arange(sequence_len, device=hidden_states.device).unsqueeze(0).expand(sequence_len, -1) chunk_mask = (indices < start_indices) | (indices >= end_indices) chunk_mask = chunk_mask.unsqueeze(0).unsqueeze(0) attention_mask = chunk_mask if attention_mask is None else (attention_mask.bool() | chunk_mask) attention_mask = attention_mask.to(dtype=hidden_states.dtype) return attention_mask def forward( self, hidden_states, attention_mask=None, output_attentions=False, output_hidden_states=False, return_dict=True, ): all_hidden_states = () if output_hidden_states else None all_self_attentions = () if output_attentions else None conv_attention_mask = attention_mask if attention_mask is not None: # make sure padded tokens output 0 hidden_states = hidden_states.masked_fill(~attention_mask.bool().unsqueeze(-1), 0.0) # extend attention_mask attention_mask = 1.0 - attention_mask[:, None, None, :].to(dtype=hidden_states.dtype) attention_mask = attention_mask.expand( attention_mask.shape[0], 1, attention_mask.shape[-1], attention_mask.shape[-1] ) if self.config.speech_encoder_chunk_size is not None: attention_mask = self._apply_chunk_attention(attention_mask, hidden_states) if attention_mask is not None: attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min hidden_states = self.dropout(hidden_states) synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self) for i, layer in enumerate(self.layers): if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description) dropout_probability = torch.rand([]) skip_the_layer = self.training and dropout_probability < self.config.speech_encoder_layerdrop if not skip_the_layer or synced_gpus: # under fsdp or deepspeed zero3 all gpus must run in sync layer_outputs = layer( hidden_states, attention_mask=attention_mask, output_attentions=output_attentions, conv_attention_mask=conv_attention_mask, ) hidden_states = layer_outputs[0] if skip_the_layer: layer_outputs = (None, None) if output_attentions: all_self_attentions = all_self_attentions + (layer_outputs[1],) hidden_states = self.layer_norm(hidden_states) if output_hidden_states: all_hidden_states = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None) return BaseModelOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_self_attentions, ) # Copied from transformers.models.seamless_m4t.modeling_seamless_m4t.SeamlessM4TConformerAdapterLayer with SeamlessM4T->SeamlessM4Tv2
SeamlessM4Tv2ConformerEncoder
python
mlflow__mlflow
mlflow/store/artifact/cloud_artifact_repo.py
{ "start": 2883, "end": 3105 }
class ____(NamedTuple): # Local filesystem path of the source file to upload src_file_path: str # Base artifact URI-relative path specifying the upload destination artifact_file_path: str
StagedArtifactUpload
python
PyCQA__pylint
pylint/message/message_definition_store.py
{ "start": 647, "end": 5083 }
class ____: """The messages store knows information about every possible message definition but has no particular state during analysis. """ def __init__( self, py_version: tuple[int, ...] | sys._version_info = sys.version_info ) -> None: self.message_id_store: MessageIdStore = MessageIdStore() # Primary registry for all active messages definitions. # It contains the 1:1 mapping from msgid to MessageDefinition. # Keys are msgid, values are MessageDefinition self._messages_definitions: dict[str, MessageDefinition] = {} # MessageDefinition kept by category self._msgs_by_category: dict[str, list[str]] = collections.defaultdict(list) self.py_version = py_version @property def messages(self) -> ValuesView[MessageDefinition]: """The list of all active messages.""" return self._messages_definitions.values() def register_messages_from_checker(self, checker: BaseChecker) -> None: """Register all messages definitions from a checker.""" checker.check_consistency() for message in checker.messages: self.register_message(message) def register_message(self, message: MessageDefinition) -> None: """Register a MessageDefinition with consistency in mind.""" self.message_id_store.register_message_definition( message.msgid, message.symbol, message.old_names ) self._messages_definitions[message.msgid] = message self._msgs_by_category[message.msgid[0]].append(message.msgid) # Since MessageDefinitionStore is only initialized once # and the arguments are relatively small we do not run the # risk of creating a large memory leak. # See discussion in: https://github.com/pylint-dev/pylint/pull/5673 @cache # pylint: disable=method-cache-max-size-none # noqa: B019 def get_message_definitions(self, msgid_or_symbol: str) -> list[MessageDefinition]: """Returns the Message definition for either a numeric or symbolic id. The cache has no limit as its size will likely stay minimal. For each message we store about 1000 characters, so even if we would have 1000 messages the cache would only take up ~= 1 Mb. """ return [ self._messages_definitions[m] for m in self.message_id_store.get_active_msgids(msgid_or_symbol) ] def get_msg_display_string(self, msgid_or_symbol: str) -> str: """Generates a user-consumable representation of a message.""" message_definitions = self.get_message_definitions(msgid_or_symbol) if len(message_definitions) == 1: return repr(message_definitions[0].symbol) return repr([md.symbol for md in message_definitions]) def help_message(self, msgids_or_symbols: Sequence[str]) -> None: """Display help messages for the given message identifiers.""" for msgids_or_symbol in msgids_or_symbols: try: for message_definition in self.get_message_definitions( msgids_or_symbol ): print(message_definition.format_help(checkerref=True)) print("") except UnknownMessageError as ex: print(ex) print("") continue def list_messages(self) -> None: """Output full messages list documentation in ReST format.""" emittable, non_emittable = self.find_emittable_messages() print("Emittable messages with current interpreter:") for msg in emittable: print(msg.format_help(checkerref=False)) print("\nNon-emittable messages with current interpreter:") for msg in non_emittable: print(msg.format_help(checkerref=False)) print("") def find_emittable_messages( self, ) -> tuple[list[MessageDefinition], list[MessageDefinition]]: """Finds all emittable and non-emittable messages.""" messages = sorted(self._messages_definitions.values(), key=lambda m: m.msgid) emittable = [] non_emittable = [] for message in messages: if message.may_be_emitted(self.py_version): emittable.append(message) else: non_emittable.append(message) return emittable, non_emittable
MessageDefinitionStore
python
anthropics__anthropic-sdk-python
src/anthropic/types/messages/message_batch_succeeded_result.py
{ "start": 234, "end": 333 }
class ____(BaseModel): message: Message type: Literal["succeeded"]
MessageBatchSucceededResult
python
chardet__chardet
chardet/chardistribution.py
{ "start": 7633, "end": 8546 }
class ____(CharDistributionAnalysis): def __init__(self) -> None: super().__init__() self._char_to_freq_order = BIG5_CHAR_TO_FREQ_ORDER self._table_size = BIG5_TABLE_SIZE self.typical_distribution_ratio = BIG5_TYPICAL_DISTRIBUTION_RATIO def get_order(self, byte_str: Union[bytes, bytearray]) -> int: # type: ignore[reportIncompatibleMethodOverride] # for big5 encoding, we are interested # first byte range: 0xa4 -- 0xfe # second byte range: 0x40 -- 0x7e , 0xa1 -- 0xfe # no validation needed here. State machine has done that first_char, second_char = byte_str[0], byte_str[1] if first_char >= 0xA4: if second_char >= 0xA1: return 157 * (first_char - 0xA4) + second_char - 0xA1 + 63 return 157 * (first_char - 0xA4) + second_char - 0x40 return -1
Big5DistributionAnalysis
python
getsentry__sentry
src/sentry/replays/usecases/delete.py
{ "start": 3520, "end": 3625 }
class ____(TypedDict): retention_days: int replay_id: str max_segment_id: int | None
MatchedRow
python
apache__airflow
providers/teradata/src/airflow/providers/teradata/utils/tpt_util.py
{ "start": 984, "end": 18891 }
class ____: """Configuration constants for TPT operations.""" DEFAULT_TIMEOUT = 5 FILE_PERMISSIONS_READ_ONLY = 0o400 TEMP_DIR_WINDOWS = "C:\\Windows\\Temp" TEMP_DIR_UNIX = "/tmp" def execute_remote_command(ssh_client: SSHClient, command: str) -> tuple[int, str, str]: """ Execute a command on remote host and properly manage SSH channels. :param ssh_client: SSH client connection :param command: Command to execute :return: Tuple of (exit_status, stdout, stderr) """ stdin, stdout, stderr = ssh_client.exec_command(command) try: exit_status = stdout.channel.recv_exit_status() stdout_data = stdout.read().decode().strip() stderr_data = stderr.read().decode().strip() return exit_status, stdout_data, stderr_data finally: stdin.close() stdout.close() stderr.close() def write_file(path: str, content: str) -> None: with open(path, "w", encoding="utf-8") as f: f.write(content) def secure_delete(file_path: str, logger: logging.Logger | None = None) -> None: """ Securely delete a file using shred if available, otherwise use os.remove. :param file_path: Path to the file to be deleted :param logger: Optional logger instance """ logger = logger or logging.getLogger(__name__) if not os.path.exists(file_path): return try: # Check if shred is available if shutil.which("shred") is not None: # Use shred to securely delete the file subprocess.run(["shred", "--remove", file_path], check=True, timeout=TPTConfig.DEFAULT_TIMEOUT) logger.info("Securely removed file using shred: %s", file_path) else: # Fall back to regular deletion os.remove(file_path) logger.info("Removed file: %s", file_path) except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as e: logger.warning("Failed to remove file %s: %s", file_path, str(e)) def remote_secure_delete( ssh_client: SSHClient, remote_files: list[str], logger: logging.Logger | None = None ) -> None: """ Securely delete remote files via SSH. Attempts shred first, falls back to rm if shred is unavailable. :param ssh_client: SSH client connection :param remote_files: List of remote file paths to delete :param logger: Optional logger instance """ logger = logger or logging.getLogger(__name__) if not ssh_client or not remote_files: return try: # Detect remote OS remote_os = get_remote_os(ssh_client, logger) windows_remote = remote_os == "windows" # Check if shred is available on remote system (UNIX/Linux) shred_available = False if not windows_remote: exit_status, output, _ = execute_remote_command(ssh_client, "command -v shred") shred_available = exit_status == 0 and output.strip() != "" for file_path in remote_files: try: if windows_remote: # Windows remote host - use del command replace_slash = file_path.replace("/", "\\") execute_remote_command( ssh_client, f'if exist "{replace_slash}" del /f /q "{replace_slash}"' ) elif shred_available: # UNIX/Linux with shred execute_remote_command(ssh_client, f"shred --remove {file_path}") else: # UNIX/Linux without shred - overwrite then delete execute_remote_command( ssh_client, f"if [ -f {file_path} ]; then " f"dd if=/dev/zero of={file_path} bs=4096 count=$(($(stat -c '%s' {file_path})/4096+1)) 2>/dev/null; " f"rm -f {file_path}; fi", ) except Exception as e: logger.warning("Failed to process remote file %s: %s", file_path, str(e)) logger.info("Processed remote files: %s", ", ".join(remote_files)) except Exception as e: logger.warning("Failed to remove remote files: %s", str(e)) def terminate_subprocess(sp: subprocess.Popen | None, logger: logging.Logger | None = None) -> None: """ Terminate a subprocess gracefully with proper error handling. :param sp: Subprocess to terminate :param logger: Optional logger instance """ logger = logger or logging.getLogger(__name__) if not sp or sp.poll() is not None: # Process is None or already terminated return logger.info("Terminating subprocess (PID: %s)", sp.pid) try: sp.terminate() # Attempt to terminate gracefully sp.wait(timeout=TPTConfig.DEFAULT_TIMEOUT) logger.info("Subprocess terminated gracefully") except subprocess.TimeoutExpired: logger.warning( "Subprocess did not terminate gracefully within %d seconds, killing it", TPTConfig.DEFAULT_TIMEOUT ) try: sp.kill() sp.wait(timeout=2) # Brief wait after kill logger.info("Subprocess killed successfully") except Exception as e: logger.error("Error killing subprocess: %s", str(e)) except Exception as e: logger.error("Error terminating subprocess: %s", str(e)) def get_remote_os(ssh_client: SSHClient, logger: logging.Logger | None = None) -> str: """ Detect the operating system of the remote host via SSH. :param ssh_client: SSH client connection :param logger: Optional logger instance :return: Operating system type as string ('windows' or 'unix') """ logger = logger or logging.getLogger(__name__) if not ssh_client: logger.warning("No SSH client provided for OS detection") return "unix" try: # Check for Windows first exit_status, stdout_data, stderr_data = execute_remote_command(ssh_client, "echo %OS%") if "Windows" in stdout_data: return "windows" # All other systems are treated as Unix-like return "unix" except Exception as e: logger.error("Error detecting remote OS: %s", str(e)) return "unix" def set_local_file_permissions(local_file_path: str, logger: logging.Logger | None = None) -> None: """ Set permissions for a local file to be read-only for the owner. :param local_file_path: Path to the local file :param logger: Optional logger instance :raises FileNotFoundError: If the file does not exist :raises OSError: If setting permissions fails """ logger = logger or logging.getLogger(__name__) if not local_file_path: logger.warning("No file path provided for permission setting") return if not os.path.exists(local_file_path): raise FileNotFoundError(f"File does not exist: {local_file_path}") try: # Set file permission to read-only for the owner (400) os.chmod(local_file_path, TPTConfig.FILE_PERMISSIONS_READ_ONLY) logger.info("Set read-only permissions for file %s", local_file_path) except (OSError, PermissionError) as e: raise OSError(f"Error setting permissions for local file {local_file_path}: {e}") from e def _set_windows_file_permissions( ssh_client: SSHClient, remote_file_path: str, logger: logging.Logger ) -> None: """Set restrictive permissions on Windows remote file.""" command = f'icacls "{remote_file_path}" /inheritance:r /grant:r "%USERNAME%":R' exit_status, stdout_data, stderr_data = execute_remote_command(ssh_client, command) if exit_status != 0: raise RuntimeError( f"Failed to set restrictive permissions on Windows remote file {remote_file_path}. " f"Exit status: {exit_status}, Error: {stderr_data if stderr_data else 'N/A'}" ) logger.info("Set restrictive permissions (owner read-only) for Windows remote file %s", remote_file_path) def _set_unix_file_permissions(ssh_client: SSHClient, remote_file_path: str, logger: logging.Logger) -> None: """Set read-only permissions on Unix/Linux remote file.""" command = f"chmod 400 {remote_file_path}" exit_status, stdout_data, stderr_data = execute_remote_command(ssh_client, command) if exit_status != 0: raise RuntimeError( f"Failed to set permissions (400) on remote file {remote_file_path}. " f"Exit status: {exit_status}, Error: {stderr_data if stderr_data else 'N/A'}" ) logger.info("Set read-only permissions for remote file %s", remote_file_path) def set_remote_file_permissions( ssh_client: SSHClient, remote_file_path: str, logger: logging.Logger | None = None ) -> None: """ Set permissions for a remote file to be read-only for the owner. :param ssh_client: SSH client connection :param remote_file_path: Path to the remote file :param logger: Optional logger instance :raises RuntimeError: If permission setting fails """ logger = logger or logging.getLogger(__name__) if not ssh_client or not remote_file_path: logger.warning( "Invalid parameters: ssh_client=%s, remote_file_path=%s", bool(ssh_client), remote_file_path ) return try: # Detect remote OS once remote_os = get_remote_os(ssh_client, logger) if remote_os == "windows": _set_windows_file_permissions(ssh_client, remote_file_path, logger) else: _set_unix_file_permissions(ssh_client, remote_file_path, logger) except RuntimeError: raise except Exception as e: raise RuntimeError(f"Error setting permissions for remote file {remote_file_path}: {e}") from e def get_remote_temp_directory(ssh_client: SSHClient, logger: logging.Logger | None = None) -> str: """ Get the remote temporary directory path based on the operating system. :param ssh_client: SSH client connection :param logger: Optional logger instance :return: Path to the remote temporary directory """ logger = logger or logging.getLogger(__name__) try: # Detect OS once remote_os = get_remote_os(ssh_client, logger) if remote_os == "windows": exit_status, temp_dir, stderr_data = execute_remote_command(ssh_client, "echo %TEMP%") if exit_status == 0 and temp_dir and temp_dir != "%TEMP%": return temp_dir logger.warning("Could not get TEMP directory, using default: %s", TPTConfig.TEMP_DIR_WINDOWS) return TPTConfig.TEMP_DIR_WINDOWS # Unix/Linux - use /tmp return TPTConfig.TEMP_DIR_UNIX except Exception as e: logger.warning("Error getting remote temp directory: %s", str(e)) return TPTConfig.TEMP_DIR_UNIX def verify_tpt_utility_installed(utility: str) -> None: """Verify if a TPT utility (e.g., tbuild) is installed and available in the system's PATH.""" if shutil.which(utility) is None: raise FileNotFoundError( f"TPT utility '{utility}' is not installed or not available in the system's PATH" ) def verify_tpt_utility_on_remote_host( ssh_client: SSHClient, utility: str, logger: logging.Logger | None = None ) -> None: """ Verify if a TPT utility (tbuild) is installed on the remote host via SSH. :param ssh_client: SSH client connection :param utility: Name of the utility to verify :param logger: Optional logger instance :raises FileNotFoundError: If utility is not found on remote host :raises RuntimeError: If verification fails unexpectedly """ logger = logger or logging.getLogger(__name__) try: # Detect remote OS once remote_os = get_remote_os(ssh_client, logger) if remote_os == "windows": command = f"where {utility}" else: command = f"which {utility}" exit_status, output, error = execute_remote_command(ssh_client, command) if exit_status != 0 or not output: raise FileNotFoundError( f"TPT utility '{utility}' is not installed or not available in PATH on the remote host. " f"Command: {command}, Exit status: {exit_status}, " f"stderr: {error if error else 'N/A'}" ) logger.info("TPT utility '%s' found at: %s", utility, output.split("\n")[0]) except (FileNotFoundError, RuntimeError): raise except Exception as e: raise RuntimeError(f"Failed to verify TPT utility '{utility}' on remote host: {e}") from e def prepare_tpt_ddl_script( sql: list[str], error_list: list[int] | None, source_conn: dict[str, Any], job_name: str | None = None, ) -> str: """ Prepare a TPT script for executing DDL statements. This method generates a TPT script that defines a DDL operator and applies the provided SQL statements. It also supports specifying a list of error codes to handle during the operation. :param sql: A list of DDL statements to execute. :param error_list: A list of error codes to handle during the operation. :param source_conn: Connection details for the source database. :param job_name: The name of the TPT job. Defaults to unique name if None. :return: A formatted TPT script as a string. :raises ValueError: If the SQL statement list is empty. """ if not sql or not isinstance(sql, list): raise ValueError("SQL statement list must be a non-empty list") # Clean and escape each SQL statement: sql_statements = [ stmt.strip().rstrip(";").replace("'", "''") for stmt in sql if stmt and isinstance(stmt, str) and stmt.strip() ] if not sql_statements: raise ValueError("No valid SQL statements found in the provided input") # Format for TPT APPLY block, indenting after the first line apply_sql = ",\n".join( [f"('{stmt};')" if i == 0 else f" ('{stmt};')" for i, stmt in enumerate(sql_statements)] ) if job_name is None: job_name = f"airflow_tptddl_{uuid.uuid4().hex}" # Format error list for inclusion in the TPT script if not error_list: error_list_stmt = "ErrorList = ['']" else: error_list_str = ", ".join([f"'{error}'" for error in error_list]) error_list_stmt = f"ErrorList = [{error_list_str}]" host = source_conn["host"] login = source_conn["login"] password = source_conn["password"] tpt_script = f""" DEFINE JOB {job_name} DESCRIPTION 'TPT DDL Operation' ( APPLY {apply_sql} TO OPERATOR ( $DDL () ATTR ( TdpId = '{host}', UserName = '{login}', UserPassword = '{password}', {error_list_stmt} ) ); ); """ return tpt_script def decrypt_remote_file( ssh_client: SSHClient, remote_enc_file: str, remote_dec_file: str, password: str, logger: logging.Logger | None = None, ) -> int: """ Decrypt a remote file using OpenSSL. :param ssh_client: SSH client connection :param remote_enc_file: Path to the encrypted file :param remote_dec_file: Path for the decrypted file :param password: Decryption password :param logger: Optional logger instance :return: Exit status of the decryption command :raises RuntimeError: If decryption fails """ logger = logger or logging.getLogger(__name__) # Detect remote OS remote_os = get_remote_os(ssh_client, logger) windows_remote = remote_os == "windows" if windows_remote: # Windows - use different quoting and potentially different OpenSSL parameters password_escaped = password.replace('"', '""') # Escape double quotes for Windows decrypt_cmd = ( f'openssl enc -d -aes-256-cbc -salt -pbkdf2 -pass pass:"{password_escaped}" ' f'-in "{remote_enc_file}" -out "{remote_dec_file}"' ) else: # Unix/Linux - use single quote escaping password_escaped = password.replace("'", "'\\''") # Escape single quotes decrypt_cmd = ( f"openssl enc -d -aes-256-cbc -salt -pbkdf2 -pass pass:'{password_escaped}' " f"-in {remote_enc_file} -out {remote_dec_file}" ) exit_status, stdout_data, stderr_data = execute_remote_command(ssh_client, decrypt_cmd) if exit_status != 0: raise RuntimeError( f"Decryption failed with exit status {exit_status}. Error: {stderr_data if stderr_data else 'N/A'}" ) logger.info("Successfully decrypted remote file %s to %s", remote_enc_file, remote_dec_file) return exit_status def transfer_file_sftp( ssh_client: SSHClient, local_path: str, remote_path: str, logger: logging.Logger | None = None ) -> None: """ Transfer a file from local to remote host using SFTP. :param ssh_client: SSH client connection :param local_path: Local file path :param remote_path: Remote file path :param logger: Optional logger instance :raises FileNotFoundError: If local file does not exist :raises RuntimeError: If file transfer fails """ logger = logger or logging.getLogger(__name__) if not os.path.exists(local_path): raise FileNotFoundError(f"Local file does not exist: {local_path}") sftp = None try: sftp = ssh_client.open_sftp() sftp.put(local_path, remote_path) logger.info("Successfully transferred file from %s to %s", local_path, remote_path) except Exception as e: raise RuntimeError(f"Failed to transfer file from {local_path} to {remote_path}: {e}") from e finally: if sftp: sftp.close()
TPTConfig
python
google__jax
jax/_src/custom_derivatives.py
{ "start": 54515, "end": 81205 }
class ____: def __init__(self, jaxpr, in_tree, out_tree, consts): self.jaxpr = jaxpr self.in_tree = in_tree self.out_tree = out_tree self.consts = consts def __iter__(self): return iter((self.jaxpr, self.in_tree, self.out_tree, self.consts)) def tree_flatten(self): return self.consts, (self.jaxpr, self.in_tree, self.out_tree) @classmethod def tree_unflatten(cls, aux, consts): jaxpr, in_tree, out_tree = aux return cls(jaxpr, in_tree, out_tree, consts) def closure_convert(fun: Callable, *example_args) -> tuple[Callable, list[Any]]: """Closure conversion utility, for use with higher-order custom derivatives. To define custom derivatives such as with ``jax.custom_vjp(f)``, the target function ``f`` must take, as formal arguments, all values involved in differentiation. If ``f`` is a higher-order function, in that it accepts as an argument a Python function ``g``, then values stored away in ``g``'s closure will not be visible to the custom derivative rules, and attempts at AD involving these values will fail. One way around this is to convert the closure by extracting these values, and to pass them as explicit formal arguments across the custom derivative boundary. This utility carries out that conversion. More precisely, it closure-converts the function ``fun`` specialized to the types of the arguments given in ``example_args``. When we refer here to "values in the closure" of ``fun``, we do not mean the values that are captured by Python directly when ``fun`` is defined (e.g. the Python objects in ``fun.__closure__``, if the attribute exists). Rather, we mean values encountered during the execution of ``fun`` on ``example_args`` that determine its output. This may include, for instance, arrays captured transitively in Python closures, i.e. in the Python closure of functions called by ``fun``, the closures of the functions that they call, and so forth. The function ``fun`` must be a pure function. Example usage:: def minimize(objective_fn, x0): converted_fn, aux_args = closure_convert(objective_fn, x0) return _minimize(converted_fn, x0, *aux_args) @partial(custom_vjp, nondiff_argnums=(0,)) def _minimize(objective_fn, x0, *args): z = objective_fn(x0, *args) # ... find minimizer x_opt ... return x_opt def fwd(objective_fn, x0, *args): y = _minimize(objective_fn, x0, *args) return y, (y, args) def rev(objective_fn, res, g): y, args = res y_bar = g # ... custom reverse-mode AD ... return x0_bar, *args_bars _minimize.defvjp(fwd, rev) Args: fun: Python callable to be converted. Must be a pure function. example_args: Arrays, scalars, or (nested) standard Python containers (tuples, lists, dicts, namedtuples, i.e., pytrees) thereof, used to determine the types of the formal arguments to ``fun``. This type-specialized form of ``fun`` is the function that will be closure converted. Returns: A pair comprising (i) a Python callable, accepting the same arguments as ``fun`` followed by arguments corresponding to the values hoisted from its closure, and (ii) a list of values hoisted from the closure. """ flat_args, in_tree = tree_flatten(example_args) in_avals = tuple(map(core.get_aval, flat_args)) debug = debug_info("closure_convert", fun, example_args, {}) if config.check_tracer_leaks.value: return _closure_convert_for_avals.__wrapped__(fun, in_tree, in_avals, debug) else: return _closure_convert_for_avals(fun, in_tree, in_avals, debug) def _maybe_perturbed(x: Any) -> bool: # False if x can't represent an AD-perturbed value (i.e. a value # with a nontrivial tangent attached), up to heuristics, and True otherwise. # See https://github.com/jax-ml/jax/issues/6415 for motivation. if not isinstance(x, core.Tracer): # If x is not a Tracer, it can't be perturbed. return False elif isinstance(x, ad.JVPTracer) and isinstance(x.tangent, ad.Zero): return _maybe_perturbed(x.primal) elif isinstance(x, pe.DynamicJaxprTracer): # If x is a DynamicJaxprTracer then we're staging out; differentiation could # happen later, but some types always have trivial tangents. vspace = x.aval.to_tangent_aval() return not (vspace is core.abstract_token or getattr(vspace, 'dtype', None) == dtypes.float0) elif not isinstance(x, ad.JVPTracer): # If x is not a JVPTracer, recursively check its contents. return any(_maybe_perturbed(attr) for name, attr in x._contents()) else: return True # We can't be sure! @cache() def _closure_convert_for_avals(fun, in_tree, in_avals, debug_info: core.DebugInfo): wrapped_fun, out_tree = flatten_fun_nokwargs( lu.wrap_init(fun, debug_info=debug_info), in_tree) jaxpr, out_pvals, consts = pe.trace_to_jaxpr_dynamic(wrapped_fun, in_avals) out_tree = out_tree() (closure_consts, const_args), merge = partition_list(_maybe_perturbed, consts) num_consts = len(const_args) def converted_fun(*args_hconsts): num_args = len(args_hconsts) - num_consts args, const_args = split_list(args_hconsts, [num_args]) consts = merge(closure_consts, const_args) all_args, in_tree2 = tree_flatten(tuple(args)) if in_tree != in_tree2: msg = ("The inputs to the closure produced by closure_convert must have " "the same Pytree structure as the example arguments passed when " f"closure_convert was called. Expected {in_tree}, but got " f"{in_tree2}") raise TypeError(msg) out_flat = core.eval_jaxpr(jaxpr, consts, *all_args) return tree_unflatten(out_tree, out_flat) return converted_fun, const_args def partition_list(choice, lst): out = [], [] which = [out[choice(elt)].append(elt) or choice(elt) for elt in lst] def merge(l1, l2): i1, i2 = iter(l1), iter(l2) return [next(i2 if snd else i1) for snd in which] return out, merge ### Custom transposition def linear_call(fun: Callable, fun_transpose: Callable, residual_args, linear_args): """Call a linear function, with a custom implementation for its transpose. The `Haskell-like type signatures`_ of ``fun`` and ``fun_transpose`` are: .. code-block:: haskell fun :: r -> a -o b fun_transpose :: r -> b -o a where the ``-o`` arrow indicates a linear function, ``r`` is the residual input type and ``a`` is the linear input type. The functions ``fun`` and ``fun_transpose`` are coupled as transposes of one another. Specifically, the transpose of a ``linear_call`` primitive is another ``linear_call`` to ``fun_transpose``, with ``fun`` as its custom transposition. For example: >>> def f(r, x): ... return x / r >>> def t(r, t): ... return t / r >>> def div_add(x, denom): ... return x + linear_call(f, t, denom, x) >>> def transpose(f, x_example): ... def transposed(y): ... x, = jax.linear_transpose(f, x_example)(y) ... return x ... return transposed >>> div_add(9., 3.) Array(12., dtype=float32, weak_type=True) >>> transpose(partial(div_add, denom=3.), 1.)(18.) # custom Array(24., dtype=float32, weak_type=True) >>> transpose(lambda x: x + x / 3., 1.)(18.) # reference Array(24., dtype=float32, weak_type=True) The above definition of ``f`` illustrates the purpose of a residual argument: division is linear in one of its inputs (the dividend ``x``) but not the other (the divisor ``r``). As another example: >>> def custom_id(x): ... def f(_, x): return x ... def t(_, t): return 7. ... return linear_call(f, t, (), x) >>> custom_id(1.) 1.0 >>> transpose(custom_id, 1.)(1.) TypedFloat(7.0, dtype=float32) >>> transpose(transpose(custom_id, 1.), 1.)(1.) 1.0 >>> transpose(transpose(transpose(custom_id, 1.), 1.), 1.)(1.) TypedFloat(7.0, dtype=float32) Args: fun: a Python callable specifying a linear function. It should take two arguments: one of "residual" inputs (type ``r``), i.e. inputs in which the function is not necessarily linear, and one of "linear" inputs (type ``a``). It should return output whose components are linear in the linear input (type ``b``). fun_transpose: a Python callable specifying a structurally linear function that is the transpose of ``fun`` with respect to its linear inputs. Its first argument is the same residual inputs (``r``) as ``fun``. Its second argument is of type ``b``. Finally, its output is of type ``a`` and each of its component are linear in its second argument (the ``b`` inputs). residual_args: Argument in which ``fun`` and ``fun_transpose`` are not necessarily linear. Not involved in transposition. linear_args: Argument in which ``fun`` and ``fun_transpose`` are linear and with respect to which the two are transposes. Returns: The call result, i.e. ``fun(residual_args, linear_args)``. .. _Haskell-like type signatures: https://wiki.haskell.org/Type_signature """ operands_res, res_tree = tree_flatten(residual_args) operands_lin, lin_tree = tree_flatten(linear_args) f_in_tree = treedef_tuple((res_tree, lin_tree)) f, out_tree = flatten_fun_nokwargs( lu.wrap_init( fun, debug_info=debug_info("linear_call fun", fun, (residual_args, linear_args), {})), f_in_tree) res_avals = map(core.get_aval, operands_res) lin_avals = map(core.get_aval, operands_lin) f_jaxpr, f_consts = _initial_style_jaxpr(f, (*res_avals, *lin_avals)) f_jaxpr_closed = _close_jaxpr(f_jaxpr) out_avals = f_jaxpr_closed.out_avals t_in_tree = treedef_tuple((res_tree, out_tree())) t, t_out_tree = flatten_fun_nokwargs( lu.wrap_init( fun_transpose, # TODO(necula): the fun_transpose takes residual and output of fun! debug_info=debug_info("linear_call fun_transpose", fun_transpose, (residual_args, linear_args), {})), t_in_tree) @pe._memoize def transpose_thunk(): t_jaxpr, t_consts = _initial_style_jaxpr(t.with_unknown_names(), (*res_avals, *out_avals)) if t_out_tree() != lin_tree: raise TypeError( 'transpose output pytree structure must match that of linear inputs, ' f'got output structure {t_out_tree()} ' f'and input structure {lin_tree}.') return _close_jaxpr(t_jaxpr), t_consts out = linear_call_p.bind(*f_consts, *operands_res, *operands_lin, callee=f_jaxpr_closed, transpose_thunk=transpose_thunk, num_callee_consts=len(f_consts), num_res=len(operands_res)) return tree_unflatten(out_tree(), out) def _linear_call_impl(*args, callee, transpose_thunk, num_callee_consts, num_res): del transpose_thunk, num_callee_consts, num_res return core.eval_jaxpr(callee.jaxpr, (), *args) def _linear_call_jvp_rule(primals, tangents, callee, transpose_thunk, num_callee_consts, num_res): consts_and_res, primals = split_list(primals, [num_callee_consts + num_res]) const_tangents, tangents = split_list(tangents, [num_callee_consts + num_res]) assert all(type(t) is Zero for t in const_tangents) primals_out = linear_call_p.bind( *consts_and_res, *primals, callee=callee, transpose_thunk=transpose_thunk, num_callee_consts=num_callee_consts, num_res=num_res) tangents_out = linear_call_p.bind( *consts_and_res, *tangents, callee=callee, transpose_thunk=transpose_thunk, num_callee_consts=num_callee_consts, num_res=num_res) return primals_out, tangents_out def _linear_call_transpose_rule(cts, *args, callee, transpose_thunk, num_callee_consts, num_res): transpose, t_consts = transpose_thunk() f_consts, operands_res, operands_lin = split_list( args, [num_callee_consts, num_res]) _, _, cts_avals = split_list( transpose.in_avals, [len(t_consts), num_res]) assert all(ad.is_undefined_primal(x) for x in operands_lin) assert all(not ad.is_undefined_primal(x) for x in operands_res) def new_transpose_thunk(): return callee, f_consts cts = [zeros_like_aval(a) if type(ct) is Zero else ct for ct, a in zip(cts, cts_avals)] cts_out = linear_call_p.bind(*t_consts, *operands_res, *cts, callee=transpose, transpose_thunk=new_transpose_thunk, num_callee_consts=len(t_consts), num_res=len(operands_res)) return [None] * (num_callee_consts + num_res) + cts_out def _linear_call_abstract_eval(*args, **kwargs): return kwargs['callee'].out_avals linear_call_p = core.Primitive('linear_call') linear_call_p.multiple_results = True linear_call_p.def_impl(_linear_call_impl) linear_call_p.def_abstract_eval(_linear_call_abstract_eval) ad.primitive_jvps[linear_call_p] = _linear_call_jvp_rule ad.primitive_transposes[linear_call_p] = _linear_call_transpose_rule pxla.register_initial_style_primitive(linear_call_p) mlir.register_lowering(linear_call_p, mlir.lower_fun( _linear_call_impl, multiple_results=True)) # A stageable primitive that fails when evaluated unreachable_p: core.Primitive = core.Primitive('unreachable') unreachable_p.multiple_results = True def unreachable_impl(*_, out_avals, exc_type, message): del out_avals raise exc_type(message) # Evaluation raises an exception unreachable_p.def_impl(unreachable_impl) # Translation raises an exception # TODO(frostig,mattjj): We have no good way to translate a function # that errs. Since MLIR lowering over-approximates concrete evaluation, # we err on MLIR lowering for the time being. mlir.register_lowering(unreachable_p, unreachable_impl) # Abstract evaluation proceeds without issue, to allow for staging unreachable_p.def_abstract_eval(lambda *_, out_avals, **__: out_avals) def unreachable(*args, out_avals=None, exc_type=TypeError, message='unreachable'): """Fail when evaluated concretely (but allow for staging). This function allows one to assert an impossibility of evaluation. It can be used to guarantee that evaluation does not "reach" a certain point in the sense that it does not execute, but it can nonetheless be staged out by JAX without error. Args: *args: The arbitrary pytree of arguments to the function. out_avals: Optional specification of the output types of this function invocation from the point of view of staging. If ``None``, these are chosen as equal to types of input arguments. exc_type: Optional constructor for the Python exception raised if evaluated. message: Optional string message for the Python exception raised if evaluated. """ if out_avals is None: out_avals = tree_map(core.get_aval, args) args_flat, in_tree = tree_flatten(args) out_avals_flat, out_tree = tree_flatten(out_avals) out = unreachable_p.bind(*args_flat, out_avals=out_avals_flat, exc_type=exc_type, message=message) return tree_unflatten(out_tree, out) disallow_jvp = partial( unreachable, exc_type=TypeError, message="can't apply forward-mode autodiff (jvp) to a custom_vjp function.") def custom_vjp_by_custom_transpose(fun, fwd, bwd): fun = custom_jvp(fun) @fun.defjvp def jvp(primals, tangents): outs, residuals = fwd(*primals) tan_out_types = tree_map(lambda o: core.get_aval(o).to_tangent_aval(), outs) tan_fn = custom_transpose(partial(disallow_jvp, out_avals=tan_out_types)) tan_fn.def_transpose(bwd) return outs, tan_fn(tan_out_types, residuals, tangents) return fun # TODO(mattjj): remove these stubs, which exist to avoid breaking internal users custom_jvp_call_jaxpr_p = core.Primitive("custom_jvp_call_jaxpr") # The following is a helper for optimizing the behavior of custom_vjp when used # under remat. This is really only useful when the `fwd` function to custom_vjp # executes a black box kernel. Otherwise, DCE will perform this optimization # automatically. # # TODO(dfm): Eventually this should probably be the default behavior for # custom_vjp, if we can make it so that it is a no-op for most cases. Right now, # it is written in "initial-style" so it doesn't support eager mode. This was # a reasonable compromise when written because it made the implementation # simpler, but it would be worth revisiting this. def optimize_remat_of_custom_vjp_fwd( fun: Callable[..., ReturnValue], debug_fun: core.DebugInfo, fwd: Callable[..., tuple[ReturnValue, Any]], debug_fwd: core.DebugInfo, nondiff_argnums: Sequence[int] = (), symbolic_zeros: bool = False, ) -> Callable[..., tuple[ReturnValue, Any]]: if symbolic_zeros: # TODO(dfm): This probably shouldn't be too hard to support. raise NotImplementedError( "remat optimization for custom_vjp does not support symbolic zeros") @wraps(fwd) def wrapped_fwd(*args, **kwargs) -> tuple[ReturnValue, Any]: # TODO(dfm): This initial logic is duplicated from custom_vjp.__call__ # above and it would be good to consolidate it. # Note: we use `fun` instead of `fwd` here for consistency with # custom_vjp.__call__ above. args = resolve_kwargs(fun, args, kwargs) if nondiff_argnums: for i in nondiff_argnums: _check_for_tracers(args[i]) nondiff_argnums_ = set(nondiff_argnums) dyn_argnums = [i for i in range(len(args)) if i not in nondiff_argnums_] f_, dyn_args = argnums_partial(lu.wrap_init(fun, debug_info=debug_fun), dyn_argnums, args, require_static_args_hashable=False) fwd_, _ = argnums_partial(lu.wrap_init(fwd, debug_info=debug_fwd), dyn_argnums, args, require_static_args_hashable=False) else: f_, dyn_args = lu.wrap_init(fun, debug_info=debug_fun), args fwd_ = lu.wrap_init(fwd, debug_info=debug_fwd) args_flat, in_tree = tree_flatten(dyn_args) flat_fun, out_type = _flatten_fun_nokwargs(f_, in_tree) flat_fwd, out_trees = _flatten_fwd(fwd_, nondiff_argnums, False, debug_fun, debug_fwd, in_tree, out_type) flat_fwd = _fix_fwd_args(flat_fwd) in_avals = [core.get_aval(x) for x in args_flat] fwd_jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(flat_fwd.with_unknown_names(), in_avals) fwd_jaxpr = pe.close_jaxpr(pe.convert_constvars_jaxpr(fwd_jaxpr)) prim_tree, res_tree, fwds = out_trees() num_res_out = res_tree.num_leaves - sum(f is not None for f in fwds) disallowed_effects = effects.custom_derivatives_allowed_effects.filter_not_in(fwd_jaxpr.effects) if disallowed_effects: raise NotImplementedError( "remat optimization for custom_vjp does not support forward " f"functions with these side effects: {disallowed_effects}") @pe._memoize def fun_jaxpr_thunk(): jaxpr, _, consts = pe.trace_to_jaxpr_dynamic(flat_fun, in_avals) return jaxpr, consts out_flat = remat_opt_p.bind(*consts, *args_flat, num_consts=len(consts), num_res=num_res_out, fwd_jaxpr=fwd_jaxpr, fun_jaxpr_thunk=fun_jaxpr_thunk) res, out_flat = split_list(out_flat, [num_res_out]) res_ = iter(res) res = [next(res_) if f is None else args_flat[f] for f in fwds] assert next(res_, None) is None out_tree = treedef_tuple((prim_tree, res_tree)) return tree_unflatten(out_tree, (*out_flat, *res)) return wrapped_fwd @lu.transformation2 def _fix_fwd_args(f, *args): args = [(x, True) for x in args] args = [x for pair in args for x in pair] return f(*args) def _remat_opt_impl( *args, num_consts: int, num_res: int, fwd_jaxpr: core.ClosedJaxpr, fun_jaxpr_thunk: Callable[[], core.ClosedJaxpr], ): del num_consts, num_res, fun_jaxpr_thunk # unused return core.jaxpr_as_fun(fwd_jaxpr)(*args) def _remat_opt_abstract_eval(*args, fwd_jaxpr: core.ClosedJaxpr, **_): del args return fwd_jaxpr.out_avals, fwd_jaxpr.effects def _remat_opt_vmap( axis_data, args, in_dims, *, num_consts: int, num_res: int, fwd_jaxpr: core.ClosedJaxpr, fun_jaxpr_thunk: Callable[[], core.ClosedJaxpr], ): args = [batching.moveaxis(x, d, 0) if d is not not_mapped and d != 0 else x for x, d in zip(args, in_dims)] in_batched = [d is not not_mapped for d in in_dims] batched_fwd_jaxpr, out_batched = batching.batch_jaxpr( fwd_jaxpr, axis_data, in_batched, False) extra_consts = batched_fwd_jaxpr.consts batched_fwd_jaxpr = pe.close_jaxpr( pe.convert_constvars_jaxpr(batched_fwd_jaxpr.jaxpr)) out_dims = [0 if b else not_mapped for b in out_batched] _, prim_batched = split_list(in_batched, [num_consts]) @pe._memoize def batched_fun_jaxpr_thunk(): fun_jaxpr = core.ClosedJaxpr(*fun_jaxpr_thunk()) batched_fun_jaxpr, out_batched = batching.batch_jaxpr( fun_jaxpr, axis_data, prim_batched, False) return batched_fun_jaxpr.jaxpr, batched_fun_jaxpr.consts batched_outs = remat_opt_p.bind(*extra_consts, *args, num_consts=num_consts + len(extra_consts), num_res=num_res, fwd_jaxpr=batched_fwd_jaxpr, fun_jaxpr_thunk=batched_fun_jaxpr_thunk) return batched_outs, out_dims def _remat_opt_jvp( primals, tangents, *, num_consts: int, num_res: int, fwd_jaxpr: core.ClosedJaxpr, fun_jaxpr_thunk: Callable[[], core.ClosedJaxpr], ): consts, primals = split_list(primals, [num_consts]) consts_dot, tangents = split_list(tangents, [num_consts]) # Tangents must be instantated in case we end up DCEing later. tangents = map(ad.instantiate_zeros, tangents) consts_nz = [not isinstance(t, Zero) for t in consts_dot] consts_dot = [c for nz, c in zip(consts_nz, consts_dot) if nz] in_nz = consts_nz + [True] * len(tangents) fwd_jaxpr_jvp_, out_nz = ad.jvp_jaxpr(fwd_jaxpr, in_nz, True) num_out = len(out_nz) - num_res fwd_jaxpr_jvp_ = ad.rearrange_binders( fwd_jaxpr_jvp_, [num_consts, len(primals)], [len(consts_dot), len(tangents)], [num_res, num_out], [num_res, num_out]) fwd_jaxpr_jvp = pe.close_jaxpr(pe.convert_constvars_jaxpr(fwd_jaxpr_jvp_.jaxpr)) # @pe._memoize def fun_jvp_jaxpr_thunk(): fun_jaxpr = core.ClosedJaxpr(*fun_jaxpr_thunk()) in_nz = [True] * len(primals) fun_jvp_jaxpr, _ = ad.jvp_jaxpr(fun_jaxpr, in_nz, True) return fun_jvp_jaxpr.jaxpr, fun_jvp_jaxpr.consts new_num_consts = len(fwd_jaxpr_jvp_.consts) + num_consts + len(consts_dot) outs = remat_opt_p.bind(*fwd_jaxpr_jvp_.consts, *consts, *consts_dot, *primals, *tangents, num_consts=new_num_consts, num_res=2 * num_res, fwd_jaxpr=fwd_jaxpr_jvp, fun_jaxpr_thunk=fun_jvp_jaxpr_thunk) res, res_dot, outs, outs_dot = split_list(outs, [num_res, num_res, num_out]) return (*res, *outs), (*res_dot, *outs_dot) def _remat_opt_transpose( cts, *args, num_consts: int, num_res: int, fwd_jaxpr: core.ClosedJaxpr, fun_jaxpr_thunk: Callable[[], core.ClosedJaxpr], ): # TODO(dfm): It shouldn't be too hard to implement this as needed in the # future. raise NotImplementedError( "remat optimization for custom_vjp does not support higher-order AD") def _remat_opt_dce(used_outs: list[bool], eqn: core.JaxprEqn): if not any(used_outs) and not pe.has_effects(eqn): return [False] * len(eqn.invars), None used_res, used_prims = split_list(used_outs, [eqn.params["num_res"]]) outvars = [v for used, v in zip(used_outs, eqn.outvars) if used] if any(used_res): # If any of the residuals are used, we still need to run fwd at this point, # but we may end up DCEing again in the future, so we must instantiate all # the input primals. instantiate = [False] * eqn.params["num_consts"] instantiate += [True] * (len(eqn.invars) - eqn.params["num_consts"]) new_jaxpr, used_ins = pe.dce_jaxpr(eqn.params["fwd_jaxpr"].jaxpr, used_outs, instantiate=instantiate) assert not new_jaxpr.constvars closed_jaxpr = pe.close_jaxpr(new_jaxpr) invars = [v for used, v in zip(used_ins, eqn.invars) if used] new_params = dict(eqn.params) new_num_consts = sum(split_list(used_ins, [eqn.params["num_consts"]])[0]) new_params["num_consts"] = new_num_consts new_params["fwd_jaxpr"] = closed_jaxpr new_params["num_res"] = sum(used_res) new_eqn = pe.new_jaxpr_eqn( invars, outvars, remat_opt_p, new_params, closed_jaxpr.effects, eqn.source_info, eqn.ctx) return used_ins, new_eqn else: # If none of the residuals are used, we run the primal computation instead. # At this point we drop this custom DCE behavior, but since the primal might # have different consts than fwd, we build a new JaxprEqn with a closed_call # primitive. fun_jaxpr, consts = eqn.params["fun_jaxpr_thunk"]() new_jaxpr, used_consts, used_ins = pe.dce_jaxpr_consts(fun_jaxpr, used_prims) consts = [c for used, c in zip(used_consts, consts) if used] closed_jaxpr = core.ClosedJaxpr(new_jaxpr, consts) _, invars = split_list(eqn.invars, [eqn.params["num_consts"]]) invars = [v for used, v in zip(used_ins, invars) if used] new_eqn = pe.new_jaxpr_eqn( invars, outvars, core.closed_call_p, dict(call_jaxpr=closed_jaxpr), closed_jaxpr.effects, eqn.source_info, eqn.ctx) used_ins = [False] * eqn.params["num_consts"] + used_ins return used_ins, new_eqn remat_opt_p = core.Primitive("remat_opt") remat_opt_p.multiple_results = True remat_opt_p.def_impl(_remat_opt_impl) remat_opt_p.def_effectful_abstract_eval(_remat_opt_abstract_eval) pxla.register_initial_style_primitive(remat_opt_p) mlir.register_lowering(remat_opt_p, mlir.lower_fun( _remat_opt_impl, multiple_results=True)) batching.fancy_primitive_batchers[remat_opt_p] = _remat_opt_vmap ad.primitive_jvps[remat_opt_p] = _remat_opt_jvp ad.primitive_transposes[remat_opt_p] = _remat_opt_transpose pe.dce_rules[remat_opt_p] = _remat_opt_dce
Residuals
python
doocs__leetcode
solution/0700-0799/0792.Number of Matching Subsequences/Solution.py
{ "start": 0, "end": 421 }
class ____: def numMatchingSubseq(self, s: str, words: List[str]) -> int: d = defaultdict(deque) for w in words: d[w[0]].append(w) ans = 0 for c in s: for _ in range(len(d[c])): t = d[c].popleft() if len(t) == 1: ans += 1 else: d[t[1]].append(t[1:]) return ans
Solution
python
scrapy__scrapy
tests/test_core_downloader.py
{ "start": 1176, "end": 1372 }
class ____: def test_repr(self): slot = Slot(concurrency=8, delay=0.1, randomize_delay=True) assert repr(slot) == "Slot(concurrency=8, delay=0.10, randomize_delay=True)"
TestSlot
python
run-llama__llama_index
llama-index-core/llama_index/core/query_engine/custom.py
{ "start": 531, "end": 2974 }
class ____(BaseModel, BaseQueryEngine): """ Custom query engine. Subclasses can define additional attributes as Pydantic fields. Subclasses must implement the `custom_query` method, which takes a query string and returns either a Response object or a string as output. They can optionally implement the `acustom_query` method for async support. """ model_config = ConfigDict(arbitrary_types_allowed=True) callback_manager: CallbackManager = Field( default_factory=lambda: CallbackManager([]), exclude=True ) def _get_prompt_modules(self) -> PromptMixinType: """Get prompt sub-modules.""" return {} def query(self, str_or_query_bundle: QueryType) -> RESPONSE_TYPE: with self.callback_manager.as_trace("query"): # if query bundle, just run the query if isinstance(str_or_query_bundle, QueryBundle): query_str = str_or_query_bundle.query_str else: query_str = str_or_query_bundle raw_response = self.custom_query(query_str) return ( Response(raw_response) if isinstance(raw_response, str) else raw_response ) async def aquery(self, str_or_query_bundle: QueryType) -> RESPONSE_TYPE: with self.callback_manager.as_trace("query"): if isinstance(str_or_query_bundle, QueryBundle): query_str = str_or_query_bundle.query_str else: query_str = str_or_query_bundle raw_response = await self.acustom_query(query_str) return ( Response(raw_response) if isinstance(raw_response, str) else raw_response ) @abstractmethod def custom_query(self, query_str: str) -> STR_OR_RESPONSE_TYPE: """Run a custom query.""" async def acustom_query(self, query_str: str) -> STR_OR_RESPONSE_TYPE: """Run a custom query asynchronously.""" # by default, just run the synchronous version return self.custom_query(query_str) def _query(self, query_bundle: QueryBundle) -> RESPONSE_TYPE: raise NotImplementedError("This query engine does not support _query.") async def _aquery(self, query_bundle: QueryBundle) -> RESPONSE_TYPE: raise NotImplementedError("This query engine does not support _aquery.")
CustomQueryEngine
python
davidhalter__jedi
test/examples/inheritance/pkg/__init__.py
{ "start": 26, "end": 74 }
class ____(Bar): def foo(self): pass
Foo
python
pandas-dev__pandas
scripts/tests/test_validate_docstrings.py
{ "start": 10791, "end": 15830 }
class ____: def test_exit_status_for_main(self, monkeypatch) -> None: monkeypatch.setattr( validate_docstrings, "pandas_validate", lambda func_name: { "docstring": "docstring1", "errors": [ ("ER01", "err desc"), ("ER02", "err desc"), ("ER03", "err desc"), ], "examples_errs": "", }, ) exit_status = validate_docstrings.main( func_name="docstring1", prefix=None, output_format="default", ignore_deprecated=False, ignore_errors={}, ) assert exit_status == 3 def test_exit_status_errors_for_validate_all(self, monkeypatch) -> None: monkeypatch.setattr( validate_docstrings, "validate_all", lambda prefix, ignore_deprecated=False, ignore_functions=None: { "docstring1": { "errors": [ ("ER01", "err desc"), ("ER02", "err desc"), ("ER03", "err desc"), ], "file": "module1.py", "file_line": 23, }, "docstring2": { "errors": [("ER04", "err desc"), ("ER05", "err desc")], "file": "module2.py", "file_line": 925, }, }, ) exit_status = validate_docstrings.main( func_name=None, prefix=None, output_format="default", ignore_deprecated=False, ignore_errors={}, ) assert exit_status == 5 def test_no_exit_status_noerrors_for_validate_all(self, monkeypatch) -> None: monkeypatch.setattr( validate_docstrings, "validate_all", lambda prefix, ignore_deprecated=False, ignore_functions=None: { "docstring1": {"errors": [], "warnings": [("WN01", "warn desc")]}, "docstring2": {"errors": []}, }, ) exit_status = validate_docstrings.main( func_name=None, output_format="default", prefix=None, ignore_deprecated=False, ignore_errors={}, ) assert exit_status == 0 def test_exit_status_for_validate_all_json(self, monkeypatch) -> None: monkeypatch.setattr( validate_docstrings, "validate_all", lambda prefix, ignore_deprecated=False, ignore_functions=None: { "docstring1": { "errors": [ ("ER01", "err desc"), ("ER02", "err desc"), ("ER03", "err desc"), ] }, "docstring2": {"errors": [("ER04", "err desc"), ("ER05", "err desc")]}, }, ) exit_status = validate_docstrings.main( func_name=None, output_format="json", prefix=None, ignore_deprecated=False, ignore_errors={}, ) assert exit_status == 0 def test_errors_param_filters_errors(self, monkeypatch) -> None: monkeypatch.setattr( validate_docstrings, "validate_all", lambda prefix, ignore_deprecated=False, ignore_functions=None: { "Series.foo": { "errors": [ ("ER01", "err desc"), ("ER02", "err desc"), ("ER03", "err desc"), ], "file": "series.py", "file_line": 142, }, "DataFrame.bar": { "errors": [("ER01", "err desc"), ("ER02", "err desc")], "file": "frame.py", "file_line": 598, }, "Series.foobar": { "errors": [("ER01", "err desc")], "file": "series.py", "file_line": 279, }, }, ) monkeypatch.setattr( validate_docstrings, "ERROR_MSGS", { "ER01": "err desc", "ER02": "err desc", "ER03": "err desc", }, ) exit_status = validate_docstrings.main( func_name=None, output_format="default", prefix=None, ignore_deprecated=False, ignore_errors={None: {"ER02", "ER03"}}, ) assert exit_status == 3 exit_status = validate_docstrings.main( func_name=None, output_format="default", prefix=None, ignore_deprecated=False, ignore_errors={None: {"ER01", "ER02"}}, ) assert exit_status == 1
TestMainFunction
python
has2k1__plotnine
plotnine/mapping/_atomic.py
{ "start": 2552, "end": 4029 }
class ____(ae_value[ShapeType]): """ A single shape value """ def __post_init__(self): from matplotlib.path import Path from ..scales.scale_shape import FILLED_SHAPES, UNFILLED_SHAPES value = self.value with suppress(TypeError): if value in (FILLED_SHAPES | UNFILLED_SHAPES): return if isinstance(value, Path): return # tuple of the form (numsides, style, angle) # where style is in the range [0, 3] # e.g (4, 1, 45) if ( isinstance(value, tuple) and len(value) == 3 and isinstance(value[0], int) and value[1] in (0, 1, 2) and isinstance(value[2], (float, int)) ): return if is_shape_points(value): self.value = tuple(value) # pyright: ignore[reportAttributeAccessIssue] return raise ValueError(f"{value} is not a known shape.") def is_shape_points(obj: Any) -> bool: """ Return True if obj is like Sequence[tuple[float, float]] """ def is_numeric(obj) -> bool: """ Return True if obj is a python or numpy float or integer """ return isinstance(obj, (float, int, np.floating, np.integer)) if not iter(obj): return False try: return all(is_numeric(a) and is_numeric(b) for a, b in obj) except (ValueError, TypeError): return False
shape
python
HypothesisWorks__hypothesis
hypothesis-python/tests/codemods/test_codemods.py
{ "start": 4745, "end": 5399 }
class ____(CodemodTest): TRANSFORM = codemods.HypothesisFixHealthCheckAll def test_noop_other_attributes(self): # Test that calls to other attributes of HealthCheck are not modified before = "result = HealthCheck.data_too_large" self.assertCodemod(before=before, after=before) def test_substitution(self) -> None: # Test that HealthCheck.all() is replaced with list(HealthCheck) before = "result = HealthCheck.all()" after = "result = list(HealthCheck)" # self.assertEqual(run_codemod(input_code), expected_code) self.assertCodemod(before=before, after=after)
TestHealthCheckAll
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/env_vars.py
{ "start": 1358, "end": 1535 }
class ____(graphene.ObjectType): results = non_null_list(GrapheneEnvVarWithConsumers) class Meta: name = "EnvVarWithConsumersList"
GrapheneEnvVarWithConsumersList
python
scrapy__scrapy
tests/test_exporters.py
{ "start": 21943, "end": 22084 }
class ____(TestJsonItemExporter): item_class = MyDataClass custom_field_item_class = CustomFieldDataclass
TestJsonItemExporterDataclass
python
pallets__flask
src/flask/debughelpers.py
{ "start": 1591, "end": 6070 }
class ____(AssertionError): """This exception is raised in debug mode if a routing redirect would cause the browser to drop the method or body. This happens when method is not GET, HEAD or OPTIONS and the status code is not 307 or 308. """ def __init__(self, request: Request) -> None: exc = request.routing_exception assert isinstance(exc, RequestRedirect) buf = [ f"A request was sent to '{request.url}', but routing issued" f" a redirect to the canonical URL '{exc.new_url}'." ] if f"{request.base_url}/" == exc.new_url.partition("?")[0]: buf.append( " The URL was defined with a trailing slash. Flask" " will redirect to the URL with a trailing slash if it" " was accessed without one." ) buf.append( " Send requests to the canonical URL, or use 307 or 308 for" " routing redirects. Otherwise, browsers will drop form" " data.\n\n" "This exception is only raised in debug mode." ) super().__init__("".join(buf)) def attach_enctype_error_multidict(request: Request) -> None: """Patch ``request.files.__getitem__`` to raise a descriptive error about ``enctype=multipart/form-data``. :param request: The request to patch. :meta private: """ oldcls = request.files.__class__ class newcls(oldcls): # type: ignore[valid-type, misc] def __getitem__(self, key: str) -> t.Any: try: return super().__getitem__(key) except KeyError as e: if key not in request.form: raise raise DebugFilesKeyError(request, key).with_traceback( e.__traceback__ ) from None newcls.__name__ = oldcls.__name__ newcls.__module__ = oldcls.__module__ request.files.__class__ = newcls def _dump_loader_info(loader: BaseLoader) -> t.Iterator[str]: yield f"class: {type(loader).__module__}.{type(loader).__name__}" for key, value in sorted(loader.__dict__.items()): if key.startswith("_"): continue if isinstance(value, (tuple, list)): if not all(isinstance(x, str) for x in value): continue yield f"{key}:" for item in value: yield f" - {item}" continue elif not isinstance(value, (str, int, float, bool)): continue yield f"{key}: {value!r}" def explain_template_loading_attempts( app: App, template: str, attempts: list[ tuple[ BaseLoader, Scaffold, tuple[str, str | None, t.Callable[[], bool] | None] | None, ] ], ) -> None: """This should help developers understand what failed""" info = [f"Locating template {template!r}:"] total_found = 0 blueprint = None if (ctx := _cv_app.get(None)) is not None and ctx.has_request: blueprint = ctx.request.blueprint for idx, (loader, srcobj, triple) in enumerate(attempts): if isinstance(srcobj, App): src_info = f"application {srcobj.import_name!r}" elif isinstance(srcobj, Blueprint): src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})" else: src_info = repr(srcobj) info.append(f"{idx + 1:5}: trying loader of {src_info}") for line in _dump_loader_info(loader): info.append(f" {line}") if triple is None: detail = "no match" else: detail = f"found ({triple[1] or '<string>'!r})" total_found += 1 info.append(f" -> {detail}") seems_fishy = False if total_found == 0: info.append("Error: the template could not be found.") seems_fishy = True elif total_found > 1: info.append("Warning: multiple loaders returned a match for the template.") seems_fishy = True if blueprint is not None and seems_fishy: info.append( " The template was looked up from an endpoint that belongs" f" to the blueprint {blueprint!r}." ) info.append(" Maybe you did not place a template in the right folder?") info.append(" See https://flask.palletsprojects.com/blueprints/#templates") app.logger.info("\n".join(info))
FormDataRoutingRedirect
python
python__mypy
mypyc/test/test_optimizations.py
{ "start": 2064, "end": 2256 }
class ____(OptimizationSuite): files = ["opt-flag-elimination.test"] def do_optimizations(self, fn: FuncIR) -> None: do_flag_elimination(fn, CompilerOptions())
TestFlagElimination
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 20386, "end": 21398 }
class ____(GatherDepDoneEvent): """class:`GatherDep` instruction terminated: generic error raised (not a network failure); e.g. data failed to deserialize. """ exception: Serialize traceback: Serialize | None exception_text: str traceback_text: str __slots__ = tuple(__annotations__) def _after_from_dict(self) -> None: self.exception = Serialize(Exception()) self.traceback = None @classmethod def from_exception( cls, err: BaseException, *, worker: str, total_nbytes: int, stimulus_id: str, ) -> GatherDepFailureEvent: msg = error_message(err) return cls( worker=worker, total_nbytes=total_nbytes, exception=msg["exception"], traceback=msg["traceback"], exception_text=msg["exception_text"], traceback_text=msg["traceback_text"], stimulus_id=stimulus_id, ) @dataclass
GatherDepFailureEvent
python
kamyu104__LeetCode-Solutions
Python/find-subtree-sizes-after-changes.py
{ "start": 1124, "end": 1831 }
class ____(object): def findSubtreeSizes(self, parent, s): """ :type parent: List[int] :type s: str :rtype: List[int] """ def dfs(u): lookup[ord(s[u])-ord('a')].append(u) for v in adj[u]: dfs(v) result[lookup[ord(s[v])-ord('a')][-1] if lookup[ord(s[v])-ord('a')] else u] += result[v] lookup[ord(s[u])-ord('a')].pop() adj = [[] for _ in xrange(len(parent))] for v, u in enumerate(parent): if u != -1: adj[u].append(v) lookup = [[] for _ in xrange(26)] result = [1]*len(parent) dfs(0) return result
Solution2
python
openai__openai-python
src/openai/types/vector_store_search_response.py
{ "start": 408, "end": 1156 }
class ____(BaseModel): attributes: Optional[Dict[str, Union[str, float, bool]]] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters, booleans, or numbers. """ content: List[Content] """Content chunks from the file.""" file_id: str """The ID of the vector store file.""" filename: str """The name of the vector store file.""" score: float """The similarity score for the result."""
VectorStoreSearchResponse
python
spyder-ide__spyder
external-deps/qtconsole/qtconsole/qtconsoleapp.py
{ "start": 16752, "end": 17253 }
class ____(JupyterQtConsoleApp): def __init__(self, *a, **kw): warn("IPythonQtConsoleApp is deprecated; use JupyterQtConsoleApp", DeprecationWarning) super().__init__(*a, **kw) # ----------------------------------------------------------------------------- # Main entry point # ----------------------------------------------------------------------------- def main(): JupyterQtConsoleApp.launch_instance() if __name__ == '__main__': main()
IPythonQtConsoleApp
python
astropy__astropy
astropy/utils/exceptions.py
{ "start": 1166, "end": 1493 }
class ____(AstropyWarning): """ A warning class indicating a change in astropy that is incompatible with previous versions. The suggested procedure is to issue this warning for the version in which the change occurs, and remove it for all following versions. """
AstropyBackwardsIncompatibleChangeWarning
python
paramiko__paramiko
paramiko/transport.py
{ "start": 127124, "end": 128149 }
class ____: def __init__(self): # (id -> Channel) self._map = weakref.WeakValueDictionary() self._lock = threading.Lock() def put(self, chanid, chan): self._lock.acquire() try: self._map[chanid] = chan finally: self._lock.release() def get(self, chanid): self._lock.acquire() try: return self._map.get(chanid, None) finally: self._lock.release() def delete(self, chanid): self._lock.acquire() try: try: del self._map[chanid] except KeyError: pass finally: self._lock.release() def values(self): self._lock.acquire() try: return list(self._map.values()) finally: self._lock.release() def __len__(self): self._lock.acquire() try: return len(self._map) finally: self._lock.release()
ChannelMap
python
getsentry__sentry
src/sentry/web/frontend/sudo.py
{ "start": 375, "end": 1607 }
class ____(BaseSudoView): template_name = "sentry/account/sudo.html" def handle_sudo(self, request: HttpRequest, context: dict[str, Any]) -> bool: if super().handle_sudo(request, context): return True if not request.user.is_authenticated: return False try: interface = Authenticator.objects.get_interface(request.user, "u2f") assert isinstance(interface, U2fInterface), "Must be U2F interface to check if enrolled" if not interface.is_enrolled(): raise LookupError() except LookupError: return False challenge = interface.activate(request).challenge if request.method == "POST": if "challenge" in request.POST and "response" in request.POST: try: challenge = json.loads(request.POST["challenge"]) response = json.loads(request.POST["response"]) except ValueError: pass else: if interface.validate_response(request, challenge, response): return True context["u2f_challenge"] = challenge return False
SudoView
python
huggingface__transformers
src/transformers/models/unispeech_sat/modeling_unispeech_sat.py
{ "start": 60086, "end": 64393 }
class ____(UniSpeechSatPreTrainedModel): def __init__(self, config): super().__init__(config) if hasattr(config, "add_adapter") and config.add_adapter: raise ValueError( "Audio frame classification does not support the use of UniSpeechSat adapters (config.add_adapter=True)" ) self.unispeech_sat = UniSpeechSatModel(config) num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings if config.use_weighted_layer_sum: self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers) self.classifier = nn.Linear(config.hidden_size, config.num_labels) self.num_labels = config.num_labels self.post_init() def freeze_feature_encoder(self): """ Calling this function will disable the gradient computation for the feature encoder so that its parameter will not be updated during training. """ self.unispeech_sat.feature_extractor._freeze_parameters() def freeze_base_model(self): """ Calling this function will disable the gradient computation for the base model so that its parameters will not be updated during training. Only the classification head will be updated. """ for param in self.unispeech_sat.parameters(): param.requires_grad = False @auto_docstring def forward( self, input_values: Optional[torch.Tensor], attention_mask: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, TokenClassifierOutput]: r""" input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library (`pip install torchcodec`) or the soundfile library (`pip install soundfile`). To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion into a tensor of type `torch.FloatTensor`. See [`UniSpeechSatProcessor.__call__`] for details. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states outputs = self.unispeech_sat( input_values, attention_mask=attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) if self.config.use_weighted_layer_sum: hidden_states = outputs[_HIDDEN_STATES_START_POSITION] hidden_states = torch.stack(hidden_states, dim=1) norm_weights = nn.functional.softmax(self.layer_weights, dim=-1) hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1) else: hidden_states = outputs[0] logits = self.classifier(hidden_states) loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), torch.argmax(labels.view(-1, self.num_labels), axis=1)) if not return_dict: output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:] return output return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
UniSpeechSatForAudioFrameClassification
python
networkx__networkx
networkx/algorithms/tests/test_planarity.py
{ "start": 174, "end": 12066 }
class ____: """Nose Unit tests for the :mod:`networkx.algorithms.planarity` module. Tests three things: 1. Check that the result is correct (returns planar if and only if the graph is actually planar) 2. In case a counter example is returned: Check if it is correct 3. In case an embedding is returned: Check if its actually an embedding """ @staticmethod def check_graph(G, is_planar=None): """Raises an exception if the lr_planarity check returns a wrong result Parameters ---------- G : NetworkX graph is_planar : bool The expected result of the planarity check. If set to None only counter example or embedding are verified. """ # obtain results of planarity check is_planar_lr, result = nx.check_planarity(G, True) is_planar_lr_rec, result_rec = check_planarity_recursive(G, True) if is_planar is not None: # set a message for the assert if is_planar: msg = "Wrong planarity check result. Should be planar." else: msg = "Wrong planarity check result. Should be non-planar." # check if the result is as expected assert is_planar == is_planar_lr, msg assert is_planar == is_planar_lr_rec, msg if is_planar_lr: # check embedding check_embedding(G, result) check_embedding(G, result_rec) else: # check counter example check_counterexample(G, result) check_counterexample(G, result_rec) def test_simple_planar_graph(self): e = [ (1, 2), (2, 3), (3, 4), (4, 6), (6, 7), (7, 1), (1, 5), (5, 2), (2, 4), (4, 5), (5, 7), ] self.check_graph(nx.Graph(e), is_planar=True) def test_planar_with_selfloop(self): e = [ (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (1, 2), (1, 3), (1, 5), (2, 5), (2, 4), (3, 4), (3, 5), (4, 5), ] self.check_graph(nx.Graph(e), is_planar=True) def test_k3_3(self): self.check_graph(nx.complete_bipartite_graph(3, 3), is_planar=False) def test_k5(self): self.check_graph(nx.complete_graph(5), is_planar=False) def test_multiple_components_planar(self): e = [(1, 2), (2, 3), (3, 1), (4, 5), (5, 6), (6, 4)] self.check_graph(nx.Graph(e), is_planar=True) def test_multiple_components_non_planar(self): G = nx.complete_graph(5) # add another planar component to the non planar component # G stays non planar G.add_edges_from([(6, 7), (7, 8), (8, 6)]) self.check_graph(G, is_planar=False) def test_non_planar_with_selfloop(self): G = nx.complete_graph(5) # add self loops for i in range(5): G.add_edge(i, i) self.check_graph(G, is_planar=False) def test_non_planar1(self): # tests a graph that has no subgraph directly isomorph to K5 or K3_3 e = [ (1, 5), (1, 6), (1, 7), (2, 6), (2, 3), (3, 5), (3, 7), (4, 5), (4, 6), (4, 7), ] self.check_graph(nx.Graph(e), is_planar=False) def test_loop(self): # test a graph with a selfloop e = [(1, 2), (2, 2)] G = nx.Graph(e) self.check_graph(G, is_planar=True) def test_comp(self): # test multiple component graph e = [(1, 2), (3, 4)] G = nx.Graph(e) G.remove_edge(1, 2) self.check_graph(G, is_planar=True) def test_goldner_harary(self): # test goldner-harary graph (a maximal planar graph) e = [ (1, 2), (1, 3), (1, 4), (1, 5), (1, 7), (1, 8), (1, 10), (1, 11), (2, 3), (2, 4), (2, 6), (2, 7), (2, 9), (2, 10), (2, 11), (3, 4), (4, 5), (4, 6), (4, 7), (5, 7), (6, 7), (7, 8), (7, 9), (7, 10), (8, 10), (9, 10), (10, 11), ] G = nx.Graph(e) self.check_graph(G, is_planar=True) def test_planar_multigraph(self): G = nx.MultiGraph([(1, 2), (1, 2), (1, 2), (1, 2), (2, 3), (3, 1)]) self.check_graph(G, is_planar=True) def test_non_planar_multigraph(self): G = nx.MultiGraph(nx.complete_graph(5)) G.add_edges_from([(1, 2)] * 5) self.check_graph(G, is_planar=False) def test_planar_digraph(self): G = nx.DiGraph([(1, 2), (2, 3), (2, 4), (4, 1), (4, 2), (1, 4), (3, 2)]) self.check_graph(G, is_planar=True) def test_non_planar_digraph(self): G = nx.DiGraph(nx.complete_graph(5)) G.remove_edge(1, 2) G.remove_edge(4, 1) self.check_graph(G, is_planar=False) def test_single_component(self): # Test a graph with only a single node G = nx.Graph() G.add_node(1) self.check_graph(G, is_planar=True) def test_graph1(self): G = nx.Graph( [ (3, 10), (2, 13), (1, 13), (7, 11), (0, 8), (8, 13), (0, 2), (0, 7), (0, 10), (1, 7), ] ) self.check_graph(G, is_planar=True) def test_graph2(self): G = nx.Graph( [ (1, 2), (4, 13), (0, 13), (4, 5), (7, 10), (1, 7), (0, 3), (2, 6), (5, 6), (7, 13), (4, 8), (0, 8), (0, 9), (2, 13), (6, 7), (3, 6), (2, 8), ] ) self.check_graph(G, is_planar=False) def test_graph3(self): G = nx.Graph( [ (0, 7), (3, 11), (3, 4), (8, 9), (4, 11), (1, 7), (1, 13), (1, 11), (3, 5), (5, 7), (1, 3), (0, 4), (5, 11), (5, 13), ] ) self.check_graph(G, is_planar=False) def test_counterexample_planar(self): with pytest.raises(nx.NetworkXException): # Try to get a counterexample of a planar graph G = nx.Graph() G.add_node(1) get_counterexample(G) def test_counterexample_planar_recursive(self): with pytest.raises(nx.NetworkXException): # Try to get a counterexample of a planar graph G = nx.Graph() G.add_node(1) get_counterexample_recursive(G) def test_edge_removal_from_planar_embedding(self): # PlanarEmbedding.check_structure() must succeed after edge removal edges = ((0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2), (0, 3)) G = nx.Graph(edges) cert, P = nx.check_planarity(G) assert cert is True P.remove_edge(0, 2) self.check_graph(P, is_planar=True) P.add_half_edge_ccw(1, 3, 2) P.add_half_edge_cw(3, 1, 2) self.check_graph(P, is_planar=True) P.remove_edges_from(((0, 3), (1, 3))) self.check_graph(P, is_planar=True) @pytest.mark.parametrize("graph_type", (nx.Graph, nx.MultiGraph)) def test_graph_planar_embedding_to_undirected(self, graph_type): G = graph_type([(0, 1), (0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]) is_planar, P = nx.check_planarity(G) assert is_planar U = P.to_undirected() assert isinstance(U, nx.Graph) assert all((d == {} for _, _, d in U.edges(data=True))) @pytest.mark.parametrize( "reciprocal, as_view", [(True, True), (True, False), (False, True)] ) def test_planar_embedding_to_undirected_invalid_parameters( self, reciprocal, as_view ): G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0), (0, 2)]) is_planar, P = nx.check_planarity(G) assert is_planar with pytest.raises(ValueError, match="is not supported for PlanarEmbedding."): P.to_undirected(reciprocal=reciprocal, as_view=as_view) def check_embedding(G, embedding): """Raises an exception if the combinatorial embedding is not correct Parameters ---------- G : NetworkX graph embedding : a dict mapping nodes to a list of edges This specifies the ordering of the outgoing edges from a node for a combinatorial embedding Notes ----- Checks the following things: - The type of the embedding is correct - The nodes and edges match the original graph - Every half edge has its matching opposite half edge - No intersections of edges (checked by Euler's formula) """ if not isinstance(embedding, nx.PlanarEmbedding): raise nx.NetworkXException("Bad embedding. Not of type nx.PlanarEmbedding") # Check structure embedding.check_structure() # Check that graphs are equivalent assert set(G.nodes) == set(embedding.nodes), ( "Bad embedding. Nodes don't match the original graph." ) # Check that the edges are equal g_edges = set() for edge in G.edges: if edge[0] != edge[1]: g_edges.add((edge[0], edge[1])) g_edges.add((edge[1], edge[0])) assert g_edges == set(embedding.edges), ( "Bad embedding. Edges don't match the original graph." ) def check_counterexample(G, sub_graph): """Raises an exception if the counterexample is wrong. Parameters ---------- G : NetworkX graph subdivision_nodes : set A set of nodes inducing a subgraph as a counterexample """ # 1. Create the sub graph sub_graph = nx.Graph(sub_graph) # 2. Remove self loops for u in sub_graph: if sub_graph.has_edge(u, u): sub_graph.remove_edge(u, u) # keep track of nodes we might need to contract contract = list(sub_graph) # 3. Contract Edges while len(contract) > 0: contract_node = contract.pop() if contract_node not in sub_graph: # Node was already contracted continue degree = sub_graph.degree[contract_node] # Check if we can remove the node if degree == 2: # Get the two neighbors neighbors = iter(sub_graph[contract_node]) u = next(neighbors) v = next(neighbors) # Save nodes for later contract.append(u) contract.append(v) # Contract edge sub_graph.remove_node(contract_node) sub_graph.add_edge(u, v) # 4. Check for isomorphism with K5 or K3_3 graphs if len(sub_graph) == 5: if not nx.is_isomorphic(nx.complete_graph(5), sub_graph): raise nx.NetworkXException("Bad counter example.") elif len(sub_graph) == 6: if not nx.is_isomorphic(nx.complete_bipartite_graph(3, 3), sub_graph): raise nx.NetworkXException("Bad counter example.") else: raise nx.NetworkXException("Bad counter example.")
TestLRPlanarity
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_ssm.py
{ "start": 2030, "end": 4863 }
class ____: def test_serialization(self): trigger = SsmRunCommandTrigger(command_id=COMMAND_ID) classpath, kwargs = trigger.serialize() assert classpath == BASE_TRIGGER_CLASSPATH + "SsmRunCommandTrigger" assert kwargs.get("command_id") == COMMAND_ID def test_serialization_with_region(self): """Test that region_name and other AWS parameters are properly serialized.""" trigger = SsmRunCommandTrigger( command_id=COMMAND_ID, region_name="us-east-1", aws_conn_id="test_conn", verify=True, botocore_config={"retries": {"max_attempts": 3}}, ) classpath, kwargs = trigger.serialize() assert classpath == BASE_TRIGGER_CLASSPATH + "SsmRunCommandTrigger" assert kwargs.get("command_id") == COMMAND_ID assert kwargs.get("region_name") == "us-east-1" assert kwargs.get("aws_conn_id") == "test_conn" assert kwargs.get("verify") is True assert kwargs.get("botocore_config") == {"retries": {"max_attempts": 3}} @pytest.mark.asyncio @mock.patch.object(SsmHook, "get_async_conn") @mock.patch.object(SsmHook, "get_waiter") async def test_run_success(self, mock_get_waiter, mock_get_async_conn, mock_ssm_list_invocations): mock_client = mock_ssm_list_invocations(mock_get_async_conn) mock_get_waiter().wait = mock.AsyncMock(name="wait") trigger = SsmRunCommandTrigger(command_id=COMMAND_ID) generator = trigger.run() response = await generator.asend(None) assert response == TriggerEvent({"status": "success", "command_id": COMMAND_ID}) assert_expected_waiter_type(mock_get_waiter, EXPECTED_WAITER_NAME) assert mock_get_waiter().wait.call_count == 2 mock_get_waiter().wait.assert_any_call( CommandId=COMMAND_ID, InstanceId=INSTANCE_ID_1, WaiterConfig={"MaxAttempts": 1} ) mock_get_waiter().wait.assert_any_call( CommandId=COMMAND_ID, InstanceId=INSTANCE_ID_2, WaiterConfig={"MaxAttempts": 1} ) mock_client.list_command_invocations.assert_called_once_with(CommandId=COMMAND_ID) @pytest.mark.asyncio @mock.patch.object(SsmHook, "get_async_conn") @mock.patch.object(SsmHook, "get_waiter") async def test_run_fails(self, mock_get_waiter, mock_get_async_conn, mock_ssm_list_invocations): mock_ssm_list_invocations(mock_get_async_conn) mock_get_waiter().wait.side_effect = WaiterError( "name", "terminal failure", {"CommandInvocations": [{"CommandId": COMMAND_ID}]} ) trigger = SsmRunCommandTrigger(command_id=COMMAND_ID) generator = trigger.run() with pytest.raises(AirflowException): await generator.asend(None)
TestSsmRunCommandTrigger
python
kamyu104__LeetCode-Solutions
Python/find-closest-node-to-given-two-nodes.py
{ "start": 49, "end": 752 }
class ____(object): def closestMeetingNode(self, edges, node1, node2): """ :type edges: List[int] :type node1: int :type node2: int :rtype: int """ def dfs(node): lookup = {} i = 0 while node != -1: if node in lookup: break lookup[node] = i i += 1 node = edges[node] return lookup lookup1, lookup2 = dfs(node1), dfs(node2) intersect = set(lookup1.iterkeys())&set(lookup2.iterkeys()) return min(intersect, key=lambda x: (max(lookup1[x], lookup2[x]), x)) if intersect else -1
Solution
python
has2k1__plotnine
plotnine/exceptions.py
{ "start": 570, "end": 888 }
class ____(Exception): """ Exception for ggplot errors """ def __init__(self, *args: str): args = tuple(dedent(arg) for arg in args) self.message = " ".join(args) def __str__(self) -> str: """ Error Message """ return repr(self.message)
PlotnineError
python
astropy__astropy
astropy/table/connect.py
{ "start": 224, "end": 2760 }
class ____(registry.UnifiedReadWrite): """Read and parse a data table and return as a Table. This function provides the Table interface to the astropy unified I/O layer. This allows easily reading a file in many supported data formats using syntax such as:: >>> from astropy.table import Table >>> dat = Table.read('table.dat', format='ascii') >>> events = Table.read('events.fits', format='fits') Get help on the available readers for ``Table`` using the``help()`` method:: >>> Table.read.help() # Get help reading Table and list supported formats >>> Table.read.help('fits') # Get detailed help on Table FITS reader >>> Table.read.list_formats() # Print list of available formats See also: https://docs.astropy.org/en/stable/io/unified.html Parameters ---------- *args : tuple, optional Positional arguments passed through to data reader. If supplied the first argument is typically the input filename. format : str File format specifier. units : list, dict, optional List or dict of units to apply to columns descriptions : list, dict, optional List or dict of descriptions to apply to columns **kwargs : dict, optional Keyword arguments passed through to data reader. Returns ------- out : `~astropy.table.Table` Table corresponding to file contents Notes ----- """ def __init__(self, instance, cls): super().__init__(instance, cls, "read", registry=None) # uses default global registry def __call__(self, *args, **kwargs): cls = self._cls units = kwargs.pop("units", None) descriptions = kwargs.pop("descriptions", None) out = self.registry.read(cls, *args, **kwargs) # For some readers (e.g., ascii.ecsv), the returned `out` class is not # guaranteed to be the same as the desired output `cls`. If so, # try coercing to desired class without copying (io.registry.read # would normally do a copy). The normal case here is swapping # Table <=> QTable. if cls is not out.__class__: try: out = cls(out, copy=False) except Exception: raise TypeError( f"could not convert reader output to {cls.__name__} class." ) out._set_column_attribute("unit", units) out._set_column_attribute("description", descriptions) return out
TableRead