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 | mlflow__mlflow | mlflow/tracking/context/system_environment_context.py | {
"start": 274,
"end": 467
} | class ____(RunContextProvider):
def in_context(self):
return MLFLOW_RUN_CONTEXT.defined
def tags(self):
return json.loads(MLFLOW_RUN_CONTEXT.get())
| SystemEnvironmentContext |
python | kamyu104__LeetCode-Solutions | Python/minimum-flips-in-binary-tree-to-get-result.py | {
"start": 164,
"end": 1830
} | class ____(object):
def minimumFlips(self, root, result):
"""
:type root: Optional[TreeNode]
:type result: bool
:rtype: int
"""
INF = float("inf")
OP = {
2: lambda x, y: x or y,
3: lambda x, y: x and y,
4: lambda x, y: x^y ,
5: lambda x, y: not x if x is not None else not y
}
def iter_dfs(root, result):
ret = collections.defaultdict(lambda: INF)
stk = [(1, (root, ret))]
while stk:
step, args = stk.pop()
if step == 1:
node, ret = args
if not node:
ret[None] = 0 # null object pattern
continue
if node.left == node.right:
ret[True] = node.val^1
ret[False] = node.val^0
continue
ret1 = collections.defaultdict(lambda: INF)
ret2 = collections.defaultdict(lambda: INF)
stk.append((2, (node, ret1, ret2, ret)))
stk.append((1, (node.right, ret2)))
stk.append((1, (node.left, ret1)))
elif step == 2:
node, ret1, ret2, ret = args
for k1, v1 in ret1.iteritems():
for k2, v2 in ret2.iteritems():
ret[OP[node.val](k1, k2)] = min(ret[OP[node.val](k1, k2)], v1+v2)
return ret[result]
return iter_dfs(root, result)
import collections
# tree dp with recursion
| Solution |
python | openai__openai-python | src/openai/resources/responses/responses.py | {
"start": 78774,
"end": 155426
} | class ____(AsyncAPIResource):
@cached_property
def input_items(self) -> AsyncInputItems:
return AsyncInputItems(self._client)
@cached_property
def input_tokens(self) -> AsyncInputTokens:
return AsyncInputTokens(self._client)
@cached_property
def with_raw_response(self) -> AsyncResponsesWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers
"""
return AsyncResponsesWithRawResponse(self)
@cached_property
def with_streaming_response(self) -> AsyncResponsesWithStreamingResponse:
"""
An alternative to `.with_raw_response` that doesn't eagerly read the response body.
For more information, see https://www.github.com/openai/openai-python#with_streaming_response
"""
return AsyncResponsesWithStreamingResponse(self)
@overload
async def create(
self,
*,
background: Optional[bool] | Omit = omit,
conversation: Optional[response_create_params.Conversation] | Omit = omit,
include: Optional[List[ResponseIncludable]] | Omit = omit,
input: Union[str, ResponseInputParam] | Omit = omit,
instructions: Optional[str] | Omit = omit,
max_output_tokens: Optional[int] | Omit = omit,
max_tool_calls: Optional[int] | Omit = omit,
metadata: Optional[Metadata] | Omit = omit,
model: ResponsesModel | Omit = omit,
parallel_tool_calls: Optional[bool] | Omit = omit,
previous_response_id: Optional[str] | Omit = omit,
prompt: Optional[ResponsePromptParam] | Omit = omit,
prompt_cache_key: str | Omit = omit,
prompt_cache_retention: Optional[Literal["in-memory", "24h"]] | Omit = omit,
reasoning: Optional[Reasoning] | Omit = omit,
safety_identifier: str | Omit = omit,
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] | Omit = omit,
store: Optional[bool] | Omit = omit,
stream: Optional[Literal[False]] | Omit = omit,
stream_options: Optional[response_create_params.StreamOptions] | Omit = omit,
temperature: Optional[float] | Omit = omit,
text: ResponseTextConfigParam | Omit = omit,
tool_choice: response_create_params.ToolChoice | Omit = omit,
tools: Iterable[ToolParam] | Omit = omit,
top_logprobs: Optional[int] | Omit = omit,
top_p: Optional[float] | Omit = omit,
truncation: Optional[Literal["auto", "disabled"]] | Omit = omit,
user: str | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Response:
"""Creates a model response.
Provide
[text](https://platform.openai.com/docs/guides/text) or
[image](https://platform.openai.com/docs/guides/images) inputs to generate
[text](https://platform.openai.com/docs/guides/text) or
[JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have
the model call your own
[custom code](https://platform.openai.com/docs/guides/function-calling) or use
built-in [tools](https://platform.openai.com/docs/guides/tools) like
[web search](https://platform.openai.com/docs/guides/tools-web-search) or
[file search](https://platform.openai.com/docs/guides/tools-file-search) to use
your own data as input for the model's response.
Args:
background: Whether to run the model response in the background.
[Learn more](https://platform.openai.com/docs/guides/background).
conversation: The conversation that this response belongs to. Items from this conversation are
prepended to `input_items` for this response request. Input items and output
items from this response are automatically added to this conversation after this
response completes.
include: Specify additional output data to include in the model response. Currently
supported values are:
- `web_search_call.action.sources`: Include the sources of the web search tool
call.
- `code_interpreter_call.outputs`: Includes the outputs of python code execution
in code interpreter tool call items.
- `computer_call_output.output.image_url`: Include image urls from the computer
call output.
- `file_search_call.results`: Include the search results of the file search tool
call.
- `message.input_image.image_url`: Include image urls from the input message.
- `message.output_text.logprobs`: Include logprobs with assistant messages.
- `reasoning.encrypted_content`: Includes an encrypted version of reasoning
tokens in reasoning item outputs. This enables reasoning items to be used in
multi-turn conversations when using the Responses API statelessly (like when
the `store` parameter is set to `false`, or when an organization is enrolled
in the zero data retention program).
input: Text, image, or file inputs to the model, used to generate a response.
Learn more:
- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
- [Image inputs](https://platform.openai.com/docs/guides/images)
- [File inputs](https://platform.openai.com/docs/guides/pdf-files)
- [Conversation state](https://platform.openai.com/docs/guides/conversation-state)
- [Function calling](https://platform.openai.com/docs/guides/function-calling)
instructions: A system (or developer) message inserted into the model's context.
When using along with `previous_response_id`, the instructions from a previous
response will not be carried over to the next response. This makes it simple to
swap out system (or developer) messages in new responses.
max_output_tokens: An upper bound for the number of tokens that can be generated for a response,
including visible output tokens and
[reasoning tokens](https://platform.openai.com/docs/guides/reasoning).
max_tool_calls: The maximum number of total calls to built-in tools that can be processed in a
response. This maximum number applies across all built-in tool calls, not per
individual tool. Any further attempts to call a tool by the model will be
ignored.
metadata: 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.
model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a
wide range of models with different capabilities, performance characteristics,
and price points. Refer to the
[model guide](https://platform.openai.com/docs/models) to browse and compare
available models.
parallel_tool_calls: Whether to allow the model to run tool calls in parallel.
previous_response_id: The unique ID of the previous response to the model. Use this to create
multi-turn conversations. Learn more about
[conversation state](https://platform.openai.com/docs/guides/conversation-state).
Cannot be used in conjunction with `conversation`.
prompt: Reference to a prompt template and its variables.
[Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts).
prompt_cache_key: Used by OpenAI to cache responses for similar requests to optimize your cache
hit rates. Replaces the `user` field.
[Learn more](https://platform.openai.com/docs/guides/prompt-caching).
prompt_cache_retention: The retention policy for the prompt cache. Set to `24h` to enable extended
prompt caching, which keeps cached prefixes active for longer, up to a maximum
of 24 hours.
[Learn more](https://platform.openai.com/docs/guides/prompt-caching#prompt-cache-retention).
reasoning: **gpt-5 and o-series models only**
Configuration options for
[reasoning models](https://platform.openai.com/docs/guides/reasoning).
safety_identifier: A stable identifier used to help detect users of your application that may be
violating OpenAI's usage policies. The IDs should be a string that uniquely
identifies each user. We recommend hashing their username or email address, in
order to avoid sending us any identifying information.
[Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).
service_tier: Specifies the processing type used for serving the request.
- If set to 'auto', then the request will be processed with the service tier
configured in the Project settings. Unless otherwise configured, the Project
will use 'default'.
- If set to 'default', then the request will be processed with the standard
pricing and performance for the selected model.
- If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or
'[priority](https://openai.com/api-priority-processing/)', then the request
will be processed with the corresponding service tier.
- When not set, the default behavior is 'auto'.
When the `service_tier` parameter is set, the response body will include the
`service_tier` value based on the processing mode actually used to serve the
request. This response value may be different from the value set in the
parameter.
store: Whether to store the generated model response for later retrieval via API.
stream: If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the
[Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)
for more information.
stream_options: Options for streaming responses. Only set this when you set `stream: true`.
temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
make the output more random, while lower values like 0.2 will make it more
focused and deterministic. We generally recommend altering this or `top_p` but
not both.
text: Configuration options for a text response from the model. Can be plain text or
structured JSON data. Learn more:
- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)
tool_choice: How the model should select which tool (or tools) to use when generating a
response. See the `tools` parameter to see how to specify which tools the model
can call.
tools: An array of tools the model may call while generating a response. You can
specify which tool to use by setting the `tool_choice` parameter.
We support the following categories of tools:
- **Built-in tools**: Tools that are provided by OpenAI that extend the model's
capabilities, like
[web search](https://platform.openai.com/docs/guides/tools-web-search) or
[file search](https://platform.openai.com/docs/guides/tools-file-search).
Learn more about
[built-in tools](https://platform.openai.com/docs/guides/tools).
- **MCP Tools**: Integrations with third-party systems via custom MCP servers or
predefined connectors such as Google Drive and SharePoint. Learn more about
[MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp).
- **Function calls (custom tools)**: Functions that are defined by you, enabling
the model to call your own code with strongly typed arguments and outputs.
Learn more about
[function calling](https://platform.openai.com/docs/guides/function-calling).
You can also use custom tools to call your own code.
top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to
return at each token position, each with an associated log probability.
top_p: An alternative to sampling with temperature, called nucleus sampling, where the
model considers the results of the tokens with top_p probability mass. So 0.1
means only the tokens comprising the top 10% probability mass are considered.
We generally recommend altering this or `temperature` but not both.
truncation: The truncation strategy to use for the model response.
- `auto`: If the input to this Response exceeds the model's context window size,
the model will truncate the response to fit the context window by dropping
items from the beginning of the conversation.
- `disabled` (default): If the input size will exceed the context window size
for a model, the request will fail with a 400 error.
user: This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use
`prompt_cache_key` instead to maintain caching optimizations. A stable
identifier for your end-users. Used to boost cache hit rates by better bucketing
similar requests and to help OpenAI detect and prevent abuse.
[Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
...
@overload
async def create(
self,
*,
stream: Literal[True],
background: Optional[bool] | Omit = omit,
conversation: Optional[response_create_params.Conversation] | Omit = omit,
include: Optional[List[ResponseIncludable]] | Omit = omit,
input: Union[str, ResponseInputParam] | Omit = omit,
instructions: Optional[str] | Omit = omit,
max_output_tokens: Optional[int] | Omit = omit,
max_tool_calls: Optional[int] | Omit = omit,
metadata: Optional[Metadata] | Omit = omit,
model: ResponsesModel | Omit = omit,
parallel_tool_calls: Optional[bool] | Omit = omit,
previous_response_id: Optional[str] | Omit = omit,
prompt: Optional[ResponsePromptParam] | Omit = omit,
prompt_cache_key: str | Omit = omit,
prompt_cache_retention: Optional[Literal["in-memory", "24h"]] | Omit = omit,
reasoning: Optional[Reasoning] | Omit = omit,
safety_identifier: str | Omit = omit,
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] | Omit = omit,
store: Optional[bool] | Omit = omit,
stream_options: Optional[response_create_params.StreamOptions] | Omit = omit,
temperature: Optional[float] | Omit = omit,
text: ResponseTextConfigParam | Omit = omit,
tool_choice: response_create_params.ToolChoice | Omit = omit,
tools: Iterable[ToolParam] | Omit = omit,
top_logprobs: Optional[int] | Omit = omit,
top_p: Optional[float] | Omit = omit,
truncation: Optional[Literal["auto", "disabled"]] | Omit = omit,
user: str | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncStream[ResponseStreamEvent]:
"""Creates a model response.
Provide
[text](https://platform.openai.com/docs/guides/text) or
[image](https://platform.openai.com/docs/guides/images) inputs to generate
[text](https://platform.openai.com/docs/guides/text) or
[JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have
the model call your own
[custom code](https://platform.openai.com/docs/guides/function-calling) or use
built-in [tools](https://platform.openai.com/docs/guides/tools) like
[web search](https://platform.openai.com/docs/guides/tools-web-search) or
[file search](https://platform.openai.com/docs/guides/tools-file-search) to use
your own data as input for the model's response.
Args:
stream: If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the
[Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)
for more information.
background: Whether to run the model response in the background.
[Learn more](https://platform.openai.com/docs/guides/background).
conversation: The conversation that this response belongs to. Items from this conversation are
prepended to `input_items` for this response request. Input items and output
items from this response are automatically added to this conversation after this
response completes.
include: Specify additional output data to include in the model response. Currently
supported values are:
- `web_search_call.action.sources`: Include the sources of the web search tool
call.
- `code_interpreter_call.outputs`: Includes the outputs of python code execution
in code interpreter tool call items.
- `computer_call_output.output.image_url`: Include image urls from the computer
call output.
- `file_search_call.results`: Include the search results of the file search tool
call.
- `message.input_image.image_url`: Include image urls from the input message.
- `message.output_text.logprobs`: Include logprobs with assistant messages.
- `reasoning.encrypted_content`: Includes an encrypted version of reasoning
tokens in reasoning item outputs. This enables reasoning items to be used in
multi-turn conversations when using the Responses API statelessly (like when
the `store` parameter is set to `false`, or when an organization is enrolled
in the zero data retention program).
input: Text, image, or file inputs to the model, used to generate a response.
Learn more:
- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
- [Image inputs](https://platform.openai.com/docs/guides/images)
- [File inputs](https://platform.openai.com/docs/guides/pdf-files)
- [Conversation state](https://platform.openai.com/docs/guides/conversation-state)
- [Function calling](https://platform.openai.com/docs/guides/function-calling)
instructions: A system (or developer) message inserted into the model's context.
When using along with `previous_response_id`, the instructions from a previous
response will not be carried over to the next response. This makes it simple to
swap out system (or developer) messages in new responses.
max_output_tokens: An upper bound for the number of tokens that can be generated for a response,
including visible output tokens and
[reasoning tokens](https://platform.openai.com/docs/guides/reasoning).
max_tool_calls: The maximum number of total calls to built-in tools that can be processed in a
response. This maximum number applies across all built-in tool calls, not per
individual tool. Any further attempts to call a tool by the model will be
ignored.
metadata: 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.
model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a
wide range of models with different capabilities, performance characteristics,
and price points. Refer to the
[model guide](https://platform.openai.com/docs/models) to browse and compare
available models.
parallel_tool_calls: Whether to allow the model to run tool calls in parallel.
previous_response_id: The unique ID of the previous response to the model. Use this to create
multi-turn conversations. Learn more about
[conversation state](https://platform.openai.com/docs/guides/conversation-state).
Cannot be used in conjunction with `conversation`.
prompt: Reference to a prompt template and its variables.
[Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts).
prompt_cache_key: Used by OpenAI to cache responses for similar requests to optimize your cache
hit rates. Replaces the `user` field.
[Learn more](https://platform.openai.com/docs/guides/prompt-caching).
prompt_cache_retention: The retention policy for the prompt cache. Set to `24h` to enable extended
prompt caching, which keeps cached prefixes active for longer, up to a maximum
of 24 hours.
[Learn more](https://platform.openai.com/docs/guides/prompt-caching#prompt-cache-retention).
reasoning: **gpt-5 and o-series models only**
Configuration options for
[reasoning models](https://platform.openai.com/docs/guides/reasoning).
safety_identifier: A stable identifier used to help detect users of your application that may be
violating OpenAI's usage policies. The IDs should be a string that uniquely
identifies each user. We recommend hashing their username or email address, in
order to avoid sending us any identifying information.
[Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).
service_tier: Specifies the processing type used for serving the request.
- If set to 'auto', then the request will be processed with the service tier
configured in the Project settings. Unless otherwise configured, the Project
will use 'default'.
- If set to 'default', then the request will be processed with the standard
pricing and performance for the selected model.
- If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or
'[priority](https://openai.com/api-priority-processing/)', then the request
will be processed with the corresponding service tier.
- When not set, the default behavior is 'auto'.
When the `service_tier` parameter is set, the response body will include the
`service_tier` value based on the processing mode actually used to serve the
request. This response value may be different from the value set in the
parameter.
store: Whether to store the generated model response for later retrieval via API.
stream_options: Options for streaming responses. Only set this when you set `stream: true`.
temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
make the output more random, while lower values like 0.2 will make it more
focused and deterministic. We generally recommend altering this or `top_p` but
not both.
text: Configuration options for a text response from the model. Can be plain text or
structured JSON data. Learn more:
- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)
tool_choice: How the model should select which tool (or tools) to use when generating a
response. See the `tools` parameter to see how to specify which tools the model
can call.
tools: An array of tools the model may call while generating a response. You can
specify which tool to use by setting the `tool_choice` parameter.
We support the following categories of tools:
- **Built-in tools**: Tools that are provided by OpenAI that extend the model's
capabilities, like
[web search](https://platform.openai.com/docs/guides/tools-web-search) or
[file search](https://platform.openai.com/docs/guides/tools-file-search).
Learn more about
[built-in tools](https://platform.openai.com/docs/guides/tools).
- **MCP Tools**: Integrations with third-party systems via custom MCP servers or
predefined connectors such as Google Drive and SharePoint. Learn more about
[MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp).
- **Function calls (custom tools)**: Functions that are defined by you, enabling
the model to call your own code with strongly typed arguments and outputs.
Learn more about
[function calling](https://platform.openai.com/docs/guides/function-calling).
You can also use custom tools to call your own code.
top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to
return at each token position, each with an associated log probability.
top_p: An alternative to sampling with temperature, called nucleus sampling, where the
model considers the results of the tokens with top_p probability mass. So 0.1
means only the tokens comprising the top 10% probability mass are considered.
We generally recommend altering this or `temperature` but not both.
truncation: The truncation strategy to use for the model response.
- `auto`: If the input to this Response exceeds the model's context window size,
the model will truncate the response to fit the context window by dropping
items from the beginning of the conversation.
- `disabled` (default): If the input size will exceed the context window size
for a model, the request will fail with a 400 error.
user: This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use
`prompt_cache_key` instead to maintain caching optimizations. A stable
identifier for your end-users. Used to boost cache hit rates by better bucketing
similar requests and to help OpenAI detect and prevent abuse.
[Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
...
@overload
async def create(
self,
*,
stream: bool,
background: Optional[bool] | Omit = omit,
conversation: Optional[response_create_params.Conversation] | Omit = omit,
include: Optional[List[ResponseIncludable]] | Omit = omit,
input: Union[str, ResponseInputParam] | Omit = omit,
instructions: Optional[str] | Omit = omit,
max_output_tokens: Optional[int] | Omit = omit,
max_tool_calls: Optional[int] | Omit = omit,
metadata: Optional[Metadata] | Omit = omit,
model: ResponsesModel | Omit = omit,
parallel_tool_calls: Optional[bool] | Omit = omit,
previous_response_id: Optional[str] | Omit = omit,
prompt: Optional[ResponsePromptParam] | Omit = omit,
prompt_cache_key: str | Omit = omit,
prompt_cache_retention: Optional[Literal["in-memory", "24h"]] | Omit = omit,
reasoning: Optional[Reasoning] | Omit = omit,
safety_identifier: str | Omit = omit,
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] | Omit = omit,
store: Optional[bool] | Omit = omit,
stream_options: Optional[response_create_params.StreamOptions] | Omit = omit,
temperature: Optional[float] | Omit = omit,
text: ResponseTextConfigParam | Omit = omit,
tool_choice: response_create_params.ToolChoice | Omit = omit,
tools: Iterable[ToolParam] | Omit = omit,
top_logprobs: Optional[int] | Omit = omit,
top_p: Optional[float] | Omit = omit,
truncation: Optional[Literal["auto", "disabled"]] | Omit = omit,
user: str | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Response | AsyncStream[ResponseStreamEvent]:
"""Creates a model response.
Provide
[text](https://platform.openai.com/docs/guides/text) or
[image](https://platform.openai.com/docs/guides/images) inputs to generate
[text](https://platform.openai.com/docs/guides/text) or
[JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs. Have
the model call your own
[custom code](https://platform.openai.com/docs/guides/function-calling) or use
built-in [tools](https://platform.openai.com/docs/guides/tools) like
[web search](https://platform.openai.com/docs/guides/tools-web-search) or
[file search](https://platform.openai.com/docs/guides/tools-file-search) to use
your own data as input for the model's response.
Args:
stream: If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the
[Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)
for more information.
background: Whether to run the model response in the background.
[Learn more](https://platform.openai.com/docs/guides/background).
conversation: The conversation that this response belongs to. Items from this conversation are
prepended to `input_items` for this response request. Input items and output
items from this response are automatically added to this conversation after this
response completes.
include: Specify additional output data to include in the model response. Currently
supported values are:
- `web_search_call.action.sources`: Include the sources of the web search tool
call.
- `code_interpreter_call.outputs`: Includes the outputs of python code execution
in code interpreter tool call items.
- `computer_call_output.output.image_url`: Include image urls from the computer
call output.
- `file_search_call.results`: Include the search results of the file search tool
call.
- `message.input_image.image_url`: Include image urls from the input message.
- `message.output_text.logprobs`: Include logprobs with assistant messages.
- `reasoning.encrypted_content`: Includes an encrypted version of reasoning
tokens in reasoning item outputs. This enables reasoning items to be used in
multi-turn conversations when using the Responses API statelessly (like when
the `store` parameter is set to `false`, or when an organization is enrolled
in the zero data retention program).
input: Text, image, or file inputs to the model, used to generate a response.
Learn more:
- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
- [Image inputs](https://platform.openai.com/docs/guides/images)
- [File inputs](https://platform.openai.com/docs/guides/pdf-files)
- [Conversation state](https://platform.openai.com/docs/guides/conversation-state)
- [Function calling](https://platform.openai.com/docs/guides/function-calling)
instructions: A system (or developer) message inserted into the model's context.
When using along with `previous_response_id`, the instructions from a previous
response will not be carried over to the next response. This makes it simple to
swap out system (or developer) messages in new responses.
max_output_tokens: An upper bound for the number of tokens that can be generated for a response,
including visible output tokens and
[reasoning tokens](https://platform.openai.com/docs/guides/reasoning).
max_tool_calls: The maximum number of total calls to built-in tools that can be processed in a
response. This maximum number applies across all built-in tool calls, not per
individual tool. Any further attempts to call a tool by the model will be
ignored.
metadata: 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.
model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a
wide range of models with different capabilities, performance characteristics,
and price points. Refer to the
[model guide](https://platform.openai.com/docs/models) to browse and compare
available models.
parallel_tool_calls: Whether to allow the model to run tool calls in parallel.
previous_response_id: The unique ID of the previous response to the model. Use this to create
multi-turn conversations. Learn more about
[conversation state](https://platform.openai.com/docs/guides/conversation-state).
Cannot be used in conjunction with `conversation`.
prompt: Reference to a prompt template and its variables.
[Learn more](https://platform.openai.com/docs/guides/text?api-mode=responses#reusable-prompts).
prompt_cache_key: Used by OpenAI to cache responses for similar requests to optimize your cache
hit rates. Replaces the `user` field.
[Learn more](https://platform.openai.com/docs/guides/prompt-caching).
prompt_cache_retention: The retention policy for the prompt cache. Set to `24h` to enable extended
prompt caching, which keeps cached prefixes active for longer, up to a maximum
of 24 hours.
[Learn more](https://platform.openai.com/docs/guides/prompt-caching#prompt-cache-retention).
reasoning: **gpt-5 and o-series models only**
Configuration options for
[reasoning models](https://platform.openai.com/docs/guides/reasoning).
safety_identifier: A stable identifier used to help detect users of your application that may be
violating OpenAI's usage policies. The IDs should be a string that uniquely
identifies each user. We recommend hashing their username or email address, in
order to avoid sending us any identifying information.
[Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).
service_tier: Specifies the processing type used for serving the request.
- If set to 'auto', then the request will be processed with the service tier
configured in the Project settings. Unless otherwise configured, the Project
will use 'default'.
- If set to 'default', then the request will be processed with the standard
pricing and performance for the selected model.
- If set to '[flex](https://platform.openai.com/docs/guides/flex-processing)' or
'[priority](https://openai.com/api-priority-processing/)', then the request
will be processed with the corresponding service tier.
- When not set, the default behavior is 'auto'.
When the `service_tier` parameter is set, the response body will include the
`service_tier` value based on the processing mode actually used to serve the
request. This response value may be different from the value set in the
parameter.
store: Whether to store the generated model response for later retrieval via API.
stream_options: Options for streaming responses. Only set this when you set `stream: true`.
temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will
make the output more random, while lower values like 0.2 will make it more
focused and deterministic. We generally recommend altering this or `top_p` but
not both.
text: Configuration options for a text response from the model. Can be plain text or
structured JSON data. Learn more:
- [Text inputs and outputs](https://platform.openai.com/docs/guides/text)
- [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs)
tool_choice: How the model should select which tool (or tools) to use when generating a
response. See the `tools` parameter to see how to specify which tools the model
can call.
tools: An array of tools the model may call while generating a response. You can
specify which tool to use by setting the `tool_choice` parameter.
We support the following categories of tools:
- **Built-in tools**: Tools that are provided by OpenAI that extend the model's
capabilities, like
[web search](https://platform.openai.com/docs/guides/tools-web-search) or
[file search](https://platform.openai.com/docs/guides/tools-file-search).
Learn more about
[built-in tools](https://platform.openai.com/docs/guides/tools).
- **MCP Tools**: Integrations with third-party systems via custom MCP servers or
predefined connectors such as Google Drive and SharePoint. Learn more about
[MCP Tools](https://platform.openai.com/docs/guides/tools-connectors-mcp).
- **Function calls (custom tools)**: Functions that are defined by you, enabling
the model to call your own code with strongly typed arguments and outputs.
Learn more about
[function calling](https://platform.openai.com/docs/guides/function-calling).
You can also use custom tools to call your own code.
top_logprobs: An integer between 0 and 20 specifying the number of most likely tokens to
return at each token position, each with an associated log probability.
top_p: An alternative to sampling with temperature, called nucleus sampling, where the
model considers the results of the tokens with top_p probability mass. So 0.1
means only the tokens comprising the top 10% probability mass are considered.
We generally recommend altering this or `temperature` but not both.
truncation: The truncation strategy to use for the model response.
- `auto`: If the input to this Response exceeds the model's context window size,
the model will truncate the response to fit the context window by dropping
items from the beginning of the conversation.
- `disabled` (default): If the input size will exceed the context window size
for a model, the request will fail with a 400 error.
user: This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use
`prompt_cache_key` instead to maintain caching optimizations. A stable
identifier for your end-users. Used to boost cache hit rates by better bucketing
similar requests and to help OpenAI detect and prevent abuse.
[Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
...
async def create(
self,
*,
background: Optional[bool] | Omit = omit,
conversation: Optional[response_create_params.Conversation] | Omit = omit,
include: Optional[List[ResponseIncludable]] | Omit = omit,
input: Union[str, ResponseInputParam] | Omit = omit,
instructions: Optional[str] | Omit = omit,
max_output_tokens: Optional[int] | Omit = omit,
max_tool_calls: Optional[int] | Omit = omit,
metadata: Optional[Metadata] | Omit = omit,
model: ResponsesModel | Omit = omit,
parallel_tool_calls: Optional[bool] | Omit = omit,
previous_response_id: Optional[str] | Omit = omit,
prompt: Optional[ResponsePromptParam] | Omit = omit,
prompt_cache_key: str | Omit = omit,
prompt_cache_retention: Optional[Literal["in-memory", "24h"]] | Omit = omit,
reasoning: Optional[Reasoning] | Omit = omit,
safety_identifier: str | Omit = omit,
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] | Omit = omit,
store: Optional[bool] | Omit = omit,
stream: Optional[Literal[False]] | Literal[True] | Omit = omit,
stream_options: Optional[response_create_params.StreamOptions] | Omit = omit,
temperature: Optional[float] | Omit = omit,
text: ResponseTextConfigParam | Omit = omit,
tool_choice: response_create_params.ToolChoice | Omit = omit,
tools: Iterable[ToolParam] | Omit = omit,
top_logprobs: Optional[int] | Omit = omit,
top_p: Optional[float] | Omit = omit,
truncation: Optional[Literal["auto", "disabled"]] | Omit = omit,
user: str | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Response | AsyncStream[ResponseStreamEvent]:
return await self._post(
"/responses",
body=await async_maybe_transform(
{
"background": background,
"conversation": conversation,
"include": include,
"input": input,
"instructions": instructions,
"max_output_tokens": max_output_tokens,
"max_tool_calls": max_tool_calls,
"metadata": metadata,
"model": model,
"parallel_tool_calls": parallel_tool_calls,
"previous_response_id": previous_response_id,
"prompt": prompt,
"prompt_cache_key": prompt_cache_key,
"prompt_cache_retention": prompt_cache_retention,
"reasoning": reasoning,
"safety_identifier": safety_identifier,
"service_tier": service_tier,
"store": store,
"stream": stream,
"stream_options": stream_options,
"temperature": temperature,
"text": text,
"tool_choice": tool_choice,
"tools": tools,
"top_logprobs": top_logprobs,
"top_p": top_p,
"truncation": truncation,
"user": user,
},
response_create_params.ResponseCreateParamsStreaming
if stream
else response_create_params.ResponseCreateParamsNonStreaming,
),
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=Response,
stream=stream or False,
stream_cls=AsyncStream[ResponseStreamEvent],
)
@overload
def stream(
self,
*,
response_id: str,
text_format: type[TextFormatT] | Omit = omit,
starting_after: int | Omit = omit,
tools: Iterable[ParseableToolParam] | Omit = omit,
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> AsyncResponseStreamManager[TextFormatT]: ...
@overload
def stream(
self,
*,
input: Union[str, ResponseInputParam],
model: ResponsesModel,
background: Optional[bool] | Omit = omit,
text_format: type[TextFormatT] | Omit = omit,
tools: Iterable[ParseableToolParam] | Omit = omit,
conversation: Optional[response_create_params.Conversation] | Omit = omit,
include: Optional[List[ResponseIncludable]] | Omit = omit,
instructions: Optional[str] | Omit = omit,
max_output_tokens: Optional[int] | Omit = omit,
max_tool_calls: Optional[int] | Omit = omit,
metadata: Optional[Metadata] | Omit = omit,
parallel_tool_calls: Optional[bool] | Omit = omit,
previous_response_id: Optional[str] | Omit = omit,
prompt: Optional[ResponsePromptParam] | Omit = omit,
prompt_cache_key: str | Omit = omit,
prompt_cache_retention: Optional[Literal["in-memory", "24h"]] | Omit = omit,
reasoning: Optional[Reasoning] | Omit = omit,
safety_identifier: str | Omit = omit,
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] | Omit = omit,
store: Optional[bool] | Omit = omit,
stream_options: Optional[response_create_params.StreamOptions] | Omit = omit,
temperature: Optional[float] | Omit = omit,
text: ResponseTextConfigParam | Omit = omit,
tool_choice: response_create_params.ToolChoice | Omit = omit,
top_logprobs: Optional[int] | Omit = omit,
top_p: Optional[float] | Omit = omit,
truncation: Optional[Literal["auto", "disabled"]] | Omit = omit,
user: str | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> AsyncResponseStreamManager[TextFormatT]: ...
def stream(
self,
*,
response_id: str | Omit = omit,
input: Union[str, ResponseInputParam] | Omit = omit,
model: ResponsesModel | Omit = omit,
background: Optional[bool] | Omit = omit,
text_format: type[TextFormatT] | Omit = omit,
tools: Iterable[ParseableToolParam] | Omit = omit,
conversation: Optional[response_create_params.Conversation] | Omit = omit,
include: Optional[List[ResponseIncludable]] | Omit = omit,
instructions: Optional[str] | Omit = omit,
max_output_tokens: Optional[int] | Omit = omit,
max_tool_calls: Optional[int] | Omit = omit,
metadata: Optional[Metadata] | Omit = omit,
parallel_tool_calls: Optional[bool] | Omit = omit,
previous_response_id: Optional[str] | Omit = omit,
prompt: Optional[ResponsePromptParam] | Omit = omit,
prompt_cache_key: str | Omit = omit,
prompt_cache_retention: Optional[Literal["in-memory", "24h"]] | Omit = omit,
reasoning: Optional[Reasoning] | Omit = omit,
safety_identifier: str | Omit = omit,
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] | Omit = omit,
store: Optional[bool] | Omit = omit,
stream_options: Optional[response_create_params.StreamOptions] | Omit = omit,
temperature: Optional[float] | Omit = omit,
text: ResponseTextConfigParam | Omit = omit,
tool_choice: response_create_params.ToolChoice | Omit = omit,
top_logprobs: Optional[int] | Omit = omit,
top_p: Optional[float] | Omit = omit,
truncation: Optional[Literal["auto", "disabled"]] | Omit = omit,
user: str | Omit = omit,
starting_after: int | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> AsyncResponseStreamManager[TextFormatT]:
new_response_args = {
"input": input,
"model": model,
"conversation": conversation,
"include": include,
"instructions": instructions,
"max_output_tokens": max_output_tokens,
"max_tool_calls": max_tool_calls,
"metadata": metadata,
"parallel_tool_calls": parallel_tool_calls,
"previous_response_id": previous_response_id,
"prompt": prompt,
"prompt_cache_key": prompt_cache_key,
"prompt_cache_retention": prompt_cache_retention,
"reasoning": reasoning,
"safety_identifier": safety_identifier,
"service_tier": service_tier,
"store": store,
"stream_options": stream_options,
"temperature": temperature,
"text": text,
"tool_choice": tool_choice,
"top_logprobs": top_logprobs,
"top_p": top_p,
"truncation": truncation,
"user": user,
"background": background,
}
new_response_args_names = [k for k, v in new_response_args.items() if is_given(v)]
if (is_given(response_id) or is_given(starting_after)) and len(new_response_args_names) > 0:
raise ValueError(
"Cannot provide both response_id/starting_after can't be provided together with "
+ ", ".join(new_response_args_names)
)
tools = _make_tools(tools)
if len(new_response_args_names) > 0:
if isinstance(input, NotGiven):
raise ValueError("input must be provided when creating a new response")
if not is_given(model):
raise ValueError("model must be provided when creating a new response")
if is_given(text_format):
if not text:
text = {}
if "format" in text:
raise TypeError("Cannot mix and match text.format with text_format")
text["format"] = _type_to_text_format_param(text_format)
api_request = self.create(
input=input,
model=model,
stream=True,
tools=tools,
conversation=conversation,
include=include,
instructions=instructions,
max_output_tokens=max_output_tokens,
max_tool_calls=max_tool_calls,
metadata=metadata,
parallel_tool_calls=parallel_tool_calls,
previous_response_id=previous_response_id,
prompt=prompt,
prompt_cache_key=prompt_cache_key,
prompt_cache_retention=prompt_cache_retention,
store=store,
stream_options=stream_options,
temperature=temperature,
text=text,
tool_choice=tool_choice,
reasoning=reasoning,
safety_identifier=safety_identifier,
service_tier=service_tier,
top_logprobs=top_logprobs,
top_p=top_p,
truncation=truncation,
user=user,
background=background,
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
)
return AsyncResponseStreamManager(
api_request,
text_format=text_format,
input_tools=tools,
starting_after=None,
)
else:
if isinstance(response_id, Omit):
raise ValueError("response_id must be provided when streaming an existing response")
api_request = self.retrieve(
response_id,
stream=True,
include=include or [],
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
)
return AsyncResponseStreamManager(
api_request,
text_format=text_format,
input_tools=tools,
starting_after=starting_after if is_given(starting_after) else None,
)
async def parse(
self,
*,
text_format: type[TextFormatT] | Omit = omit,
background: Optional[bool] | Omit = omit,
conversation: Optional[response_create_params.Conversation] | Omit = omit,
include: Optional[List[ResponseIncludable]] | Omit = omit,
input: Union[str, ResponseInputParam] | Omit = omit,
instructions: Optional[str] | Omit = omit,
max_output_tokens: Optional[int] | Omit = omit,
max_tool_calls: Optional[int] | Omit = omit,
metadata: Optional[Metadata] | Omit = omit,
model: ResponsesModel | Omit = omit,
parallel_tool_calls: Optional[bool] | Omit = omit,
previous_response_id: Optional[str] | Omit = omit,
prompt: Optional[ResponsePromptParam] | Omit = omit,
prompt_cache_key: str | Omit = omit,
prompt_cache_retention: Optional[Literal["in-memory", "24h"]] | Omit = omit,
reasoning: Optional[Reasoning] | Omit = omit,
safety_identifier: str | Omit = omit,
service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] | Omit = omit,
store: Optional[bool] | Omit = omit,
stream: Optional[Literal[False]] | Literal[True] | Omit = omit,
stream_options: Optional[response_create_params.StreamOptions] | Omit = omit,
temperature: Optional[float] | Omit = omit,
text: ResponseTextConfigParam | Omit = omit,
tool_choice: response_create_params.ToolChoice | Omit = omit,
tools: Iterable[ParseableToolParam] | Omit = omit,
top_logprobs: Optional[int] | Omit = omit,
top_p: Optional[float] | Omit = omit,
truncation: Optional[Literal["auto", "disabled"]] | Omit = omit,
user: str | Omit = omit,
verbosity: Optional[Literal["low", "medium", "high"]] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> ParsedResponse[TextFormatT]:
if is_given(text_format):
if not text:
text = {}
if "format" in text:
raise TypeError("Cannot mix and match text.format with text_format")
text["format"] = _type_to_text_format_param(text_format)
tools = _make_tools(tools)
def parser(raw_response: Response) -> ParsedResponse[TextFormatT]:
return parse_response(
input_tools=tools,
text_format=text_format,
response=raw_response,
)
return await self._post(
"/responses",
body=maybe_transform(
{
"background": background,
"conversation": conversation,
"include": include,
"input": input,
"instructions": instructions,
"max_output_tokens": max_output_tokens,
"max_tool_calls": max_tool_calls,
"metadata": metadata,
"model": model,
"parallel_tool_calls": parallel_tool_calls,
"previous_response_id": previous_response_id,
"prompt": prompt,
"prompt_cache_key": prompt_cache_key,
"prompt_cache_retention": prompt_cache_retention,
"reasoning": reasoning,
"safety_identifier": safety_identifier,
"service_tier": service_tier,
"store": store,
"stream": stream,
"stream_options": stream_options,
"temperature": temperature,
"text": text,
"tool_choice": tool_choice,
"tools": tools,
"top_logprobs": top_logprobs,
"top_p": top_p,
"truncation": truncation,
"user": user,
"verbosity": verbosity,
},
response_create_params.ResponseCreateParams,
),
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
post_parser=parser,
),
# we turn the `Response` instance into a `ParsedResponse`
# in the `parser` function above
cast_to=cast(Type[ParsedResponse[TextFormatT]], Response),
)
@overload
async def retrieve(
self,
response_id: str,
*,
include: List[ResponseIncludable] | Omit = omit,
include_obfuscation: bool | Omit = omit,
starting_after: int | Omit = omit,
stream: Literal[False] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Response: ...
@overload
async def retrieve(
self,
response_id: str,
*,
stream: Literal[True],
include: List[ResponseIncludable] | Omit = omit,
starting_after: int | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> AsyncStream[ResponseStreamEvent]: ...
@overload
async def retrieve(
self,
response_id: str,
*,
stream: bool,
include: List[ResponseIncludable] | Omit = omit,
starting_after: int | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> Response | AsyncStream[ResponseStreamEvent]: ...
@overload
async def retrieve(
self,
response_id: str,
*,
stream: bool = False,
include: List[ResponseIncludable] | Omit = omit,
starting_after: int | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
) -> Response | AsyncStream[ResponseStreamEvent]:
"""
Retrieves a model response with the given ID.
Args:
include: Additional fields to include in the response. See the `include` parameter for
Response creation above for more information.
include_obfuscation: When true, stream obfuscation will be enabled. Stream obfuscation adds random
characters to an `obfuscation` field on streaming delta events to normalize
payload sizes as a mitigation to certain side-channel attacks. These obfuscation
fields are included by default, but add a small amount of overhead to the data
stream. You can set `include_obfuscation` to false to optimize for bandwidth if
you trust the network links between your application and the OpenAI API.
starting_after: The sequence number of the event after which to start streaming.
stream: If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the
[Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)
for more information.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
...
@overload
async def retrieve(
self,
response_id: str,
*,
stream: Literal[True],
include: List[ResponseIncludable] | Omit = omit,
include_obfuscation: bool | Omit = omit,
starting_after: int | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> AsyncStream[ResponseStreamEvent]:
"""
Retrieves a model response with the given ID.
Args:
stream: If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the
[Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)
for more information.
include: Additional fields to include in the response. See the `include` parameter for
Response creation above for more information.
include_obfuscation: When true, stream obfuscation will be enabled. Stream obfuscation adds random
characters to an `obfuscation` field on streaming delta events to normalize
payload sizes as a mitigation to certain side-channel attacks. These obfuscation
fields are included by default, but add a small amount of overhead to the data
stream. You can set `include_obfuscation` to false to optimize for bandwidth if
you trust the network links between your application and the OpenAI API.
starting_after: The sequence number of the event after which to start streaming.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
...
@overload
async def retrieve(
self,
response_id: str,
*,
stream: bool,
include: List[ResponseIncludable] | Omit = omit,
include_obfuscation: bool | Omit = omit,
starting_after: int | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Response | AsyncStream[ResponseStreamEvent]:
"""
Retrieves a model response with the given ID.
Args:
stream: If set to true, the model response data will be streamed to the client as it is
generated using
[server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).
See the
[Streaming section below](https://platform.openai.com/docs/api-reference/responses-streaming)
for more information.
include: Additional fields to include in the response. See the `include` parameter for
Response creation above for more information.
include_obfuscation: When true, stream obfuscation will be enabled. Stream obfuscation adds random
characters to an `obfuscation` field on streaming delta events to normalize
payload sizes as a mitigation to certain side-channel attacks. These obfuscation
fields are included by default, but add a small amount of overhead to the data
stream. You can set `include_obfuscation` to false to optimize for bandwidth if
you trust the network links between your application and the OpenAI API.
starting_after: The sequence number of the event after which to start streaming.
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
...
async def retrieve(
self,
response_id: str,
*,
include: List[ResponseIncludable] | Omit = omit,
include_obfuscation: bool | Omit = omit,
starting_after: int | Omit = omit,
stream: Literal[False] | Literal[True] | Omit = omit,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Response | AsyncStream[ResponseStreamEvent]:
if not response_id:
raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}")
return await self._get(
f"/responses/{response_id}",
options=make_request_options(
extra_headers=extra_headers,
extra_query=extra_query,
extra_body=extra_body,
timeout=timeout,
query=await async_maybe_transform(
{
"include": include,
"include_obfuscation": include_obfuscation,
"starting_after": starting_after,
"stream": stream,
},
response_retrieve_params.ResponseRetrieveParams,
),
),
cast_to=Response,
stream=stream or False,
stream_cls=AsyncStream[ResponseStreamEvent],
)
async def delete(
self,
response_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> None:
"""
Deletes a model response with the given ID.
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not response_id:
raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}")
extra_headers = {"Accept": "*/*", **(extra_headers or {})}
return await self._delete(
f"/responses/{response_id}",
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=NoneType,
)
async def cancel(
self,
response_id: str,
*,
# Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs.
# The extra values given here take precedence over values defined on the client or passed to this method.
extra_headers: Headers | None = None,
extra_query: Query | None = None,
extra_body: Body | None = None,
timeout: float | httpx.Timeout | None | NotGiven = not_given,
) -> Response:
"""Cancels a model response with the given ID.
Only responses created with the
`background` parameter set to `true` can be cancelled.
[Learn more](https://platform.openai.com/docs/guides/background).
Args:
extra_headers: Send extra headers
extra_query: Add additional query parameters to the request
extra_body: Add additional JSON properties to the request
timeout: Override the client-level default timeout for this request, in seconds
"""
if not response_id:
raise ValueError(f"Expected a non-empty value for `response_id` but received {response_id!r}")
return await self._post(
f"/responses/{response_id}/cancel",
options=make_request_options(
extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout
),
cast_to=Response,
)
| AsyncResponses |
python | numba__numba | numba/tests/test_closure.py | {
"start": 2710,
"end": 13629
} | class ____(TestCase):
"""
Tests for (partial) closure support in njit. The support is partial
because it only works for closures that can be successfully inlined
at compile time.
"""
def test_inner_function(self):
def outer(x):
def inner(x):
return x * x
return inner(x) + inner(x)
cfunc = njit(outer)
self.assertEqual(cfunc(10), outer(10))
def test_inner_function_with_closure(self):
def outer(x):
y = x + 1
def inner(x):
return x * x + y
return inner(x) + inner(x)
cfunc = njit(outer)
self.assertEqual(cfunc(10), outer(10))
def test_inner_function_with_closure_2(self):
def outer(x):
y = x + 1
def inner(x):
return x * y
y = inner(x)
return y + inner(x)
cfunc = njit(outer)
self.assertEqual(cfunc(10), outer(10))
def test_inner_function_with_closure_3(self):
code = """
def outer(x):
y = x + 1
z = 0
def inner(x):
nonlocal z
z += x * x
return z + y
return inner(x) + inner(x) + z
"""
ns = {}
exec(code.strip(), ns)
cfunc = njit(ns['outer'])
self.assertEqual(cfunc(10), ns['outer'](10))
def test_inner_function_nested(self):
def outer(x):
def inner(y):
def innermost(z):
return x + y + z
s = 0
for i in range(y):
s += innermost(i)
return s
return inner(x * x)
cfunc = njit(outer)
self.assertEqual(cfunc(10), outer(10))
def test_bulk_use_cases(self):
""" Tests the large number of use cases defined below """
# jitted function used in some tests
@njit
def fib3(n):
if n < 2:
return n
return fib3(n - 1) + fib3(n - 2)
def outer1(x):
""" Test calling recursive function from inner """
def inner(x):
return fib3(x)
return inner(x)
def outer2(x):
""" Test calling recursive function from closure """
z = x + 1
def inner(x):
return x + fib3(z)
return inner(x)
def outer3(x):
""" Test recursive inner """
def inner(x):
if x < 2:
return 10
else:
inner(x - 1)
return inner(x)
def outer4(x):
""" Test recursive closure """
y = x + 1
def inner(x):
if x + y < 2:
return 10
else:
inner(x - 1)
return inner(x)
def outer5(x):
""" Test nested closure """
y = x + 1
def inner1(x):
z = y + x + 2
def inner2(x):
return x + z
return inner2(x) + y
return inner1(x)
def outer6(x):
""" Test closure with list comprehension in body """
y = x + 1
def inner1(x):
z = y + x + 2
return [t for t in range(z)]
return inner1(x)
_OUTER_SCOPE_VAR = 9
def outer7(x):
""" Test use of outer scope var, no closure """
z = x + 1
return x + z + _OUTER_SCOPE_VAR
_OUTER_SCOPE_VAR = 9
def outer8(x):
""" Test use of outer scope var, with closure """
z = x + 1
def inner(x):
return x + z + _OUTER_SCOPE_VAR
return inner(x)
def outer9(x):
""" Test closure assignment"""
z = x + 1
def inner(x):
return x + z
f = inner
return f(x)
def outer10(x):
""" Test two inner, one calls other """
z = x + 1
def inner(x):
return x + z
def inner2(x):
return inner(x)
return inner2(x)
def outer11(x):
""" return the closure """
z = x + 1
def inner(x):
return x + z
return inner
def outer12(x):
""" closure with kwarg"""
z = x + 1
def inner(x, kw=7):
return x + z + kw
return inner(x)
def outer13(x, kw=7):
""" outer with kwarg no closure"""
z = x + 1 + kw
return z
def outer14(x, kw=7):
""" outer with kwarg used in closure"""
z = x + 1
def inner(x):
return x + z + kw
return inner(x)
def outer15(x, kw=7):
""" outer with kwarg as arg to closure"""
z = x + 1
def inner(x, kw):
return x + z + kw
return inner(x, kw)
def outer16(x):
""" closure is generator, consumed locally """
z = x + 1
def inner(x):
yield x + z
return list(inner(x))
def outer17(x):
""" closure is generator, returned """
z = x + 1
def inner(x):
yield x + z
return inner(x)
def outer18(x):
""" closure is generator, consumed in loop """
z = x + 1
def inner(x):
yield x + z
for i in inner(x):
t = i
return t
def outer19(x):
""" closure as arg to another closure """
z1 = x + 1
z2 = x + 2
def inner(x):
return x + z1
def inner2(f, x):
return f(x) + z2
return inner2(inner, x)
def outer20(x):
""" Test calling numpy in closure """
z = x + 1
def inner(x):
return x + numpy.cos(z)
return inner(x)
def outer21(x):
""" Test calling numpy import as in closure """
z = x + 1
def inner(x):
return x + np.cos(z)
return inner(x)
def outer22():
"""Test to ensure that unsupported *args raises correctly"""
def bar(a, b):
pass
x = 1, 2
bar(*x)
# functions to test that are expected to pass
f = [outer1, outer2, outer5, outer6, outer7, outer8,
outer9, outer10, outer12, outer13, outer14,
outer15, outer19, outer20, outer21]
for ref in f:
cfunc = njit(ref)
var = 10
self.assertEqual(cfunc(var), ref(var))
# test functions that are expected to fail
with self.assertRaises(NotImplementedError) as raises:
cfunc = jit(nopython=True)(outer3)
cfunc(var)
msg = "Unsupported use of cell variable encountered"
self.assertIn(msg, str(raises.exception))
with self.assertRaises(NotImplementedError) as raises:
cfunc = jit(nopython=True)(outer4)
cfunc(var)
msg = "Unsupported use of cell variable encountered"
self.assertIn(msg, str(raises.exception))
with self.assertRaises(TypingError) as raises:
cfunc = jit(nopython=True)(outer11)
cfunc(var)
msg = "Cannot capture the non-constant value"
self.assertIn(msg, str(raises.exception))
with self.assertRaises(UnsupportedError) as raises:
cfunc = jit(nopython=True)(outer16)
cfunc(var)
msg = "The use of yield in a closure is unsupported."
self.assertIn(msg, str(raises.exception))
with self.assertRaises(UnsupportedError) as raises:
cfunc = jit(nopython=True)(outer17)
cfunc(var)
msg = "The use of yield in a closure is unsupported."
self.assertIn(msg, str(raises.exception))
with self.assertRaises(UnsupportedError) as raises:
cfunc = jit(nopython=True)(outer18)
cfunc(var)
msg = "The use of yield in a closure is unsupported."
self.assertIn(msg, str(raises.exception))
with self.assertRaises(UnsupportedError) as raises:
cfunc = jit(nopython=True)(outer22)
cfunc()
msg = "Calling a closure with *args is unsupported."
self.assertIn(msg, str(raises.exception))
def test_closure_renaming_scheme(self):
# See #7380, this checks that inlined (from closure) variables have a
# name derived from the function they were defined in.
@njit(pipeline_class=IRPreservingTestPipeline)
def foo(a, b):
def bar(z):
x = 5
y = 10
return x + y + z
return bar(a), bar(b)
self.assertEqual(foo(10, 20), (25, 35))
# check IR. Look for the `x = 5`... there should be
# Two lots of `const(int, 5)`, one for each inline
# The LHS of the assignment will have a name like:
# closure__locals__bar_v2_x
# Ensure that this is the case!
func_ir = foo.overloads[foo.signatures[0]].metadata['preserved_ir']
store = []
for blk in func_ir.blocks.values():
for stmt in blk.body:
if isinstance(stmt, ir.Assign):
if isinstance(stmt.value, ir.Const):
if stmt.value.value == 5:
store.append(stmt)
self.assertEqual(len(store), 2)
for i in store:
name = i.target.name
regex = r'closure__locals__bar_v[0-9]+.x'
self.assertRegex(name, regex)
def test_issue9222(self):
# Ensures that float default arguments are handled correctly in
# closures.
@njit
def foo():
def bar(x, y=1.1):
return x + y
return bar
@njit
def consume():
return foo()(4)
# In Issue #9222, the result was completely wrong - 15 instead of 5.1 -
# so allclose should be sufficient for comparison here.
np.testing.assert_allclose(consume(), 4 + 1.1)
@TestCase.run_test_in_subprocess
def test_issue_9577(self):
@njit
def _inner():
range_start = 0
for _ in range(1):
np.array([1 for _ in range(range_start, 7)])
range_start = 0
_inner()
if __name__ == '__main__':
unittest.main()
| TestInlinedClosure |
python | numba__llvmlite | llvmlite/ir/instructions.py | {
"start": 23406,
"end": 24999
} | class ____(Instruction):
def __init__(self, parent, vector1, vector2, mask, name=''):
if not isinstance(vector1.type, types.VectorType):
raise TypeError("vector1 needs to be of VectorType.")
if vector2 != Undefined:
if vector2.type != vector1.type:
raise TypeError("vector2 needs to be " +
"Undefined or of the same type as vector1.")
if (not isinstance(mask, Constant) or
not isinstance(mask.type, types.VectorType) or
not (isinstance(mask.type.element, types.IntType) and
mask.type.element.width == 32)):
raise TypeError("mask needs to be a constant i32 vector.")
typ = types.VectorType(vector1.type.element, mask.type.count)
index_range = range(vector1.type.count
if vector2 == Undefined
else 2 * vector1.type.count)
if not all(ii.constant in index_range for ii in mask.constant):
raise IndexError(
"mask values need to be in {0}".format(index_range),
)
super(ShuffleVector, self).__init__(parent, typ, "shufflevector",
[vector1, vector2, mask], name=name)
def descr(self, buf):
buf.append("shufflevector {0} {1}\n".format(
", ".join("{0} {1}".format(op.type, op.get_reference())
for op in self.operands),
self._stringify_metadata(leading_comma=True),
))
| ShuffleVector |
python | pytorch__pytorch | torch/distributed/fsdp/api.py | {
"start": 12125,
"end": 13716
} | class ____(Enum):
"""
This enum indicates that which type of ``state_dict`` the FSDP module is
currently processing (returning or loading).
The default value is FULL_STATE_DICT to comply the PyTorch convention.
.. note::
FSDP currently supports three types of ``state_dict``:
1. ``state_dict/load_state_dict`: this pair of APIs return and load
the non-sharded, unflattened parameters. The semantics is the
same as using DDP.
2. ``_local_state_dict/_load_local_state_dict``: this pair of APIs return
and load local sharded, flattened parameters. The values returned
by ``_local_state_dict`` can be directly used by FSDP and is only
meaningful to FSDP (because parameters are flattened). Note that
these APIs are meant for use via the :func:`state_dict_type`
context manager as follows:
>>> # xdoctest: +SKIP("undefined variables")
>>> with fsdp.state_dict_type(StateDictType.LOCAL_STATE_DICT):
... state = fsdp.state_dict() # loads local state dict
3. ``_sharded_state_dict/_load_sharded_state_dict``: this pair of APIs
return and load sharded, unflattened parameters. The ``state_dict``
return by ``sharded_state_dict`` can be used by all other parallel
schemes (resharding may be required).
"""
FULL_STATE_DICT = auto()
LOCAL_STATE_DICT = auto()
SHARDED_STATE_DICT = auto()
@dataclass
| StateDictType |
python | sphinx-doc__sphinx | sphinx/domains/python/__init__.py | {
"start": 9381,
"end": 9834
} | class ____(PyMethod):
"""Description of a decoratormethod."""
def run(self) -> list[Node]:
self.name = 'py:method'
return super().run()
def handle_signature(self, sig: str, signode: desc_signature) -> tuple[str, str]:
ret = super().handle_signature(sig, signode)
signode.insert(0, addnodes.desc_addname('@', '@'))
return ret
def needs_arglist(self) -> bool:
return False
| PyDecoratorMethod |
python | ray-project__ray | rllib/examples/envs/classes/debug_counter_env.py | {
"start": 102,
"end": 1007
} | class ____(gym.Env):
"""Simple Env that yields a ts counter as observation (0-based).
Actions have no effect.
The episode length is always 15.
Reward is always: current ts % 3.
"""
def __init__(self, config=None):
config = config or {}
self.action_space = gym.spaces.Discrete(2)
self.observation_space = gym.spaces.Box(0, 100, (1,), dtype=np.float32)
self.start_at_t = int(config.get("start_at_t", 0))
self.i = self.start_at_t
def reset(self, *, seed=None, options=None):
self.i = self.start_at_t
return self._get_obs(), {}
def step(self, action):
self.i += 1
terminated = False
truncated = self.i >= 15 + self.start_at_t
return self._get_obs(), float(self.i % 3), terminated, truncated, {}
def _get_obs(self):
return np.array([self.i], dtype=np.float32)
| DebugCounterEnv |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 15628,
"end": 16012
} | class ____(sgqlc.types.Enum):
"""The possible administrator roles in an enterprise account.
Enumeration Choices:
* `BILLING_MANAGER`: Represents a billing manager of the
enterprise account.
* `OWNER`: Represents an owner of the enterprise account.
"""
__schema__ = github_schema
__choices__ = ("BILLING_MANAGER", "OWNER")
| EnterpriseAdministratorRole |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_asb.py | {
"start": 11403,
"end": 14120
} | class ____:
def test_init(self):
"""
Test init by creating AzureServiceBusTopicCreateOperator with task id and topic name,
by asserting the value
"""
asb_create_topic = AzureServiceBusTopicCreateOperator(
task_id="asb_create_topic",
topic_name=TOPIC_NAME,
)
assert asb_create_topic.task_id == "asb_create_topic"
assert asb_create_topic.topic_name == TOPIC_NAME
@mock.patch("airflow.providers.microsoft.azure.hooks.asb.AdminClientHook.get_conn")
@mock.patch("azure.servicebus.management.TopicProperties")
def test_create_topic(self, mock_topic_properties, mock_get_conn):
"""
Test AzureServiceBusTopicCreateOperator passed with the topic name
mocking the connection
"""
asb_create_topic = AzureServiceBusTopicCreateOperator(
task_id="asb_create_topic",
topic_name=TOPIC_NAME,
)
mock_topic_properties.name = TOPIC_NAME
mock_get_conn.return_value.__enter__.return_value.create_topic.return_value = mock_topic_properties
# create the topic
created_topic_name = asb_create_topic.execute(None)
# ensure the topic name is returned
assert created_topic_name == TOPIC_NAME
# ensure create_topic is called with the correct arguments on the connection
mock_get_conn.return_value.__enter__.return_value.create_topic.assert_called_once_with(
topic_name=TOPIC_NAME,
default_message_time_to_live=None,
max_size_in_megabytes=None,
requires_duplicate_detection=None,
duplicate_detection_history_time_window=None,
enable_batched_operations=None,
size_in_bytes=None,
filtering_messages_before_publishing=None,
authorization_rules=None,
support_ordering=None,
auto_delete_on_idle=None,
enable_partitioning=None,
enable_express=None,
user_metadata=None,
max_message_size_in_kilobytes=None,
)
@mock.patch("airflow.providers.microsoft.azure.hooks.asb.AdminClientHook")
def test_create_topic_exception(self, mock_sb_admin_client):
"""
Test `AzureServiceBusTopicCreateOperator` functionality to raise AirflowException,
by passing topic name as None and pytest raise Airflow Exception
"""
asb_create_topic_exception = AzureServiceBusTopicCreateOperator(
task_id="create_service_bus_subscription",
topic_name=None,
)
with pytest.raises(TypeError):
asb_create_topic_exception.execute(None)
| TestABSTopicCreateOperator |
python | pallets__werkzeug | examples/cupoftee/network.py | {
"start": 180,
"end": 408
} | class ____:
last_sync = None
def sync(self):
try:
self._sync()
except (OSError, socket.timeout):
return False
self.last_sync = datetime.utcnow()
return True
| Syncable |
python | Pylons__pyramid | tests/test_httpexceptions.py | {
"start": 15536,
"end": 16848
} | class ____(unittest.TestCase):
def _makeOne(self, *arg, **kw):
from pyramid.httpexceptions import _HTTPMove
return _HTTPMove(*arg, **kw)
def test_it_location_none_valueerrors(self):
# Constructing a HTTPMove instance with location=None should
# throw a ValueError from __init__ so that a more-confusing
# exception won't be thrown later from .prepare(environ)
self.assertRaises(ValueError, self._makeOne, location=None)
def test_it_location_not_passed(self):
exc = self._makeOne()
self.assertEqual(exc.location, '')
def test_it_location_passed(self):
exc = self._makeOne(location='foo')
self.assertEqual(exc.location, 'foo')
def test_it_location_firstarg(self):
exc = self._makeOne('foo')
self.assertEqual(exc.location, 'foo')
def test_it_call_with_default_body_tmpl(self):
exc = self._makeOne(location='foo')
environ = _makeEnviron()
start_response = DummyStartResponse()
app_iter = exc(environ, start_response)
self.assertEqual(
app_iter[0],
(
b'520 Unknown Error\n\nThe resource has been moved to foo; '
b'you should be redirected automatically.\n\n'
),
)
| Test_HTTPMove |
python | streamlit__streamlit | lib/tests/streamlit/elements/vega_charts_test.py | {
"start": 2876,
"end": 19606
} | class ____(DeltaGeneratorTestCase):
"""Test the `st.altair_chart` command."""
def test_altair_chart(self):
"""Test that it can be called with args."""
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
EXPECTED_DATAFRAME = pd.DataFrame(
{
"a": ["A", "B", "C", "D"],
"b": [28, 55, 43, 91],
}
)
st.altair_chart(chart)
proto = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert not proto.HasField("data")
assert len(proto.datasets) == 1
pd.testing.assert_frame_equal(
convert_arrow_bytes_to_pandas_df(proto.datasets[0].data.data),
EXPECTED_DATAFRAME,
)
spec_dict = json.loads(proto.spec)
assert spec_dict["encoding"] == {
"y": {"field": "b", "type": "quantitative"},
"x": {"field": "a", "type": "nominal"},
}
assert spec_dict["data"] == {"name": proto.datasets[0].name}
assert spec_dict["mark"] in ["bar", {"type": "bar"}]
assert "encoding" in spec_dict
assert proto.selection_mode == []
assert proto.id == ""
assert proto.form_id == ""
def test_altair_chart_uses_convert_anything_to_df(self):
"""Test that st.altair_chart uses convert_anything_to_df to convert input data."""
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
with mock.patch(
"streamlit.dataframe_util.convert_anything_to_pandas_df"
) as convert_anything_to_df:
convert_anything_to_df.return_value = df
st.altair_chart(chart)
convert_anything_to_df.assert_called_once()
@parameterized.expand(
[
("streamlit", "streamlit"),
(None, ""),
]
)
def test_theme(self, theme_value, proto_value):
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
st.altair_chart(chart, theme=theme_value)
el = self.get_delta_from_queue().new_element
assert el.arrow_vega_lite_chart.theme == proto_value
def test_bad_theme(self):
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
with pytest.raises(StreamlitAPIException):
st.altair_chart(chart, theme="bad_theme")
def test_works_with_element_replay(self):
"""Test that element replay works for vega if used as non-widget element."""
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
@st.cache_data
def cache_element():
st.altair_chart(chart)
with patch(
"streamlit.runtime.caching.cache_utils.replay_cached_messages",
wraps=cached_message_replay.replay_cached_messages,
) as replay_cached_messages_mock:
cache_element()
el = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert el.spec != ""
# The first time the cached function is called, the replay function is not called
replay_cached_messages_mock.assert_not_called()
cache_element()
el = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert el.spec != ""
# The second time the cached function is called, the replay function is called
replay_cached_messages_mock.assert_called_once()
cache_element()
el = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert el.spec != ""
# The third time the cached function is called, the replay function is called
replay_cached_messages_mock.assert_called()
def test_empty_altair_chart_throws_error(self):
with pytest.raises(TypeError):
st.altair_chart(use_container_width=True)
@parameterized.expand(
[
("rerun", ["my_param"]),
("ignore", []),
(lambda: None, ["my_param"]),
]
)
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_altair_on_select(self, on_select: Any, expected_selection_mode: list[str]):
point = alt.selection_point(name="my_param")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(point)
st.altair_chart(chart, on_select=on_select)
proto = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert proto.selection_mode == expected_selection_mode
def test_dataset_names_stay_stable(self):
"""Test that dataset names stay stable across multiple calls
with new Pandas objects containing the same data.
"""
# Execution 1:
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
st.altair_chart(chart)
chart_el_1 = self.get_delta_from_queue().new_element
# Execution 2 (recreate the same chart with new objects)
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
st.altair_chart(chart)
chart_el_2 = self.get_delta_from_queue().new_element
# Make sure that there is one named dataset:
assert len(chart_el_1.arrow_vega_lite_chart.datasets) == 1
# The names should not have changes
assert [
dataset.name for dataset in chart_el_1.arrow_vega_lite_chart.datasets
] == [dataset.name for dataset in chart_el_2.arrow_vega_lite_chart.datasets]
# The specs should also be the same:
assert (
chart_el_1.arrow_vega_lite_chart.spec
== chart_el_2.arrow_vega_lite_chart.spec
)
@parameterized.expand(
[
(True),
(False),
("invalid"),
]
)
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_altair_on_select_invalid(self, on_select):
point = alt.selection_point(name="name")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(point)
with pytest.raises(StreamlitAPIException):
st.altair_chart(chart, on_select=on_select)
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_altair_no_name_point_selection(self):
point = alt.selection_point()
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(point)
st.altair_chart(chart, on_select="rerun")
proto = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert "param_1" in proto.spec
assert "param1" not in proto.spec
assert proto.selection_mode == ["param_1"]
assert proto.id != ""
assert proto.form_id == ""
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_altair_no_name_interval_selection(self):
interval = alt.selection_interval()
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(interval)
st.altair_chart(chart, on_select="rerun")
proto = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert "param_1" in proto.spec
assert "param1" not in proto.spec
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_altair_named_point_selection(self):
point = alt.selection_point(name="point")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(point)
st.altair_chart(chart, on_select="rerun")
proto = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert "point" in proto.spec
assert "param_1" not in proto.spec
assert proto.selection_mode == ["point"]
assert proto.id != ""
assert proto.form_id == ""
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_altair_named_interval_selection(self):
interval = alt.selection_interval(name="interval")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(interval)
st.altair_chart(chart, on_select="rerun")
proto = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert "interval" in proto.spec
assert proto.selection_mode == ["interval"]
assert proto.id != ""
assert proto.form_id == ""
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_altair_on_select_initial_returns(self):
"""Test st.altair returns an empty selection as initial result."""
interval = alt.selection_interval(name="my_param")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(interval)
event = st.altair_chart(chart, on_select="rerun", key="chart_selection")
assert event.selection.my_param == {}
# Check that the selection state is added to the session state:
assert st.session_state.chart_selection.selection.my_param == {}
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
@patch("streamlit.runtime.Runtime.exists", MagicMock(return_value=True))
def test_inside_form_on_select_rerun(self):
"""Test that form id is marshalled correctly inside of a form."""
with st.form("form"):
point = alt.selection_point(name="point")
df = pd.DataFrame(
[["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]
).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(point)
st.altair_chart(chart, on_select="rerun")
# 2 elements will be created: form block, altair_chart
assert len(self.get_all_deltas_from_queue()) == 2
form_proto = self.get_delta_from_queue(0).add_block
arrow_vega_lite_proto = self.get_delta_from_queue(
1
).new_element.arrow_vega_lite_chart
assert arrow_vega_lite_proto.form_id == form_proto.form.form_id
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
@patch("streamlit.runtime.Runtime.exists", MagicMock(return_value=True))
def test_outside_form_on_select_rerun(self):
"""Test that form id is marshalled correctly outside of a form."""
with st.form("form"):
point = alt.selection_point(name="point")
df = pd.DataFrame(
[["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]
).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(point)
st.altair_chart(chart, on_select="ignore")
# 2 elements will be created: form block, altair_chart
assert len(self.get_all_deltas_from_queue()) == 2
vega_lite_proto = self.get_delta_from_queue(1).new_element.arrow_vega_lite_chart
assert vega_lite_proto.form_id == ""
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_throws_exception_if_provided_selection_mode_not_found(self):
"""Test that an exception is thrown if the provided selection mode is not found in the spec."""
interval = alt.selection_interval(name="my_interval_selection")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(interval)
with pytest.raises(StreamlitAPIException):
st.altair_chart(
chart, on_select="rerun", selection_mode=["not_existing_param"]
)
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_respects_selection_mode_parameter(self):
"""Test that the selection_mode parameter is respected."""
interval = alt.selection_interval(name="my_interval_selection")
point = alt.selection_point(name="my_point_selection")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = (
alt.Chart(df)
.mark_bar()
.encode(x="a", y="b")
.add_params(interval)
.add_params(point)
)
st.altair_chart(chart, on_select="rerun", selection_mode=["my_point_selection"])
vega_lite_proto = self.get_delta_from_queue().new_element.arrow_vega_lite_chart
assert vega_lite_proto.selection_mode == ["my_point_selection"]
def test_throws_exception_if_no_selections_defined_in_spec(self):
"""Test that an exception is thrown if no selections are defined in the spec
but `on_select` is activated.
"""
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b")
with pytest.raises(StreamlitAPIException):
st.altair_chart(chart, on_select="rerun")
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_shows_cached_widget_replay_warning(self):
"""Test that a warning is shown when this is used with selections activated
inside a cached function."""
point = alt.selection_point(name="point")
df = pd.DataFrame([["A", "B", "C", "D"], [28, 55, 43, 91]], index=["a", "b"]).T
chart = alt.Chart(df).mark_bar().encode(x="a", y="b").add_params(point)
st.cache_data(lambda: st.altair_chart(chart, on_select="rerun"))()
# The widget itself is still created, so we need to go back one element more:
el = self.get_delta_from_queue(-2).new_element.exception
assert el.type == "CachedWidgetWarning"
assert el.is_warning
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_that_altair_chart_spec_stays_stable(self):
"""Test that st.altair_chart stays stable across multiple calls."""
# Execution 1:
chart = create_advanced_altair_chart()
st.altair_chart(chart)
initial_spec = (
self.get_delta_from_queue().new_element.arrow_vega_lite_chart.spec
)
# Create the same chart 100 times and check that the spec is the same:
for _ in range(100):
chart = create_advanced_altair_chart()
st.altair_chart(chart)
el = self.get_delta_from_queue().new_element
assert el.arrow_vega_lite_chart.spec == initial_spec
@unittest.skipIf(
is_altair_version_less_than("5.0.0") is True,
"This test only runs if altair is >= 5.0.0",
)
def test_that_selections_on_composite_charts_are_disallowed(self):
"""Test that an exception is thrown if a multi-view / composite chart
is passed with selections."""
chart = create_advanced_altair_chart()
with pytest.raises(StreamlitAPIException):
st.altair_chart(chart, on_select="rerun")
| AltairChartTest |
python | encode__django-rest-framework | tests/test_generics.py | {
"start": 1148,
"end": 1330
} | class ____(serializers.ModelSerializer):
slug = serializers.ReadOnlyField()
class Meta:
model = SlugBasedModel
fields = ('text', 'slug')
# Views
| SlugSerializer |
python | python__mypy | mypyc/irbuild/prepare.py | {
"start": 26477,
"end": 26978
} | class ____(NamedTuple):
singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]]
decorators_to_remove: dict[FuncDef, list[int]]
def find_singledispatch_register_impls(
modules: list[MypyFile], errors: Errors
) -> SingledispatchInfo:
visitor = SingledispatchVisitor(errors)
for module in modules:
visitor.current_path = module.path
module.accept(visitor)
return SingledispatchInfo(visitor.singledispatch_impls, visitor.decorators_to_remove)
| SingledispatchInfo |
python | tox-dev__tox | src/tox/config/main.py | {
"start": 586,
"end": 7201
} | class ____:
"""Main configuration object for tox."""
def __init__( # noqa: PLR0913 # <- no way around many args
self,
config_source: Source,
options: Parsed,
root: Path,
pos_args: Sequence[str] | None,
work_dir: Path,
extra_envs: Iterable[str],
) -> None:
self._pos_args = None if pos_args is None else tuple(pos_args)
self._work_dir = work_dir
self._root = root
self._options = options
self._extra_envs = extra_envs
self._overrides: OverrideMap = defaultdict(list)
for override in options.override:
self._overrides[override.namespace].append(override)
self._src = config_source
self._key_to_conf_set: dict[tuple[str, str, str], ConfigSet] = OrderedDict()
self._core_set: CoreConfigSet | None = None
self.memory_seed_loaders: defaultdict[str, list[MemoryLoader]] = defaultdict(list)
def pos_args(self, to_path: Path | None) -> tuple[str, ...] | None:
"""
:param to_path: if not None rewrite relative posargs paths from cwd to to_path
:return: positional argument
"""
if self._pos_args is not None and to_path is not None and Path.cwd() != to_path:
args = []
# we use os.path to unroll .. in path without resolve
to_path_str = os.path.abspath(str(to_path)) # noqa: PTH100
for arg in self._pos_args:
path_arg = Path(arg)
if path_arg.exists() and not path_arg.is_absolute():
# we use os.path to unroll .. in path without resolve
path_arg_str = os.path.abspath(str(path_arg)) # noqa: PTH100
# we use os.path to not fail when not within
relative = os.path.relpath(path_arg_str, to_path_str)
args.append(relative)
else:
args.append(arg)
return tuple(args)
return self._pos_args
@property
def work_dir(self) -> Path:
""":return: working directory for this project"""
return self._work_dir
@property
def src_path(self) -> Path:
""":return: the location of the tox configuration source"""
return self._src.path
def __iter__(self) -> Iterator[str]:
""":return: an iterator that goes through existing environments"""
# NOTE: `tee(self._extra_envs)[1]` is necessary for compatibility with
# NOTE: Python 3.11 and older versions. Once Python 3.12 is the lowest
# NOTE: supported version, it can be changed to
# NOTE: `chain.from_iterable(tee(self._extra_envs, 1))`.
return chain(self._src.envs(self.core), tee(self._extra_envs)[1])
def sections(self) -> Iterator[Section]:
yield from self._src.sections()
def __repr__(self) -> str:
return f"{type(self).__name__}(config_source={self._src!r})"
def __contains__(self, item: str) -> bool:
""":return: check if an environment already exists"""
return any(name for name in self if name == item)
@classmethod
def make(cls, parsed: Parsed, pos_args: Sequence[str] | None, source: Source, extra_envs: Iterable[str]) -> Config:
"""Make a tox configuration object."""
# root is the project root, where the configuration file is at
# work dir is where we put our own files
root: Path = source.path.parent if parsed.root_dir is None else parsed.root_dir
work_dir: Path = source.path.parent if parsed.work_dir is None else parsed.work_dir
# if these are relative we need to expand them them to ensure paths built on this can resolve independent on cwd
root = root.resolve()
work_dir = work_dir.resolve()
return cls(
config_source=source,
options=parsed,
pos_args=pos_args,
root=root,
work_dir=work_dir,
extra_envs=extra_envs,
)
@property
def options(self) -> Parsed:
return self._options
@property
def core(self) -> CoreConfigSet:
""":return: the core configuration"""
if self._core_set is not None:
return self._core_set
core_section = self._src.get_core_section()
core = CoreConfigSet(self, core_section, self._root, self.src_path)
core.loaders.extend(self._src.get_loaders(core_section, base=[], override_map=self._overrides, conf=core))
self._core_set = core
return core
def get_section_config(
self,
section: Section,
base: list[str] | None,
of_type: type[T],
for_env: str | None,
loaders: Sequence[Loader[Any]] | None = None,
) -> T:
key = section.key, for_env or "", "-".join(base or [])
try:
return self._key_to_conf_set[key] # type: ignore[return-value] # expected T but found ConfigSet
except KeyError:
conf_set = of_type(self, section, for_env)
self._key_to_conf_set[key] = conf_set
if for_env is not None:
conf_set.loaders.extend(self.memory_seed_loaders.get(for_env, []))
for loader in self._src.get_loaders(section, base, self._overrides, conf_set):
conf_set.loaders.append(loader)
if loaders is not None:
conf_set.loaders.extend(loaders)
return conf_set
def get_env(
self,
item: str,
package: bool = False, # noqa: FBT001, FBT002
loaders: Sequence[Loader[Any]] | None = None,
) -> EnvConfigSet:
"""
Return the configuration for a given tox environment (will create if not exist yet).
:param item: the name of the environment is
:param package: a flag indicating if the environment is of type packaging or not (only used for creation)
:param loaders: loaders to use for this configuration (only used for creation)
:return: the tox environments config
"""
section, base_test, base_pkg = self._src.get_tox_env_section(item)
return self.get_section_config(
section,
base=base_pkg if package else base_test,
of_type=EnvConfigSet,
for_env=item,
loaders=loaders,
)
def clear_env(self, name: str) -> None:
section, _, __ = self._src.get_tox_env_section(name)
self._key_to_conf_set = {k: v for k, v in self._key_to_conf_set.items() if k[0] == section.key and k[1] == name}
___all__ = [
"Config",
]
| Config |
python | apache__thrift | contrib/zeromq/TZmqServer.py | {
"start": 1897,
"end": 2709
} | class ____(object):
def __init__(self):
self.servers = []
def serveOne(self, timeout=-1):
self._serveActive(self._setupPoll(), timeout)
def serveForever(self):
poll_info = self._setupPoll()
while True:
self._serveActive(poll_info, -1)
def _setupPoll(self):
server_map = {}
poller = zmq.Poller()
for server in self.servers:
server_map[server.socket] = server
poller.register(server.socket, zmq.POLLIN)
return (server_map, poller)
def _serveActive(self, poll_info, timeout):
(server_map, poller) = poll_info
ready = dict(poller.poll())
for sock, state in ready.items():
assert (state & zmq.POLLIN) != 0
server_map[sock].serveOne()
| TZmqMultiServer |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-chatgpt-plugin/llama_index/tools/chatgpt_plugin/base.py | {
"start": 249,
"end": 2598
} | class ____(BaseToolSpec):
"""
ChatGPT Plugin Tool.
This tool leverages the OpenAPI tool spec to automatically load ChatGPT
plugins from a manifest file.
You should also provide the Requests tool spec to allow the Agent to make calls to the OpenAPI endpoints
To use endpoints with authorization, use the Requests tool spec with the authorization headers
"""
spec_functions = ["load_openapi_spec", "describe_plugin"]
def __init__(
self, manifest: Optional[dict] = None, manifest_url: Optional[str] = None
):
import yaml
if manifest and manifest_url:
raise ValueError("You cannot provide both a manifest and a manifest_url")
elif manifest:
pass
elif manifest_url:
response = requests.get(manifest_url).text
manifest = yaml.safe_load(response)
else:
raise ValueError("You must provide either a manifest or a manifest_url")
if manifest["api"]["type"] != "openapi":
raise ValueError(
f'API type must be "openapi", not "{manifest["api"]["type"]}"'
)
if manifest["auth"]["type"] != "none":
raise ValueError("Authentication cannot be supported for ChatGPT plugins")
self.openapi = OpenAPIToolSpec(url=manifest["api"]["url"])
self.plugin_description = f"""
'human_description': {manifest["description_for_human"]}
'model_description': {manifest["description_for_model"]}
"""
def load_openapi_spec(self) -> List[Document]:
"""
You are an AI agent specifically designed to retrieve information by making web requests to an API based on an OpenAPI specification.
Here's a step-by-step guide to assist you in answering questions:
1. Determine the base URL required for making the request
2. Identify the relevant paths necessary to address the question
3. Find the required parameters for making the request
4. Perform the necessary requests to obtain the answer
Returns:
Document: A List of Document objects describing the OpenAPI spec
"""
return self.openapi.load_openapi_spec()
def describe_plugin(self) -> List[Document]:
return self.plugin_description
| ChatGPTPluginToolSpec |
python | kamyu104__LeetCode-Solutions | Python/partition-array-according-to-given-pivot.py | {
"start": 44,
"end": 530
} | class ____(object):
def pivotArray(self, nums, pivot):
"""
:type nums: List[int]
:type pivot: int
:rtype: List[int]
"""
result = [pivot]*len(nums)
left, right = 0, len(nums)-sum(x > pivot for x in nums)
for x in nums:
if x < pivot:
result[left] = x
left += 1
elif x > pivot:
result[right] = x
right += 1
return result
| Solution |
python | pandas-dev__pandas | pandas/tests/apply/conftest.py | {
"start": 1877,
"end": 2045
} | class ____:
__pandas_udf__ = MockExecutionEngine
@pytest.fixture(params=[None, MockEngineDecorator])
def engine(request):
return request.param
| MockEngineDecorator |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/integrations/airbyte_cloud/define_upstream_dependencies.py | {
"start": 421,
"end": 1014
} | class ____(DagsterAirbyteTranslator):
def get_asset_spec(self, props: AirbyteConnectionTableProps) -> dg.AssetSpec:
# We create the default asset spec using super()
default_spec = super().get_asset_spec(props)
# We set an upstream dependency for our assets
return default_spec.replace_attributes(deps=["my_upstream_asset_key"])
airbyte_cloud_specs = load_airbyte_cloud_asset_specs(
airbyte_workspace, dagster_airbyte_translator=MyCustomAirbyteTranslator()
)
# end_upstream_asset
defs = dg.Definitions(assets=airbyte_cloud_specs)
| MyCustomAirbyteTranslator |
python | spyder-ide__spyder | spyder/plugins/explorer/widgets/main_widget.py | {
"start": 1068,
"end": 1199
} | class ____:
Files = 'files_section'
Header = 'header_section'
Common = 'common_section'
| ExplorerWidgetOptionsMenuSections |
python | astropy__astropy | astropy/modeling/rotations.py | {
"start": 5373,
"end": 6369
} | class ____:
"""
Base class which does the actual computation.
"""
_separable = False
def evaluate(self, alpha, delta, phi, theta, psi, axes_order):
shape = None
if isinstance(alpha, np.ndarray):
alpha = alpha.ravel()
delta = delta.ravel()
shape = alpha.shape
inp = spherical2cartesian(alpha, delta)
matrix = _create_matrix([phi, theta, psi], axes_order)
result = np.dot(matrix, inp)
a, b = cartesian2spherical(*result)
if shape is not None:
a = a.reshape(shape)
b = b.reshape(shape)
return a, b
_input_units_strict = True
_input_units_allow_dimensionless = True
@property
def input_units(self):
"""Input units."""
return {self.inputs[0]: u.deg, self.inputs[1]: u.deg}
@property
def return_units(self):
"""Output units."""
return {self.outputs[0]: u.deg, self.outputs[1]: u.deg}
| _EulerRotation |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 46545,
"end": 46954
} | class ____(Elemwise):
_projection_passthrough = True
_parameters = ["frame", "values"]
operation = M.isin
@functools.cached_property
def _meta(self):
return make_meta(
meta_nonempty(self.frame._meta).isin(
meta_nonempty(self.frame._meta).iloc[[0]]
)
)
def _broadcast_dep(self, dep: Expr):
return dep.npartitions == 1
| Isin |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer.py | {
"start": 56972,
"end": 58738
} | class ____(nn.Module):
def __init__(self, *args, feature_size: int = 256, mask_feature_size: int = 256, **kwargs):
r"""
Pixel Decoder Module proposed in [Per-Pixel Classification is Not All You Need for Semantic
Segmentation](https://huggingface.co/papers/2107.06278). It first runs the backbone's features into a Feature Pyramid
Network creating a list of feature maps. Then, it projects the last one to the correct `mask_size`.
Args:
feature_size (`int`, *optional*, defaults to 256):
The feature size (channel dimension) of the FPN feature maps.
mask_feature_size (`int`, *optional*, defaults to 256):
The features (channels) of the target masks size \\(C_{\epsilon}\\) in the paper.
"""
super().__init__()
self.fpn = MaskFormerFPNModel(*args, feature_size=feature_size, **kwargs)
self.mask_projection = nn.Conv2d(feature_size, mask_feature_size, kernel_size=3, padding=1)
def forward(
self, features: list[Tensor], output_hidden_states: bool = False, return_dict: bool = True
) -> MaskFormerPixelDecoderOutput:
fpn_features = self.fpn(features)
# we use the last feature map
last_feature_projected = self.mask_projection(fpn_features[-1])
if not return_dict:
return (last_feature_projected, tuple(fpn_features)) if output_hidden_states else (last_feature_projected,)
return MaskFormerPixelDecoderOutput(
last_hidden_state=last_feature_projected, hidden_states=tuple(fpn_features) if output_hidden_states else ()
)
# copied and adapted from original implementation, also practically equal to DetrSinePositionEmbedding
| MaskFormerPixelDecoder |
python | facebook__pyre-check | client/coverage_data.py | {
"start": 13515,
"end": 15321
} | class ____(VisitorWithPositionData):
suppression_regexes: Dict[SuppressionKind, str] = {
SuppressionKind.PYRE_FIXME: r".*# *pyre-fixme(\[(\d* *,? *)*\])?",
SuppressionKind.PYRE_IGNORE: r".*# *pyre-ignore(\[(\d* *,? *)*\])?",
SuppressionKind.TYPE_IGNORE: r".*# *type: ignore",
}
def __init__(self) -> None:
self.suppressions: List[TypeErrorSuppression] = []
@staticmethod
def _error_codes_from_re_group(
match: re.Match[str],
line: int,
) -> Optional[List[int]]:
if len(match.groups()) < 1:
code_group = None
else:
code_group = match.group(1)
if code_group is None:
return None
code_strings = code_group.strip("[] ").split(",")
try:
codes = [int(code) for code in code_strings]
return codes
except ValueError:
LOG.warning("Invalid error suppression code: %s", line)
return []
def suppression_from_comment(
self,
node: libcst.Comment,
) -> Iterable[TypeErrorSuppression]:
location = self.location(node)
for suppression_kind, regex in self.suppression_regexes.items():
match = re.match(regex, node.value)
if match is not None:
yield TypeErrorSuppression(
kind=suppression_kind,
location=location,
error_codes=self._error_codes_from_re_group(
match=match,
line=location.start_line,
),
)
def visit_Comment(self, node: libcst.Comment) -> None:
for suppression in self.suppression_from_comment(node):
self.suppressions.append(suppression)
| SuppressionCollector |
python | plotly__plotly.py | plotly/graph_objs/layout/_smith.py | {
"start": 235,
"end": 5129
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str = "layout.smith"
_valid_props = {"bgcolor", "domain", "imaginaryaxis", "realaxis"}
@property
def bgcolor(self):
"""
Set the background color of the subplot
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def domain(self):
"""
The 'domain' property is an instance of Domain
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.smith.Domain`
- A dict of string/value properties that will be passed
to the Domain constructor
Returns
-------
plotly.graph_objs.layout.smith.Domain
"""
return self["domain"]
@domain.setter
def domain(self, val):
self["domain"] = val
@property
def imaginaryaxis(self):
"""
The 'imaginaryaxis' property is an instance of Imaginaryaxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.smith.Imaginaryaxis`
- A dict of string/value properties that will be passed
to the Imaginaryaxis constructor
Returns
-------
plotly.graph_objs.layout.smith.Imaginaryaxis
"""
return self["imaginaryaxis"]
@imaginaryaxis.setter
def imaginaryaxis(self, val):
self["imaginaryaxis"] = val
@property
def realaxis(self):
"""
The 'realaxis' property is an instance of Realaxis
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.smith.Realaxis`
- A dict of string/value properties that will be passed
to the Realaxis constructor
Returns
-------
plotly.graph_objs.layout.smith.Realaxis
"""
return self["realaxis"]
@realaxis.setter
def realaxis(self, val):
self["realaxis"] = val
@property
def _prop_descriptions(self):
return """\
bgcolor
Set the background color of the subplot
domain
:class:`plotly.graph_objects.layout.smith.Domain`
instance or dict with compatible properties
imaginaryaxis
:class:`plotly.graph_objects.layout.smith.Imaginaryaxis
` instance or dict with compatible properties
realaxis
:class:`plotly.graph_objects.layout.smith.Realaxis`
instance or dict with compatible properties
"""
def __init__(
self,
arg=None,
bgcolor=None,
domain=None,
imaginaryaxis=None,
realaxis=None,
**kwargs,
):
"""
Construct a new Smith object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.layout.Smith`
bgcolor
Set the background color of the subplot
domain
:class:`plotly.graph_objects.layout.smith.Domain`
instance or dict with compatible properties
imaginaryaxis
:class:`plotly.graph_objects.layout.smith.Imaginaryaxis
` instance or dict with compatible properties
realaxis
:class:`plotly.graph_objects.layout.smith.Realaxis`
instance or dict with compatible properties
Returns
-------
Smith
"""
super().__init__("smith")
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.Smith
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.Smith`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("domain", arg, domain)
self._set_property("imaginaryaxis", arg, imaginaryaxis)
self._set_property("realaxis", arg, realaxis)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Smith |
python | huggingface__transformers | tests/models/owlv2/test_image_processing_owlv2.py | {
"start": 2895,
"end": 6800
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = Owlv2ImageProcessor if is_vision_available() else None
fast_image_processing_class = Owlv2ImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = Owlv2ImageProcessingTester(self)
@property
def image_processor_dict(self):
return self.image_processor_tester.prepare_image_processor_dict()
def test_image_processor_properties(self):
for image_processing_class in self.image_processor_list:
image_processing = image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(image_processing, "do_resize"))
self.assertTrue(hasattr(image_processing, "size"))
self.assertTrue(hasattr(image_processing, "do_normalize"))
self.assertTrue(hasattr(image_processing, "image_mean"))
self.assertTrue(hasattr(image_processing, "image_std"))
def test_image_processor_from_dict_with_kwargs(self):
for image_processing_class in self.image_processor_list:
image_processor = image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size, {"height": 18, "width": 18})
image_processor = image_processing_class.from_dict(
self.image_processor_dict, size={"height": 42, "width": 42}
)
self.assertEqual(image_processor.size, {"height": 42, "width": 42})
@slow
def test_image_processor_integration_test(self):
for image_processing_class in self.image_processor_list:
processor = image_processing_class()
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
pixel_values = processor(image, return_tensors="pt").pixel_values
mean_value = round(pixel_values.mean().item(), 4)
self.assertEqual(mean_value, 0.2353)
@slow
def test_image_processor_integration_test_resize(self):
for use_fast in [False, True]:
checkpoint = "google/owlv2-base-patch16-ensemble"
processor = AutoProcessor.from_pretrained(checkpoint, use_fast=use_fast)
model = Owlv2ForObjectDetection.from_pretrained(checkpoint)
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
text = ["cat"]
target_size = image.size[::-1]
expected_boxes = torch.tensor(
[
[341.66656494140625, 23.38756561279297, 642.321044921875, 371.3482971191406],
[6.753320693969727, 51.96149826049805, 326.61810302734375, 473.12982177734375],
]
)
# single image
inputs = processor(text=[text], images=[image], return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
results = processor.post_process_object_detection(outputs, threshold=0.2, target_sizes=[target_size])[0]
boxes = results["boxes"]
torch.testing.assert_close(boxes, expected_boxes, atol=1e-1, rtol=1e-1)
# batch of images
inputs = processor(text=[text, text], images=[image, image], return_tensors="pt")
with torch.no_grad():
outputs = model(**inputs)
results = processor.post_process_object_detection(
outputs, threshold=0.2, target_sizes=[target_size, target_size]
)
for result in results:
boxes = result["boxes"]
torch.testing.assert_close(boxes, expected_boxes, atol=1e-1, rtol=1e-1)
@unittest.skip(reason="OWLv2 doesn't treat 4 channel PIL and numpy consistently yet") # FIXME Amy
def test_call_numpy_4_channels(self):
pass
| Owlv2ImageProcessingTest |
python | huggingface__transformers | tests/models/time_series_transformer/test_modeling_time_series_transformer.py | {
"start": 7028,
"end": 19689
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(TimeSeriesTransformerModel, TimeSeriesTransformerForPrediction) if is_torch_available() else ()
)
pipeline_model_mapping = {"feature-extraction": TimeSeriesTransformerModel} if is_torch_available() else {}
is_encoder_decoder = True
test_missing_keys = False
test_inputs_embeds = False
def setUp(self):
self.model_tester = TimeSeriesTransformerModelTester(self)
self.config_tester = ConfigTester(
self,
config_class=TimeSeriesTransformerConfig,
has_text_modality=False,
prediction_length=self.model_tester.prediction_length,
)
def test_config(self):
self.config_tester.run_common_tests()
def test_save_load_strict(self):
config, _ = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
self.assertEqual(info["missing_keys"], set())
def test_encoder_decoder_model_standalone(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
@unittest.skip(reason="Model has no tokens embeddings")
def test_resize_tokens_embeddings(self):
pass
# # Input is 'static_categorical_features' not 'input_ids'
def test_model_main_input_name(self):
model_signature = inspect.signature(getattr(TimeSeriesTransformerModel, "forward"))
# The main input is the name of the argument after `self`
observed_main_input_name = list(model_signature.parameters.keys())[1]
self.assertEqual(TimeSeriesTransformerModel.main_input_name, observed_main_input_name)
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
arg_names = [*signature.parameters.keys()]
expected_arg_names = [
"past_values",
"past_time_features",
"past_observed_mask",
"static_categorical_features",
"static_real_features",
"future_values",
"future_time_features",
]
expected_arg_names.extend(
[
"future_observed_mask",
"decoder_attention_mask",
"encoder_outputs",
"past_key_values",
"output_hidden_states",
"output_attentions",
"use_cache",
"return_dict",
]
if "future_observed_mask" in arg_names
else [
"decoder_attention_mask",
"encoder_outputs",
"past_key_values",
"output_hidden_states",
"output_attentions",
"use_cache",
"return_dict",
]
)
self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
def test_attention_outputs(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.return_dict = True
seq_len = getattr(self.model_tester, "seq_length", None)
decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len)
encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
for model_class in self.all_model_classes:
inputs_dict["output_attentions"] = True
inputs_dict["output_hidden_states"] = False
config.return_dict = True
model = model_class._from_config(config, attn_implementation="eager")
config = model.config
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
config.output_attentions = True
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
attentions = outputs.encoder_attentions
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
self.assertListEqual(
list(attentions[0].shape[-3:]),
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_seq_length],
)
out_len = len(outputs)
correct_outlen = 7
if "last_hidden_state" in outputs:
correct_outlen += 1
if "past_key_values" in outputs:
correct_outlen += 1 # past_key_values have been returned
if "loss" in outputs:
correct_outlen += 1
if "params" in outputs:
correct_outlen += 1
self.assertEqual(out_len, correct_outlen)
# decoder attentions
decoder_attentions = outputs.decoder_attentions
self.assertIsInstance(decoder_attentions, (list, tuple))
self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
self.assertListEqual(
list(decoder_attentions[0].shape[-3:]),
[self.model_tester.num_attention_heads, decoder_seq_length, decoder_seq_length],
)
# cross attentions
cross_attentions = outputs.cross_attentions
self.assertIsInstance(cross_attentions, (list, tuple))
self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
self.assertListEqual(
list(cross_attentions[0].shape[-3:]),
[
self.model_tester.num_attention_heads,
decoder_seq_length,
encoder_seq_length,
],
)
# Check attention is always last and order is fine
inputs_dict["output_attentions"] = True
inputs_dict["output_hidden_states"] = True
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
self.assertEqual(out_len + 2, len(outputs))
self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
self.assertListEqual(
list(self_attentions[0].shape[-3:]),
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_seq_length],
)
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip(
reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
)
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
@parameterized.expand(
[
(1, 5, [1]),
(1, 5, [1, 10, 15]),
(1, 5, [3, 6, 9, 10]),
(2, 5, [1, 2, 7]),
(2, 5, [2, 3, 4, 6]),
(4, 5, [1, 5, 9, 11]),
(4, 5, [7, 8, 13, 14]),
],
)
def test_create_network_inputs(self, prediction_length, context_length, lags_sequence):
history_length = max(lags_sequence) + context_length
config = TimeSeriesTransformerConfig(
prediction_length=prediction_length,
context_length=context_length,
lags_sequence=lags_sequence,
scaling=False,
num_parallel_samples=10,
num_static_categorical_features=1,
cardinality=[1],
embedding_dimension=[2],
num_static_real_features=1,
)
model = TimeSeriesTransformerModel(config)
batch = {
"static_categorical_features": torch.tensor([[0]], dtype=torch.int64),
"static_real_features": torch.tensor([[0.0]], dtype=torch.float32),
"past_time_features": torch.arange(history_length, dtype=torch.float32).view(1, history_length, 1),
"past_values": torch.arange(history_length, dtype=torch.float32).view(1, history_length),
"past_observed_mask": torch.arange(history_length, dtype=torch.float32).view(1, history_length),
}
# test with no future_target (only one step prediction)
batch["future_time_features"] = torch.arange(history_length, history_length + 1, dtype=torch.float32).view(
1, 1, 1
)
transformer_inputs, loc, scale, _ = model.create_network_inputs(**batch)
self.assertTrue((scale == 1.0).all())
assert (loc == 0.0).all()
ref = torch.arange(max(lags_sequence), history_length, dtype=torch.float32)
for idx, lag in enumerate(lags_sequence):
assert torch.isclose(ref - lag, transformer_inputs[0, :, idx]).all()
# test with all future data
batch["future_time_features"] = torch.arange(
history_length, history_length + prediction_length, dtype=torch.float32
).view(1, prediction_length, 1)
batch["future_values"] = torch.arange(
history_length, history_length + prediction_length, dtype=torch.float32
).view(1, prediction_length)
transformer_inputs, loc, scale, _ = model.create_network_inputs(**batch)
assert (scale == 1.0).all()
assert (loc == 0.0).all()
ref = torch.arange(max(lags_sequence), history_length + prediction_length, dtype=torch.float32)
for idx, lag in enumerate(lags_sequence):
assert torch.isclose(ref - lag, transformer_inputs[0, :, idx]).all()
# test for generation
batch.pop("future_values")
transformer_inputs, loc, scale, _ = model.create_network_inputs(**batch)
lagged_sequence = model.get_lagged_subsequences(
sequence=batch["past_values"],
subsequences_length=1,
shift=1,
)
# assert that the last element of the lagged sequence is the one after the encoders input
assert transformer_inputs[0, ..., 0][-1] + 1 == lagged_sequence[0, ..., 0][-1]
future_values = torch.arange(history_length, history_length + prediction_length, dtype=torch.float32).view(
1, prediction_length
)
# assert that the first element of the future_values is offset by lag after the decoders input
assert lagged_sequence[0, ..., 0][-1] + lags_sequence[0] == future_values[0, ..., 0]
@is_flaky()
def test_retain_grad_hidden_states_attentions(self):
super().test_retain_grad_hidden_states_attentions()
@unittest.skip(reason="Model does not have input embeddings")
def test_model_get_set_embeddings(self):
pass
def prepare_batch(filename="train-batch.pt"):
file = hf_hub_download(repo_id="hf-internal-testing/tourism-monthly-batch", filename=filename, repo_type="dataset")
check_torch_load_is_safe()
batch = torch.load(file, map_location=torch_device, weights_only=True)
return batch
@require_torch
@slow
| TimeSeriesTransformerModelTest |
python | jschneier__django-storages | storages/utils.py | {
"start": 4679,
"end": 5536
} | class ____(FileProxyMixin):
"""
A wrapper for a file-like object, that makes read() always returns bytes.
"""
def __init__(self, file, encoding=None):
"""
:param file: The file-like object to wrap.
:param encoding: Specify the encoding to use when file.read() returns strings.
If not provided will default to file.encoding, of if that's not available,
to utf-8.
"""
self.file = file
self._encoding = encoding or getattr(file, "encoding", None) or "utf-8"
def read(self, *args, **kwargs):
content = self.file.read(*args, **kwargs)
if not isinstance(content, bytes):
content = content.encode(self._encoding)
return content
def close(self):
self.file.close()
def readable(self):
return True
| ReadBytesWrapper |
python | realpython__materials | django-diary/source_code_step_6/entries/views.py | {
"start": 446,
"end": 653
} | class ____(SuccessMessageMixin, CreateView):
model = Entry
fields = ["title", "content"]
success_url = reverse_lazy("entry-list")
success_message = "Your new entry was created!"
| EntryCreateView |
python | sqlalchemy__sqlalchemy | test/ext/test_baked.py | {
"start": 894,
"end": 3225
} | class ____(BakedTest):
@classmethod
def setup_mappers(cls):
User = cls.classes.User
cls.mapper_registry.map_imperatively(User, cls.tables.users)
def _assert_cache_key(self, key, elements):
eq_(key, tuple(elem.__code__ for elem in elements))
def test_initial_key(self):
User = self.classes.User
session = fixture_session()
def l1():
return session.query(User)
q1 = self.bakery(l1)
self._assert_cache_key(q1._cache_key, [l1])
eq_(q1.steps, [l1])
def test_inplace_add(self):
User = self.classes.User
session = fixture_session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
self._assert_cache_key(q1._cache_key, [l1])
eq_(q1.steps, [l1])
q2 = q1.add_criteria(l2)
is_(q2, q1)
self._assert_cache_key(q1._cache_key, [l1, l2])
eq_(q1.steps, [l1, l2])
def test_inplace_add_operator(self):
User = self.classes.User
session = fixture_session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
self._assert_cache_key(q1._cache_key, [l1])
q1 += l2
self._assert_cache_key(q1._cache_key, [l1, l2])
def test_chained_add(self):
User = self.classes.User
session = fixture_session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
q2 = q1.with_criteria(l2)
is_not(q2, q1)
self._assert_cache_key(q1._cache_key, [l1])
self._assert_cache_key(q2._cache_key, [l1, l2])
def test_chained_add_operator(self):
User = self.classes.User
session = fixture_session()
def l1():
return session.query(User)
def l2(q):
return q.filter(User.name == bindparam("name"))
q1 = self.bakery(l1)
q2 = q1 + l2
is_not(q2, q1)
self._assert_cache_key(q1._cache_key, [l1])
self._assert_cache_key(q2._cache_key, [l1, l2])
| StateChangeTest |
python | GoogleCloudPlatform__python-docs-samples | functions/v2/typed/greeting/main.py | {
"start": 686,
"end": 997
} | class ____:
first_name: str
last_name: str
# Required to deserialize the request
@staticmethod
def from_dict(req: dict) -> "GreetingRequest":
return GreetingRequest(
first_name=req["first_name"],
last_name=req["last_name"],
)
@dataclass
| GreetingRequest |
python | openai__openai-python | src/openai/types/responses/response_output_text.py | {
"start": 2272,
"end": 2367
} | class ____(BaseModel):
token: str
bytes: List[int]
logprob: float
| LogprobTopLogprob |
python | apache__thrift | lib/py/test/thrift_transport.py | {
"start": 891,
"end": 1598
} | class ____(unittest.TestCase):
def test_TFileObjectTransport(self):
test_dir = os.path.dirname(os.path.abspath(__file__))
datatxt_path = os.path.join(test_dir, 'data.txt')
buffer = '{"soft":"thrift","version":0.13,"1":true}'
with open(datatxt_path, "w+") as f:
buf = TTransport.TFileObjectTransport(f)
buf.write(buffer)
buf.flush()
buf.close()
with open(datatxt_path, "rb") as f:
buf = TTransport.TFileObjectTransport(f)
value = buf.read(len(buffer)).decode('utf-8')
self.assertEqual(buffer, value)
buf.close()
os.remove(datatxt_path)
| TestTFileObjectTransport |
python | skorch-dev__skorch | skorch/tests/callbacks/test_scoring.py | {
"start": 34879,
"end": 39419
} | class ____:
@pytest.fixture
def scoring_cls(self, request):
from skorch.callbacks import PassthroughScoring
return PassthroughScoring
@pytest.fixture
def train_loss(self, scoring_cls):
# use train batch size to stand in for batch-level scores
return scoring_cls(name='train_batch_size', on_train=True)
@pytest.fixture
def valid_loss(self, scoring_cls):
# use valid batch size to stand in for batch-level scores
return scoring_cls(name='valid_batch_size')
@pytest.fixture
def net(self, classifier_module, train_loss, valid_loss, classifier_data):
from skorch import NeuralNetClassifier
net = NeuralNetClassifier(
classifier_module,
batch_size=10,
# use train and valid batch size to stand in for
# batch-level scores
callbacks=[train_loss, valid_loss],
max_epochs=2)
X, y = classifier_data
n = 75
# n=75 with a 4/5 train/valid split -> 60/15 samples; with a
# batch size of 10, that leads to train batch sizes of
# [10,10,10,10] and valid batch sizes of [10,5]; all labels
# are set to 0 to ensure that the stratified split is exactly
# equal to the desired split
y = np.zeros_like(y)
return net.fit(X[:n], y[:n])
@pytest.fixture
def history(self, net):
return net.history
@pytest.fixture
def history_empty(self):
from skorch.history import History
return History()
def test_correct_train_pass_through_scores(self, history):
# train: average of [10,10,10,10,10] is 10
train_scores = history[:, 'train_batch_size']
assert np.allclose(train_scores, 10.0)
def test_correct_valid_pass_through_scores(self, history):
# valid: average of [10,5] with weights also being [10,5] =
# (10*10 + 5*5)/15
expected = (10 * 10 + 5 * 5) / 15 # 8.333..
valid_losses = history[:, 'valid_batch_size']
assert np.allclose(valid_losses, [expected, expected])
def test_missing_entry_in_epoch(self, scoring_cls, history_empty):
"""We skip one entry in history_empty. This batch should simply be
ignored.
"""
history_empty.new_epoch()
history_empty.new_batch()
history_empty.record_batch('score', 10)
history_empty.record_batch('train_batch_size', 10)
history_empty.new_batch()
# this score is ignored since it has no associated batch size
history_empty.record_batch('score', 20)
net = Mock(history=history_empty)
cb = scoring_cls(name='score', on_train=True).initialize()
cb.on_epoch_end(net)
train_score = history_empty[-1, 'score']
assert np.isclose(train_score, 10.0)
@pytest.mark.parametrize('lower_is_better, expected', [
(True, [True, True, True, False, False]),
(False, [True, False, False, True, False]),
(None, []),
])
def test_lower_is_better_is_honored(
self, net_cls, module_cls, scoring_cls, train_split, data,
history_empty, lower_is_better, expected,
):
# results in expected patterns of True and False
scores = [10, 8, 6, 11, 7]
cb = scoring_cls(
name='score',
lower_is_better=lower_is_better,
).initialize()
net = Mock(history=history_empty)
for score in scores:
history_empty.new_epoch()
history_empty.new_batch()
history_empty.record_batch('score', score)
history_empty.record_batch('valid_batch_size', 55) # doesn't matter
cb.on_epoch_end(net)
if lower_is_better is not None:
is_best = history_empty[:, 'score_best']
assert is_best == expected
else:
# if lower_is_better==None, don't write score
with pytest.raises(KeyError):
# pylint: disable=pointless-statement
history_empty[:, 'score_best']
def test_no_error_when_no_valid_data(
self, net_cls, module_cls, scoring_cls, data,
):
# we set the name to 'valid_batch_size' but disable
# train/valid split -- there should be no error
net = net_cls(
module_cls,
callbacks=[scoring_cls(name='valid_batch_size')],
max_epochs=1,
train_split=None,
)
# does not raise
net.fit(*data)
| TestPassthrougScoring |
python | pytest-dev__pytest | testing/test_skipping.py | {
"start": 36509,
"end": 43534
} | class ____:
def test_skipif(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.skipif(True, reason="True123")
def test_func1():
pass
@pytest.mark.skipif(False, reason="True123")
def test_func2():
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"""
*1 passed*1 skipped*
"""
)
def test_skipif_noreason(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.skipif(True)
def test_func():
pass
"""
)
result = pytester.runpytest("-rs")
result.stdout.fnmatch_lines(
"""
*1 error*
"""
)
def test_xfail(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.xfail(True, reason="True123")
def test_func():
assert 0
"""
)
result = pytester.runpytest("-rxs")
result.stdout.fnmatch_lines(
"""
*XFAIL*True123*
*1 xfail*
"""
)
def test_xfail_item(pytester: Pytester) -> None:
# Ensure pytest.xfail works with non-Python Item
pytester.makeconftest(
"""
import pytest
class MyItem(pytest.Item):
nodeid = 'foo'
def runtest(self):
pytest.xfail("Expected Failure")
def pytest_collect_file(file_path, parent):
return MyItem.from_parent(name="foo", parent=parent)
"""
)
result = pytester.inline_run()
_passed, skipped, failed = result.listoutcomes()
assert not failed
xfailed = [r for r in skipped if hasattr(r, "wasxfail")]
assert xfailed
def test_module_level_skip_error(pytester: Pytester) -> None:
"""Verify that using pytest.skip at module level causes a collection error."""
pytester.makepyfile(
"""
import pytest
pytest.skip("skip_module_level")
def test_func():
assert True
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
["*Using pytest.skip outside of a test will skip the entire module*"]
)
def test_module_level_skip_with_allow_module_level(pytester: Pytester) -> None:
"""Verify that using pytest.skip(allow_module_level=True) is allowed."""
pytester.makepyfile(
"""
import pytest
pytest.skip("skip_module_level", allow_module_level=True)
def test_func():
assert 0
"""
)
result = pytester.runpytest("-rxs")
result.stdout.fnmatch_lines(["*SKIP*skip_module_level"])
def test_invalid_skip_keyword_parameter(pytester: Pytester) -> None:
"""Verify that using pytest.skip() with unknown parameter raises an error."""
pytester.makepyfile(
"""
import pytest
pytest.skip("skip_module_level", unknown=1)
def test_func():
assert 0
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*TypeError:*['unknown']*"])
def test_mark_xfail_item(pytester: Pytester) -> None:
# Ensure pytest.mark.xfail works with non-Python Item
pytester.makeconftest(
"""
import pytest
class MyItem(pytest.Item):
nodeid = 'foo'
def setup(self):
marker = pytest.mark.xfail("1 == 2", reason="Expected failure - false")
self.add_marker(marker)
marker = pytest.mark.xfail(True, reason="Expected failure - true")
self.add_marker(marker)
def runtest(self):
assert False
def pytest_collect_file(file_path, parent):
return MyItem.from_parent(name="foo", parent=parent)
"""
)
result = pytester.inline_run()
_passed, skipped, failed = result.listoutcomes()
assert not failed
xfailed = [r for r in skipped if hasattr(r, "wasxfail")]
assert xfailed
def test_summary_list_after_errors(pytester: Pytester) -> None:
"""Ensure the list of errors/fails/xfails/skips appears after tracebacks in terminal reporting."""
pytester.makepyfile(
"""
import pytest
def test_fail():
assert 0
"""
)
result = pytester.runpytest("-ra")
result.stdout.fnmatch_lines(
[
"=* FAILURES *=",
"*= short test summary info =*",
"FAILED test_summary_list_after_errors.py::test_fail - assert 0",
]
)
def test_importorskip() -> None:
with pytest.raises(
pytest.skip.Exception,
match=r"^could not import 'doesnotexist': No module named .*",
):
pytest.importorskip("doesnotexist")
def test_relpath_rootdir(pytester: Pytester) -> None:
pytester.makepyfile(
**{
"tests/test_1.py": """
import pytest
@pytest.mark.skip()
def test_pass():
pass
""",
}
)
result = pytester.runpytest("-rs", "tests/test_1.py", "--rootdir=tests")
result.stdout.fnmatch_lines(
["SKIPPED [[]1[]] tests/test_1.py:2: unconditional skip"]
)
def test_skip_from_fixture(pytester: Pytester) -> None:
pytester.makepyfile(
**{
"tests/test_1.py": """
import pytest
def test_pass(arg):
pass
@pytest.fixture
def arg():
condition = True
if condition:
pytest.skip("Fixture conditional skip")
""",
}
)
result = pytester.runpytest("-rs", "tests/test_1.py", "--rootdir=tests")
result.stdout.fnmatch_lines(
["SKIPPED [[]1[]] tests/test_1.py:2: Fixture conditional skip"]
)
def test_skip_using_reason_works_ok(pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
def test_skipping_reason():
pytest.skip(reason="skippedreason")
"""
)
result = pytester.runpytest(p)
result.stdout.no_fnmatch_line("*PytestDeprecationWarning*")
result.assert_outcomes(skipped=1)
def test_fail_using_reason_works_ok(pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
def test_failing_reason():
pytest.fail(reason="failedreason")
"""
)
result = pytester.runpytest(p)
result.stdout.no_fnmatch_line("*PytestDeprecationWarning*")
result.assert_outcomes(failed=1)
def test_exit_with_reason_works_ok(pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
import pytest
def test_exit_reason_only():
pytest.exit(reason="foo")
"""
)
result = pytester.runpytest(p)
result.stdout.fnmatch_lines("*_pytest.outcomes.Exit: foo*")
| TestBooleanCondition |
python | pytorch__pytorch | torch/testing/_internal/common_utils.py | {
"start": 117471,
"end": 118573
} | class ____(Pair):
"""Fallback ABC pair that handles non-numeric inputs.
To avoid recreating the mismatch messages of :meth:`unittest.TestCase.assertEqual`, this pair simply wraps it in
order to use it with the :class:`Pair` "framework" from :func:`are_equal`.
Define the :attr:`UnittestPair.CLS` in a subclass to indicate which class(es) of the inputs the pair should support.
"""
CLS: Union[type, tuple[type, ...]]
TYPE_NAME: Optional[str] = None
def __init__(self, actual, expected, **other_parameters):
self._check_inputs_isinstance(actual, expected, cls=self.CLS)
super().__init__(actual, expected, **other_parameters)
def compare(self):
test_case = unittest.TestCase()
try:
return test_case.assertEqual(self.actual, self.expected)
except test_case.failureException as error:
msg = str(error)
type_name = self.TYPE_NAME or (self.CLS if isinstance(self.CLS, type) else self.CLS[0]).__name__
self._fail(AssertionError, f"{type_name.title()} comparison failed: {msg}")
| UnittestPair |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py | {
"start": 19268,
"end": 20322
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreMemcachedHook")
def test_assert_valid_hook_call(self, mock_hook):
task = CloudMemorystoreMemcachedListInstancesOperator(
task_id=TEST_TASK_ID,
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
task.execute(mock.MagicMock())
mock_hook.assert_called_once_with(
gcp_conn_id=TEST_GCP_CONN_ID,
impersonation_chain=TEST_IMPERSONATION_CHAIN,
)
mock_hook.return_value.list_instances.assert_called_once_with(
location=TEST_LOCATION,
project_id=TEST_PROJECT_ID,
retry=TEST_RETRY,
timeout=TEST_TIMEOUT,
metadata=TEST_METADATA,
)
| TestCloudMemorystoreMemcachedListInstancesOperator |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/freshness_tests/test_internal_freshness.py | {
"start": 1525,
"end": 2134
} | class ____:
def test_apply_freshness_policy_explicit_none_fails(self) -> None:
"""Check that we cannot apply a null policy to assets."""
@asset
def asset_no_freshness():
pass
defs = dg.Definitions(assets=[asset_no_freshness])
with pytest.raises(ParameterCheckError):
defs.map_asset_specs(
func=lambda spec: apply_freshness_policy(
spec,
None, # pyright: ignore[reportArgumentType]
overwrite_existing=False,
)
)
| TestApplyFreshnessPolicy |
python | openai__gym | gym/error.py | {
"start": 1484,
"end": 1607
} | class ____(Error):
"""Raised when the user requests a rendering mode not supported by the environment."""
| UnsupportedMode |
python | google__jax | tests/pallas/tpu_pallas_test.py | {
"start": 25829,
"end": 25919
} | class ____(PallasCallDynamicGridTest):
INTERPRET = True
| PallasCallDynamicGridInterpretTest |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 14684,
"end": 14849
} | class ____(QueryExecutionError):
"""
Exception raised when a function in the query is provided an invalid
argument type.
"""
| QueryIllegalTypeOfArgument |
python | django__django | django/db/models/functions/datetime.py | {
"start": 13437,
"end": 13571
} | class ____(TruncBase):
kind = "second"
DateTimeField.register_lookup(TruncDate)
DateTimeField.register_lookup(TruncTime)
| TruncSecond |
python | spack__spack | lib/spack/spack/new_installer.py | {
"start": 17415,
"end": 25741
} | class ____:
"""Attach to an existing POSIX jobserver or create a FIFO-based one."""
def __init__(self, num_jobs: int) -> None:
#: Keep track of how many tokens Spack itself has acquired, which is used to release them.
self.tokens_acquired = 0
self.num_jobs = num_jobs
self.fifo_path: Optional[str] = None
self.created = False
self._setup()
# Ensure that Executable()(...) in build processes ultimately inherit jobserver fds.
os.set_inheritable(self.r, True)
os.set_inheritable(self.w, True)
# r_conn and w_conn are used to make build processes inherit the jobserver fds if needed.
# Connection objects close the fd as they are garbage collected, so store them.
self.r_conn = Connection(self.r)
self.w_conn = Connection(self.w)
def _setup(self) -> None:
fifo_config = get_jobserver_config()
if type(fifo_config) is str:
# FIFO-based jobserver. Try to open the FIFO.
open_attempt = open_existing_jobserver_fifo(fifo_config)
if open_attempt:
self.r, self.w = open_attempt
self.fifo_path = fifo_config
return
elif type(fifo_config) is tuple:
# Old style pipe-based jobserver. Validate the fds before using them.
r, w = fifo_config
if fcntl.fcntl(r, fcntl.F_GETFD) != -1 and fcntl.fcntl(w, fcntl.F_GETFD) != -1:
self.r, self.w = r, w
return
# No existing jobserver we can connect to: create a FIFO-based one.
self.r, self.w, self.fifo_path = create_jobserver_fifo(self.num_jobs)
self.created = True
def makeflags(self, gmake: Optional[spack.spec.Spec]) -> str:
"""Return the MAKEFLAGS for a build process, depending on its gmake build dependency."""
if self.fifo_path and (not gmake or gmake.satisfies("@4.4:")):
return f" -j{self.num_jobs} --jobserver-auth=fifo:{self.fifo_path}"
elif not gmake or gmake.satisfies("@4.0:"):
return f" -j{self.num_jobs} --jobserver-auth={self.r},{self.w}"
else:
return f" -j{self.num_jobs} --jobserver-fds={self.r},{self.w}"
def acquire(self, jobs: int) -> int:
"""Try and acquire at most 'jobs' tokens from the jobserver. Returns the number of
tokens actually acquired (may be less than requested, or zero)."""
try:
num_acquired = len(os.read(self.r, jobs))
self.tokens_acquired += num_acquired
return num_acquired
except BlockingIOError:
return 0
def release(self) -> None:
"""Release a token back to the jobserver."""
# The last job to quit has an implicit token, so don't release if we have none.
if self.tokens_acquired == 0:
return
os.write(self.w, b"+")
self.tokens_acquired -= 1
def close(self) -> None:
# Remove the FIFO if we created it.
if self.created and self.fifo_path:
try:
os.unlink(self.fifo_path)
except OSError:
pass
try:
os.rmdir(os.path.dirname(self.fifo_path))
except OSError:
pass
# TODO: implement a sanity check here:
# 1. did we release all tokens we acquired?
# 2. if we created the jobserver, did the children return all tokens?
self.r_conn.close()
self.w_conn.close()
def start_build(
spec: spack.spec.Spec,
explicit: bool,
mirrors: List[spack.url_buildcache.MirrorURLAndVersion],
unsigned: Optional[bool],
install_policy: InstallPolicy,
dirty: bool,
keep_stage: bool,
restage: bool,
overwrite: bool,
keep_prefix: bool,
skip_patch: bool,
jobserver: JobServer,
) -> ChildInfo:
"""Start a new build."""
# Create pipes for the child's output, state reporting, and control.
state_r_conn, state_w_conn = Pipe(duplex=False)
output_r_conn, output_w_conn = Pipe(duplex=False)
control_r_conn, control_w_conn = Pipe(duplex=False)
# Obtain the MAKEFLAGS to be set in the child process, and determine whether it's necessary
# for the child process to inherit our jobserver fds.
gmake = next(iter(spec.dependencies("gmake")), None)
makeflags = jobserver.makeflags(gmake)
fifo = "--jobserver-auth=fifo:" in makeflags
proc = Process(
target=worker_function,
args=(
spec,
explicit,
mirrors,
unsigned,
install_policy,
dirty,
keep_stage,
restage,
overwrite,
keep_prefix,
skip_patch,
state_w_conn,
output_w_conn,
control_r_conn,
makeflags,
None if fifo else jobserver.r_conn,
None if fifo else jobserver.w_conn,
spack.store.STORE,
spack.config.CONFIG,
),
)
proc.start()
# The parent process does not need the write ends of the main pipes or the read end of control.
state_w_conn.close()
output_w_conn.close()
control_r_conn.close()
# Set the read ends to non-blocking: in principle redundant with epoll/kqueue, but safer.
os.set_blocking(output_r_conn.fileno(), False)
os.set_blocking(state_r_conn.fileno(), False)
return ChildInfo(proc, spec, output_r_conn, state_r_conn, control_w_conn, explicit)
def reap_children(
child_data: Dict[int, ChildInfo], selector: selectors.BaseSelector, jobserver: JobServer
) -> List[int]:
"""Reap terminated child processes"""
to_delete: List[int] = []
for pid, child in child_data.items():
if child.proc.is_alive():
continue
to_delete.append(pid)
jobserver.release()
child.cleanup(selector)
return to_delete
def get_jobserver_config(makeflags: Optional[str] = None) -> Optional[Union[str, Tuple[int, int]]]:
"""Parse MAKEFLAGS for jobserver. Either it's a FIFO or (r, w) pair of file descriptors.
Args:
makeflags: MAKEFLAGS string to parse. If None, reads from os.environ.
"""
makeflags = os.environ.get("MAKEFLAGS", "") if makeflags is None else makeflags
if not makeflags:
return None
# We can have the following flags:
# --jobserver-fds=R,W (before GNU make 4.2)
# --jobserver-auth=fifo:PATH or --jobserver-auth=R,W (after GNU make 4.2)
# In case of multiple, the last one wins.
matches = re.findall(r" --jobserver-[^=]+=([^ ]+)", makeflags)
if not matches:
return None
last_match: str = matches[-1]
assert isinstance(last_match, str)
if last_match.startswith("fifo:"):
return last_match[5:]
parts = last_match.split(",", 1)
if len(parts) != 2:
return None
try:
return int(parts[0]), int(parts[1])
except ValueError:
return None
def create_jobserver_fifo(num_jobs: int) -> Tuple[int, int, str]:
"""Create a new jobserver FIFO with the specified number of job tokens."""
tmpdir = tempfile.mkdtemp()
fifo_path = os.path.join(tmpdir, "jobserver_fifo")
try:
os.mkfifo(fifo_path, 0o600)
read_fd = os.open(fifo_path, os.O_RDONLY | os.O_NONBLOCK)
write_fd = os.open(fifo_path, os.O_WRONLY)
# write num_jobs - 1 tokens, because the first job is implicit
os.write(write_fd, b"+" * (num_jobs - 1))
return read_fd, write_fd, fifo_path
except Exception:
try:
os.unlink(fifo_path)
except OSError as e:
spack.llnl.util.tty.debug(f"Failed to remove POSIX jobserver FIFO: {e}", level=3)
pass
try:
os.rmdir(tmpdir)
except OSError as e:
spack.llnl.util.tty.debug(f"Failed to remove POSIX jobserver FIFO dir: {e}", level=3)
pass
raise
def open_existing_jobserver_fifo(fifo_path: str) -> Optional[Tuple[int, int]]:
"""Open an existing jobserver FIFO for reading and writing."""
try:
read_fd = os.open(fifo_path, os.O_RDONLY | os.O_NONBLOCK)
write_fd = os.open(fifo_path, os.O_WRONLY)
return read_fd, write_fd
except OSError:
return None
| JobServer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-amazon-ads/unit_tests/integrations/ad_responses/records/report_check_status_record_builder.py | {
"start": 221,
"end": 1223
} | class ____(RecordBuilder):
@classmethod
def status_record(cls) -> "ReportCheckStatusRecordBuilder":
return cls(
find_template("report_status_response", __file__), id_path=None, status_path=FieldPath("status"), url_path=FieldPath("url")
)
def __init__(
self,
template: Dict[str, Any],
id_path: Optional[Path] = None,
status_path: Optional[Path] = None,
url_path: Optional[Path] = None,
cursor_path: Optional[Union[FieldPath, NestedPath]] = None,
):
super().__init__(template, id_path, cursor_path)
self._status_path = status_path
self._url_path = url_path
def with_status(self, status: str) -> "ReportCheckStatusRecordBuilder":
self._set_field("status", self._status_path, status)
return self
def with_url(self, url: str) -> "ReportCheckStatusRecordBuilder":
self._set_field("status", self._url_path, url)
return self
| ReportCheckStatusRecordBuilder |
python | getsentry__sentry | src/sentry/sentry_apps/installations.py | {
"start": 1991,
"end": 4179
} | class ____:
sentry_app_installation: SentryAppInstallation
expires_at: datetime.date | None = None
def run(self, user: User | RpcUser, request: HttpRequest | None = None) -> ApiToken:
with transaction.atomic(router.db_for_write(ApiToken)):
self._check_token_limit()
api_token = self._create_api_token()
self._create_sentry_app_installation_token(api_token=api_token)
self.record_analytics(user)
return api_token
def _check_token_limit(self) -> None:
curr_count = SentryAppInstallationToken.objects.filter(
sentry_app_installation=self.sentry_app_installation
).count()
if curr_count >= INTERNAL_INTEGRATION_TOKEN_COUNT_MAX:
raise ApiTokenLimitError(
"Cannot generate more than %d tokens for a single integration"
% INTERNAL_INTEGRATION_TOKEN_COUNT_MAX
)
def _create_api_token(self) -> ApiToken:
return ApiToken.objects.create(
user=self.sentry_app.proxy_user,
application_id=self.sentry_app.application_id,
scope_list=self.sentry_app.scope_list,
expires_at=self.expires_at,
)
def _create_sentry_app_installation_token(
self, api_token: ApiToken
) -> SentryAppInstallationToken:
return SentryAppInstallationToken.objects.create(
api_token=api_token, sentry_app_installation=self.sentry_app_installation
)
def record_analytics(self, user: User | RpcUser) -> None:
from sentry import analytics
analytics.record(
SentryAppInstallationTokenCreated(
user_id=user.id,
organization_id=self.organization_id,
sentry_app_installation_id=self.sentry_app_installation.id,
sentry_app=self.sentry_app.slug,
)
)
@cached_property
def sentry_app(self) -> SentryApp:
return self.sentry_app_installation.sentry_app
@cached_property
def organization_id(self) -> int:
return self.sentry_app_installation.organization_id
@dataclasses.dataclass
| SentryAppInstallationTokenCreator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 689904,
"end": 690292
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("LinkedBranch", graphql_name="node")
"""The item at the end of the edge."""
| LinkedBranchEdge |
python | walkccc__LeetCode | solutions/1304. Find N Unique Integers Sum up to Zero/1304.py | {
"start": 0,
"end": 94
} | class ____:
def sumZero(self, n: int) -> list[int]:
return list(range(1 - n, n, 2))
| Solution |
python | pydata__xarray | xarray/backends/scipy_.py | {
"start": 5736,
"end": 10788
} | class ____(WritableCFDataStore):
"""Store for reading and writing data via scipy.io.netcdf_file.
This store has the advantage of being able to be initialized with a
StringIO object, allow for serialization without writing to disk.
It only supports the NetCDF3 file-format.
"""
def __init__(
self, filename_or_obj, mode="r", format=None, group=None, mmap=None, lock=None
):
if group is not None:
raise ValueError("cannot save to a group with the scipy.io.netcdf backend")
if format is None or format == "NETCDF3_64BIT":
version = 2
elif format == "NETCDF3_CLASSIC":
version = 1
else:
raise ValueError(f"invalid format for scipy.io.netcdf backend: {format!r}")
if lock is None and mode != "r" and isinstance(filename_or_obj, str):
lock = get_write_lock(filename_or_obj)
self.lock = ensure_lock(lock)
if isinstance(filename_or_obj, BytesIOProxy):
source = filename_or_obj
filename_or_obj = io.BytesIO()
source.getvalue = filename_or_obj.getbuffer
if isinstance(filename_or_obj, str): # path
manager = CachingFileManager(
_open_scipy_netcdf,
filename_or_obj,
mode=mode,
lock=lock,
kwargs=dict(mmap=mmap, version=version),
)
elif hasattr(filename_or_obj, "seek"): # file object
# Note: checking for .seek matches the check for file objects
# in scipy.io.netcdf_file
scipy_dataset = _open_scipy_netcdf(
filename_or_obj,
mode=mode,
mmap=mmap,
version=version,
flush_only=True,
)
assert not scipy_dataset.use_mmap # no mmap for file objects
manager = DummyFileManager(scipy_dataset)
else:
raise ValueError(
f"cannot open {filename_or_obj=} with scipy.io.netcdf_file"
)
self._manager = manager
@property
def ds(self) -> scipy.io.netcdf_file:
return self._manager.acquire()
def open_store_variable(self, name, var):
return Variable(
var.dimensions,
indexing.LazilyIndexedArray(ScipyArrayWrapper(name, self)),
_decode_attrs(var._attributes),
)
def get_variables(self):
return FrozenDict(
(k, self.open_store_variable(k, v)) for k, v in self.ds.variables.items()
)
def get_attrs(self):
return Frozen(_decode_attrs(self.ds._attributes))
def get_dimensions(self):
return Frozen(self.ds.dimensions)
def get_encoding(self):
return {
"unlimited_dims": {k for k, v in self.ds.dimensions.items() if v is None}
}
def set_dimension(self, name, length, is_unlimited=False):
if name in self.ds.dimensions:
raise ValueError(
f"{type(self).__name__} does not support modifying dimensions"
)
dim_length = length if not is_unlimited else None
self.ds.createDimension(name, dim_length)
def _validate_attr_key(self, key):
if not is_valid_nc3_name(key):
raise ValueError("Not a valid attribute name")
def set_attribute(self, key, value):
self._validate_attr_key(key)
value = encode_nc3_attr_value(value)
setattr(self.ds, key, value)
def encode_variable(self, variable, name=None):
variable = encode_nc3_variable(variable, name=name)
return variable
def prepare_variable(
self, name, variable, check_encoding=False, unlimited_dims=None
):
if (
check_encoding
and variable.encoding
and variable.encoding != {"_FillValue": None}
):
raise ValueError(
f"unexpected encoding for scipy backend: {list(variable.encoding)}"
)
data = variable.data
# nb. this still creates a numpy array in all memory, even though we
# don't write the data yet; scipy.io.netcdf does not support incremental
# writes.
if name not in self.ds.variables:
self.ds.createVariable(name, data.dtype, variable.dims)
scipy_var = self.ds.variables[name]
for k, v in variable.attrs.items():
self._validate_attr_key(k)
setattr(scipy_var, k, v)
target = ScipyArrayWrapper(name, self)
return target, data
def sync(self):
self.ds.sync()
def close(self):
self._manager.close()
def _normalize_filename_or_obj(
filename_or_obj: str
| os.PathLike[Any]
| ReadBuffer
| bytes
| memoryview
| AbstractDataStore,
) -> str | ReadBuffer | AbstractDataStore:
if isinstance(filename_or_obj, bytes | memoryview):
return io.BytesIO(filename_or_obj)
else:
return _normalize_path(filename_or_obj)
| ScipyDataStore |
python | sqlalchemy__sqlalchemy | test/sql/test_types.py | {
"start": 17308,
"end": 20942
} | class ____(fixtures.TestBase):
@testing.combinations(
("Boo", Boolean()),
("Str", String()),
("Tex", Text()),
("Uni", Unicode()),
("Int", Integer()),
("Sma", SmallInteger()),
("Big", BigInteger()),
("Num", Numeric()),
("Flo", Float()),
("Enu", Enum("one", "two", "three")),
("Dat", DateTime()),
("Dat", Date()),
("Tim", Time()),
("Lar", LargeBinary()),
("Pic", PickleType()),
("Int", Interval()),
("Dec", SomeTypeDecorator()),
argnames="name,type_",
id_="ar",
)
@testing.variation("use_adapt", [True, False])
def test_pickle_types(self, name, type_, use_adapt):
if use_adapt:
type_ = type_.copy()
column_type = Column(name, type_)
meta = MetaData()
Table("foo", meta, column_type)
expr = select(1).where(column_type == bindparam("q"))
for loads, dumps in picklers():
loads(dumps(column_type))
loads(dumps(meta))
expr_str_one = str(expr)
ne = loads(dumps(expr))
eq_(str(ne), expr_str_one)
re_pickle_it = loads(dumps(ne))
eq_(str(re_pickle_it), expr_str_one)
def test_pickle_td_comparator(self):
comparator = SomeTypeDecorator().comparator_factory(column("q"))
expected_mro = (
TypeDecorator.Comparator,
sqltypes.Concatenable.Comparator,
TypeEngine.Comparator,
)
eq_(comparator.__class__.__mro__[1:4], expected_mro)
for loads, dumps in picklers():
unpickled = loads(dumps(comparator))
eq_(unpickled.__class__.__mro__[1:4], expected_mro)
reunpickled = loads(dumps(unpickled))
eq_(reunpickled.__class__.__mro__[1:4], expected_mro)
@testing.combinations(
("Str", String()),
("Tex", Text()),
("Uni", Unicode()),
("Boo", Boolean()),
("Dat", DateTime()),
("Dat", Date()),
("Tim", Time()),
("Lar", LargeBinary()),
("Pic", PickleType()),
("Int", Interval()),
("Enu", Enum("one", "two", "three")),
argnames="name,type_",
id_="ar",
)
@testing.variation("use_adapt", [True, False])
def test_pickle_types_other_process(self, name, type_, use_adapt):
"""test for #11530
this does a full exec of python interpreter so the number of variations
here is reduced to just a single pickler, else each case takes
a full second.
"""
if use_adapt:
type_ = type_.copy()
column_type = Column(name, type_)
meta = MetaData()
Table("foo", meta, column_type)
for target in column_type, meta:
f, name = mkstemp("pkl")
with os.fdopen(f, "wb") as f:
pickle.dump(target, f)
name = name.replace(os.sep, "/")
code = (
"import sqlalchemy; import pickle; "
f"pickle.load(open('''{name}''', 'rb'))"
)
parts = list(sys.path)
if os.environ.get("PYTHONPATH"):
parts.append(os.environ["PYTHONPATH"])
pythonpath = os.pathsep.join(parts)
proc = subprocess.run(
[sys.executable, "-c", code],
env={**os.environ, "PYTHONPATH": pythonpath},
stderr=subprocess.PIPE,
)
eq_(proc.returncode, 0, proc.stderr.decode(errors="replace"))
os.unlink(name)
| PickleTypesTest |
python | python-excel__xlrd | xlrd/book.py | {
"start": 4216,
"end": 9265
} | class ____(BaseObject):
"""
Information relating to a named reference, formula, macro, etc.
.. note::
Name information is **not** extracted from files older than
Excel 5.0 (``Book.biff_version < 50``)
"""
_repr_these = ['stack']
book = None # parent
#: 0 = Visible; 1 = Hidden
hidden = 0
#: 0 = Command macro; 1 = Function macro. Relevant only if macro == 1
func = 0
#: 0 = Sheet macro; 1 = VisualBasic macro. Relevant only if macro == 1
vbasic = 0
#: 0 = Standard name; 1 = Macro name
macro = 0
#: 0 = Simple formula; 1 = Complex formula (array formula or user defined).
#:
#: .. note:: No examples have been sighted.
complex = 0
#: 0 = User-defined name; 1 = Built-in name
#:
#: Common examples: ``Print_Area``, ``Print_Titles``; see OOo docs for
#: full list
builtin = 0
#: Function group. Relevant only if macro == 1; see OOo docs for values.
funcgroup = 0
#: 0 = Formula definition; 1 = Binary data
#:
#: .. note:: No examples have been sighted.
binary = 0
#: The index of this object in book.name_obj_list
name_index = 0
# A Unicode string. If builtin, decoded as per OOo docs.
name = UNICODE_LITERAL("")
#: An 8-bit string.
raw_formula = b''
#: ``-1``:
#: The name is global (visible in all calculation sheets).
#: ``-2``:
#: The name belongs to a macro sheet or VBA sheet.
#: ``-3``:
#: The name is invalid.
#: ``0 <= scope < book.nsheets``:
#: The name is local to the sheet whose index is scope.
scope = -1
#: The result of evaluating the formula, if any.
#: If no formula, or evaluation of the formula encountered problems,
#: the result is ``None``. Otherwise the result is a single instance of the
#: :class:`~xlrd.formula.Operand` class.
#
result = None
def cell(self):
"""
This is a convenience method for the frequent use case where the name
refers to a single cell.
:returns: An instance of the :class:`~xlrd.sheet.Cell` class.
:raises xlrd.biffh.XLRDError:
The name is not a constant absolute reference
to a single cell.
"""
res = self.result
if res:
# result should be an instance of the Operand class
kind = res.kind
value = res.value
if kind == oREF and len(value) == 1:
ref3d = value[0]
if (0 <= ref3d.shtxlo == ref3d.shtxhi - 1 and
ref3d.rowxlo == ref3d.rowxhi - 1 and
ref3d.colxlo == ref3d.colxhi - 1):
sh = self.book.sheet_by_index(ref3d.shtxlo)
return sh.cell(ref3d.rowxlo, ref3d.colxlo)
self.dump(
self.book.logfile,
header="=== Dump of Name object ===",
footer="======= End of dump =======",
)
raise XLRDError("Not a constant absolute reference to a single cell")
def area2d(self, clipped=True):
"""
This is a convenience method for the use case where the name
refers to one rectangular area in one worksheet.
:param clipped:
If ``True``, the default, the returned rectangle is clipped
to fit in ``(0, sheet.nrows, 0, sheet.ncols)``.
it is guaranteed that ``0 <= rowxlo <= rowxhi <= sheet.nrows`` and
that the number of usable rows in the area (which may be zero) is
``rowxhi - rowxlo``; likewise for columns.
:returns: a tuple ``(sheet_object, rowxlo, rowxhi, colxlo, colxhi)``.
:raises xlrd.biffh.XLRDError:
The name is not a constant absolute reference
to a single area in a single sheet.
"""
res = self.result
if res:
# result should be an instance of the Operand class
kind = res.kind
value = res.value
if kind == oREF and len(value) == 1: # only 1 reference
ref3d = value[0]
if 0 <= ref3d.shtxlo == ref3d.shtxhi - 1: # only 1 usable sheet
sh = self.book.sheet_by_index(ref3d.shtxlo)
if not clipped:
return sh, ref3d.rowxlo, ref3d.rowxhi, ref3d.colxlo, ref3d.colxhi
rowxlo = min(ref3d.rowxlo, sh.nrows)
rowxhi = max(rowxlo, min(ref3d.rowxhi, sh.nrows))
colxlo = min(ref3d.colxlo, sh.ncols)
colxhi = max(colxlo, min(ref3d.colxhi, sh.ncols))
assert 0 <= rowxlo <= rowxhi <= sh.nrows
assert 0 <= colxlo <= colxhi <= sh.ncols
return sh, rowxlo, rowxhi, colxlo, colxhi
self.dump(
self.book.logfile,
header="=== Dump of Name object ===",
footer="======= End of dump =======",
)
raise XLRDError("Not a constant absolute reference to a single area in a single sheet")
| Name |
python | tensorflow__tensorflow | tensorflow/python/data/ops/interleave_op.py | {
"start": 3715,
"end": 6409
} | class ____(dataset_ops.UnaryDataset):
"""A `Dataset` that maps a function over its input and interleaves the result.
"""
def __init__(self,
input_dataset,
map_func,
cycle_length,
block_length,
num_parallel_calls,
buffer_output_elements=dataset_ops.AUTOTUNE,
prefetch_input_elements=dataset_ops.AUTOTUNE,
deterministic=None,
name=None):
"""See `Dataset.interleave()` for details."""
self._input_dataset = input_dataset
self._map_func = structured_function.StructuredFunctionWrapper(
map_func, self._transformation_name(), dataset=input_dataset)
if not isinstance(self._map_func.output_structure, dataset_ops.DatasetSpec):
raise TypeError(
"The `map_func` argument must return a `Dataset` object. Got "
f"{dataset_ops.get_type(self._map_func.output_structure)!r}.")
self._structure = self._map_func.output_structure._element_spec # pylint: disable=protected-access
self._cycle_length = ops.convert_to_tensor(
cycle_length, dtype=dtypes.int64, name="cycle_length")
self._block_length = ops.convert_to_tensor(
block_length, dtype=dtypes.int64, name="block_length")
self._buffer_output_elements = ops.convert_to_tensor(
buffer_output_elements,
dtype=dtypes.int64,
name="buffer_output_elements")
self._prefetch_input_elements = ops.convert_to_tensor(
prefetch_input_elements,
dtype=dtypes.int64,
name="prefetch_input_elements")
self._num_parallel_calls = ops.convert_to_tensor(
num_parallel_calls, dtype=dtypes.int64, name="num_parallel_calls")
if deterministic is None:
deterministic_string = "default"
elif deterministic:
deterministic_string = "true"
else:
deterministic_string = "false"
self._name = name
variant_tensor = gen_dataset_ops.parallel_interleave_dataset_v4(
input_dataset._variant_tensor, # pylint: disable=protected-access
self._map_func.function.captured_inputs, # pylint: disable=protected-access
self._cycle_length,
self._block_length,
self._buffer_output_elements,
self._prefetch_input_elements,
self._num_parallel_calls,
f=self._map_func.function,
deterministic=deterministic_string,
**self._common_args)
super().__init__(input_dataset, variant_tensor)
def _functions(self):
return [self._map_func]
@property
def element_spec(self):
return self._structure
def _transformation_name(self):
return "Dataset.interleave()"
| _ParallelInterleaveDataset |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/types.py | {
"start": 9798,
"end": 10513
} | class ____:
"""Annotation used to mark state attributes as omitted from input or output schemas."""
input: bool = True
"""Whether to omit the attribute from the input schema."""
output: bool = True
"""Whether to omit the attribute from the output schema."""
OmitFromInput = OmitFromSchema(input=True, output=False)
"""Annotation used to mark state attributes as omitted from input schema."""
OmitFromOutput = OmitFromSchema(input=False, output=True)
"""Annotation used to mark state attributes as omitted from output schema."""
PrivateStateAttr = OmitFromSchema(input=True, output=True)
"""Annotation used to mark state attributes as purely internal for a given middleware."""
| OmitFromSchema |
python | numpy__numpy | numpy/random/tests/test_generator_mt19937.py | {
"start": 2793,
"end": 4209
} | class ____:
def test_n_zero(self):
# Tests the corner case of n == 0 for the binomial distribution.
# binomial(0, p) should be zero for any p in [0, 1].
# This test addresses issue #3480.
zeros = np.zeros(2, dtype='int')
for p in [0, .5, 1]:
assert_(random.binomial(0, p) == 0)
assert_array_equal(random.binomial(zeros, p), zeros)
def test_p_is_nan(self):
# Issue #4571.
assert_raises(ValueError, random.binomial, 1, np.nan)
def test_p_extremely_small(self):
n = 50000000000
p = 5e-17
sample_size = 20000000
x = random.binomial(n, p, size=sample_size)
sample_mean = x.mean()
expected_mean = n * p
sigma = np.sqrt(n * p * (1 - p) / sample_size)
# Note: the parameters were chosen so that expected_mean - 6*sigma
# is a positive value. The first `assert` below validates that
# assumption (in case someone edits the parameters in the future).
# The second `assert` is the actual test.
low_bound = expected_mean - 6 * sigma
assert low_bound > 0, "bad test params: 6-sigma lower bound is negative"
test_msg = (f"sample mean {sample_mean} deviates from the expected mean "
f"{expected_mean} by more than 6*sigma")
assert abs(expected_mean - sample_mean) < 6 * sigma, test_msg
| TestBinomial |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-graphdb-cypher/llama_index/readers/graphdb_cypher/base.py | {
"start": 190,
"end": 1766
} | class ____(BaseReader):
"""
Graph database Cypher reader.
Combines all Cypher query results into the Document type used by LlamaIndex.
Args:
uri (str): Graph Database URI
username (str): Username
password (str): Password
"""
def __init__(self, uri: str, username: str, password: str, database: str) -> None:
"""Initialize with parameters."""
try:
from neo4j import GraphDatabase, basic_auth
except ImportError:
raise ImportError(
"`neo4j` package not found, please run `pip install neo4j`"
)
if uri:
if uri is None:
raise ValueError("`uri` must be provided.")
self.client = GraphDatabase.driver(
uri=uri, auth=basic_auth(username, password)
)
self.database = database
def load_data(
self, query: str, parameters: Optional[Dict] = None
) -> List[Document]:
"""
Run the Cypher with optional parameters and turn results into documents.
Args:
query (str): Graph Cypher query string.
parameters (Optional[Dict]): optional query parameters.
Returns:
List[Document]: A list of documents.
"""
if parameters is None:
parameters = {}
records, summary, keys = self.client.execute_query(
query, parameters, database_=self.database
)
return [Document(text=yaml.dump(entry.data())) for entry in records]
| GraphDBCypherReader |
python | facebook__pyre-check | tools/generate_taint_models/view_generator.py | {
"start": 481,
"end": 2163
} | class ____(NamedTuple):
urls_module: str
url_resolver_type: DynamicURLType
url_pattern_type: DynamicURLType
def get_all_views(django_urls: DjangoUrls) -> List[Callable[..., object]]:
LOG.info(f"Getting all URLs from `{django_urls.urls_module}`")
imported_urls_module = import_module(django_urls.urls_module)
functions_to_model = []
# pyre-ignore: Too dynamic.
def visit_all_patterns(url_patterns: Iterable[Any]) -> None:
for pattern in url_patterns:
if isinstance(pattern, django_urls.url_resolver_type):
# TODO(T47152686): Fix the pyre bug that causes us to miss the
# nested function.
visit_all_patterns(pattern.url_patterns)
elif isinstance(pattern, django_urls.url_pattern_type):
callback = pattern.callback
if inspect.ismethod(callback) or inspect.isfunction(callback):
functions_to_model.append(callback)
elif hasattr(callback, "__call__"): # noqa: B004
# Rare case: We have a functor, rather than a function. In
# this case, we want to return the user-defined '__call__'
# method itself, so that 'taint_callable_functions' can
# properly model it
functions_to_model.append(callback.__call__)
else:
raise TypeError("callback is not a function, method, or functor")
else:
raise TypeError("pattern is not url resolver or url pattern.")
visit_all_patterns(imported_urls_module.urlpatterns)
return functions_to_model
| DjangoUrls |
python | huggingface__transformers | tests/models/janus/test_image_processing_janus.py | {
"start": 1133,
"end": 2980
} | class ____:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=384,
min_resolution=30,
max_resolution=200,
do_resize=True,
size=None,
do_normalize=True,
image_mean=[0.48145466, 0.4578275, 0.40821073],
image_std=[0.26862954, 0.26130258, 0.27577711],
do_convert_rgb=True,
):
size = size if size is not None else {"height": 384, "width": 384}
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.do_resize = do_resize
self.size = size
self.do_normalize = do_normalize
self.image_mean = image_mean
self.image_std = image_std
self.do_convert_rgb = do_convert_rgb
def prepare_image_processor_dict(self):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_convert_rgb": self.do_convert_rgb,
}
# Copied from tests.models.clip.test_image_processing_clip.CLIPImageProcessingTester.prepare_image_inputs
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
return prepare_image_inputs(
batch_size=self.batch_size,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
numpify=numpify,
torchify=torchify,
)
@require_torch
@require_vision
| JanusImageProcessingTester |
python | joke2k__faker | faker/providers/job/ru_RU/__init__.py | {
"start": 212,
"end": 12507
} | class ____(BaseProvider):
jobs = [
"Авиадиспетчер",
"Авиатехник",
"Авиационный техник",
"Автогонщик",
"Автослесарь",
"Автоэлектрик",
"Агроном",
"Агроном по защите растений",
"Агроном-почвовед",
"Адвокат",
"Администратор базы данных",
"Аккумуляторщик",
"Актуарий",
"Актёр",
"Акушер",
"Аллерголог",
"Аналитик",
"Андролог",
"Антрополог",
"Артиллерист",
"Артист цирка",
"Археолог",
"Архивариус",
"Архитектор",
"Астроном",
"Астрофизик",
"Астрохимик",
"Бактериолог",
"Балерина",
"Балетмейстер",
"Банкир",
"Бармен",
"Баталер",
"Безработный",
"Библиотекарь",
"Библиотековед",
"Биоинженер",
"Биолог",
"Биофизик",
"Биохимик",
"Блоггер",
"Бондарь",
"Борт-инженер",
"Борт-механик",
"Борт-радист",
"Борт-стрелок",
"Бортинженер",
"Бортмеханик",
"Бортпроводник/стюард",
"Ботаник",
"Брейдер",
"Брокер",
"Булочник",
"Бульдозерист",
"Бухгалтер",
"Веб-интегратор",
"Веб-мастер",
"Веб-программист",
"Верстальщик",
"Ветеринар",
"Визажист",
"Виноградарь",
"Вирусолог",
"Водитель",
"Водолаз",
"Военно-полевой хирург",
"Военно-полевой хирург",
"Военнослужащий",
"Военный дознаватель",
"Военный консультант",
"Военный переводчик",
"Военный полицейский",
"Военный прокурор",
"Военный судья",
"Военный юрист",
"Воздухоплаватель",
"Вокалист",
"Воспитатель",
"Воспитатель",
"Востоковед",
"Врач МСЭК",
"Врач УЗ-диагностики",
"Врач скорой помощи",
"Врач функциональной диагностики",
"Выпускающий редактор",
"Гастроэнтеролог",
"Гематолог",
"Генетик",
"Генетик",
"Географ",
"Геодезист",
"Геолог",
"Гепатолог",
"Гидролог",
"Гинеколог",
"Гирудотерапевт",
"Гитарист",
"Гляциолог",
"Гомеопат",
"Горничная",
"Горнострелок",
"Горняк",
"Государственный исполнитель",
"Гранатомётчик",
"Грейдерист",
"Гренадер",
"Гример",
"Грузчик",
"Дворник",
"Декан",
"Декоратор",
"Дерматолог",
"Десантник",
"Детектив",
"Дефектолог",
"Диверсант",
"Диджей",
"Диетолог",
"Дизайнер",
"Дизайнер рекламы",
"Дизайнер-конструктор",
"Диктор",
"Дилер",
"Дипломат",
"Дипломат",
"Дипломатический работник",
"Дирижёр",
"Диспетчер",
"Дознаватель",
"Донкерман",
"Доула",
"Доярка",
"Драпировщик",
"Египтолог",
"Животновод",
"Жиловщик/Обвальщик",
"Журналист",
"Заряжающий",
"Заточник",
"Звукорежиссёр",
"Зенитчик",
"Златокузнец",
"Зоолог",
"Зоотехник",
"Издатель",
"Изобретатр",
"Иконописец",
"Иллюстратор",
"Имиджмейкер",
"Иммунолог",
"Инженер",
"Инженер",
"Инженер КИПиА",
"Инженер по Технике Безопасности",
"Инженер по механизации",
"Инженер-акустик",
"Инженер-взрывотехник",
"Инженер-гальваник",
"Инженер-гидравлик",
"Инженер-конструктор",
"Инженер-лаборант",
"Инженер-лесотехник",
"Инженер-механик",
"Инженер-системотехник",
"Инженер-строитель",
"Инженер-технолог",
"Инженер-физик",
"Инженер-химик",
"Инженер-электрик",
"Инженер-энергетик",
"Инкассатор",
"Интендант",
"Инфекционист",
"Искусствовед",
"Историк",
"Ихтиолог",
"Кабельщик",
"Кавалерист",
"Каменотёс",
"Канонир",
"Капитан судна",
"Каптенармус",
"Кардиолог",
"Кардиохирург",
"Каскадёр",
"Кассир",
"Квасник",
"Кинодраматург",
"Кинолог",
"Кинолог",
"Киномеханик",
"Кинооператор",
"Кинорежиссер",
"Кладовщик",
"Клинер",
"Кнопочник",
"Кодер",
"Кок",
"Командир",
"Комбайнер",
"Комендант",
"Коммерческий директор",
"Композитор",
"Конвоир",
"Кондитер",
"Кондитер",
"Кондуктор",
"Коневод",
"Контент-менеджер",
"Копирайтер",
"Корректировщик",
"Корректор",
"Косметолог",
"Космонавт",
"Крановщик",
"Кредитный консультант",
"Криптозоолог",
"Критик",
"Кровельщик",
"Кромкозакатчик",
"Крупье",
"Кузнец",
"Культуролог",
"Лаборант",
"Лекальщик",
"Лимфолог",
"Лингвист",
"Литейщик",
"Лифтёр",
"Логик",
"Логопед",
"Логопед",
"Лоцман",
"Лётчик",
"Лётчик",
"Маклер биржевой",
"Маляр",
"Маммолог",
"Манекенщица",
"Мануалист",
"Маркетолог",
"Маркитант",
"Маркшейдер",
"Массажист",
"Мастер маникюра",
"Мастер маникюра",
"Мастер педикюра",
"Математик",
"Машинист",
"Машинист локомотива",
"Машинистка",
"Медицинская сестра",
"Медник",
"Мелиоратор",
"Мельник",
"Менеджер",
"Менеджер по работе с клиентами",
"Мерчандайзер",
"Месильщик",
"Металлург",
"Метеоролог",
"Метранпаж",
"Метрдотель",
"Механизатор",
"Механик",
"Механик-Водитель",
"Миколог",
"Микробиолог",
"Министр",
"Модель",
"Модельер",
"Монтажник",
"Монтажник радиоэлектронной аппаратуры и приборов",
"Монтажник связи",
"Морской пехотинец",
"Моторист",
"Моторист",
"Мотострелок",
"Музыкант",
"Мусоропроводчик",
"Мусорщик",
"Мясник",
"Наводчик орудия",
"Налоговый инспектор",
"Нарколог",
"Начальник военного оркестра",
"Начальник гаупвахты",
"Начальник склада",
"Начальник службы",
"Начальник штаба",
"Невролог",
"Невропатолог",
"Нейрохирург",
"Неонатолог",
"Нефролог",
"Нотариус",
"Няня",
"Огнемётчик",
"Океанолог",
"Онколог",
"Оперативный работник",
"Оператор ПК",
"Оператор РЛС",
"Оператор вооружения",
"Оператор кино и телевидения",
"Оператор коллцентра",
"Оператор машинного доения",
"Операционист",
"Организатор свадеб",
"Орнитолог",
"Ортодонт",
"Ортопед",
"Особист",
"Оториноларинголог",
"Официант",
"Офтальмолог",
"Палеонтолог",
"Парикмахер",
"Парикмахер",
"Парфюмер",
"Пастух",
"Патологоанатом",
"Педагог",
"Педиатр",
"Пекарь",
"Переводчик",
"Переводчик",
"Переплётчик",
"Печатник",
"Писатель",
"Пластический хирург",
"Плиточник",
"Плотник",
"Повар",
"Повар",
"Пограничник",
"Подводник",
"Пожарный",
"Политолог",
"Полицейский",
"Портной",
"Портье",
"Постановщик трюков",
"Почтальон",
"Поэт",
"Правовед",
"Предприниматель",
"Преподаватель",
"Проводник",
"Программист",
"Программист",
"Продавец",
"Продавец",
"Продюсер",
"Прозектор",
"Проктолог",
"Прокурор",
"Промышленный альпинист",
"Промышленный альпинист",
"Проректор",
"Профпатолог",
"Проходчик",
"Психиатр",
"Психолог",
"Психоневропатолог",
"Психотерапевт",
"Пулемётчик",
"Пульмонолог",
"Пчеловод",
"Работник органов ЗАГСа",
"Радиолог",
"Радиомеханик",
"Радиотелефонист",
"Радист",
"Радист",
"Разведчик",
"Ракетчик",
"Распиловщик",
"Растениевод",
"Расточник",
"Реаниматолог",
"Ревматолог",
"Редактор",
"Режиссёр",
"Ректор",
"Релайтер",
"Религиовед",
"Рентгенолог",
"Реставратор",
"Рефлексотерапевт",
"Рихтовщик",
"Робототехник",
"Садовник",
"Садовод",
"Санитар",
"Сантехник",
"Сапожник",
"Сапёр",
"Сборщик",
"Сварщик",
"Связист",
"Священнослужитель",
"Секретчик",
"Сексолог",
"Сексопатолог",
"Семейный врач",
"Серпентолог",
"Сиделка",
"Системный администратор",
"Скорняк",
"Скотник",
"Скульптор",
"Следователь",
"Слесарь",
"Слесарь-механик",
"Сметчик",
"Снабженец",
"Снайпер",
"Сомелье",
"Сомнолог",
"Социолог",
"Специалист по клеточным технологиям",
"Специалист по стрижке овец",
"Спортивный врач",
"Сталевар",
"Старшина",
"Стилист",
"Столяр",
"Столяр-краснодеревщик",
"Стоматолог",
"Страховой агент",
"Стрелок",
"Стрелочник",
"Строитель",
"Судебный пристав",
"Судья",
"Сурдолог",
"Сурдопедагог",
"Сценарист",
"Сыровар",
"Табаковод",
"Табунщик",
"Таксист",
"Тальман",
"Таможенник",
"Танатолог",
"Танкист",
"Танцор",
"Татуировщик",
"Телеграфист",
"Тележурналист",
"Телемастер",
"Телефонист",
"Телохранитель",
"Теолог",
"Терапевт",
"Териолог",
"Тестировщик",
"Техник",
"Техник",
"Технолог",
"Типограф",
"Тифлопедагог",
"Товаровед",
"Токарь",
"Токарь-карусельщик",
"Токсиколог",
"Топограф",
"Торакальный хирург",
"Торговый представитель",
"Травматолог",
"Тракторист",
"Трансфузиолог",
"Трейдер",
"Тренд-вотчер",
"Тыловик",
"Тюремный надзиратель",
"Уборщик",
"Упаковщик",
"Уролог",
"Учитель",
"Учёный",
"Фальцовщик",
"Фармацевт",
"Фельдшер",
"Фельдшер",
"Фермер",
"Физик",
"Физиотерапевт",
"Филолог",
"Философ",
"Финансист",
"Финансист",
"Флеболог",
"Флорист",
"Флорист",
"Формовщик",
"Фортификатор",
"Фотограф",
"Фотомодель",
"Фрезеровщик",
"Фтизиатр",
"Фуражир",
"Футуролог",
"Химик",
"Химик",
"Химик-аналитик",
"Химик-контролер",
"Химик-технолог",
"Хирург",
"Хлебопёк",
"Хлебороб",
"Хлопокороб",
"Холодильщик",
"Хореограф",
"Художник",
"Художник по свету",
"Шахтёр",
"Швейцар",
"Швея",
"Шифровальщик",
"Шкипер",
"Шлифовщик",
"Шорник",
"Штукатур",
"Штурман",
"Эколог",
"Экономист",
"Экспедитор",
"Экспедитор на дальних поездках",
"Эксперт-криминалист",
"Электрик",
"Эндокринолог",
"Эндоскопист",
"Энтомолог",
"Эпидемиолог",
"Эфферентолог",
"Ювелир",
"Юрисконсульт",
"Юрист",
]
| Provider |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_setitem.py | {
"start": 690,
"end": 29644
} | class ____:
def test_setitem_str_subclass(self):
# GH#37366
class mystring(str):
__slots__ = ()
data = ["2020-10-22 01:21:00+00:00"]
index = DatetimeIndex(data)
df = DataFrame({"a": [1]}, index=index)
df["b"] = 2
df[mystring("c")] = 3
expected = DataFrame({"a": [1], "b": [2], mystring("c"): [3]}, index=index)
tm.assert_equal(df, expected)
@pytest.mark.parametrize(
"dtype", ["int32", "int64", "uint32", "uint64", "float32", "float64"]
)
def test_setitem_dtype(self, dtype, float_frame):
# Use integers since casting negative floats to uints is undefined
arr = np.random.default_rng(2).integers(1, 10, len(float_frame))
float_frame[dtype] = np.array(arr, dtype=dtype)
assert float_frame[dtype].dtype.name == dtype
def test_setitem_list_not_dataframe(self, float_frame):
data = np.random.default_rng(2).standard_normal((len(float_frame), 2))
float_frame[["A", "B"]] = data
tm.assert_almost_equal(float_frame[["A", "B"]].values, data)
def test_setitem_error_msmgs(self):
# GH 7432
df = DataFrame(
{"bar": [1, 2, 3], "baz": ["d", "e", "f"]},
index=Index(["a", "b", "c"], name="foo"),
)
ser = Series(
["g", "h", "i", "j"],
index=Index(["a", "b", "c", "a"], name="foo"),
name="fiz",
)
msg = "cannot reindex on an axis with duplicate labels"
with pytest.raises(ValueError, match=msg):
df["newcol"] = ser
# GH 4107, more descriptive error message
df = DataFrame(
np.random.default_rng(2).integers(0, 2, (4, 4)),
columns=["a", "b", "c", "d"],
)
msg = "Cannot set a DataFrame with multiple columns to the single column gr"
with pytest.raises(ValueError, match=msg):
df["gr"] = df.groupby(["b", "c"]).count()
# GH 55956, specific message for zero columns
msg = "Cannot set a DataFrame without columns to the column gr"
with pytest.raises(ValueError, match=msg):
df["gr"] = DataFrame()
def test_setitem_benchmark(self):
# from the vb_suite/frame_methods/frame_insert_columns
N = 10
K = 5
df = DataFrame(index=range(N))
new_col = np.random.default_rng(2).standard_normal(N)
for i in range(K):
df[i] = new_col
expected = DataFrame(np.repeat(new_col, K).reshape(N, K), index=range(N))
tm.assert_frame_equal(df, expected)
def test_setitem_different_dtype(self):
df = DataFrame(
np.random.default_rng(2).standard_normal((5, 3)),
index=np.arange(5),
columns=["c", "b", "a"],
)
df.insert(0, "foo", df["a"])
df.insert(2, "bar", df["c"])
# diff dtype
# new item
df["x"] = df["a"].astype("float32")
result = df.dtypes
expected = Series(
[np.dtype("float64")] * 5 + [np.dtype("float32")],
index=["foo", "c", "bar", "b", "a", "x"],
)
tm.assert_series_equal(result, expected)
# replacing current (in different block)
df["a"] = df["a"].astype("float32")
result = df.dtypes
expected = Series(
[np.dtype("float64")] * 4 + [np.dtype("float32")] * 2,
index=["foo", "c", "bar", "b", "a", "x"],
)
tm.assert_series_equal(result, expected)
df["y"] = df["a"].astype("int32")
result = df.dtypes
expected = Series(
[np.dtype("float64")] * 4 + [np.dtype("float32")] * 2 + [np.dtype("int32")],
index=["foo", "c", "bar", "b", "a", "x", "y"],
)
tm.assert_series_equal(result, expected)
def test_setitem_overwrite_index(self):
# GH 13522 - assign the index as a column and then overwrite the values
# -> should not affect the index
df = DataFrame(index=["A", "B", "C"])
df["X"] = df.index
df["X"] = ["x", "y", "z"]
exp = DataFrame(
data={"X": ["x", "y", "z"]}, index=["A", "B", "C"], columns=["X"]
)
tm.assert_frame_equal(df, exp)
def test_setitem_empty_columns(self):
# Starting from an empty DataFrame and setting a column should result
# in a default string dtype for the columns' Index
# https://github.com/pandas-dev/pandas/issues/60338
df = DataFrame()
df["foo"] = [1, 2, 3]
expected = DataFrame({"foo": [1, 2, 3]})
tm.assert_frame_equal(df, expected)
df = DataFrame(columns=Index([]))
df["foo"] = [1, 2, 3]
expected = DataFrame({"foo": [1, 2, 3]})
tm.assert_frame_equal(df, expected)
def test_setitem_dt64_index_empty_columns(self):
rng = date_range("1/1/2000 00:00:00", "1/1/2000 1:59:50", freq="10s", unit="ns")
df = DataFrame(index=np.arange(len(rng)))
df["A"] = rng
assert df["A"].dtype == np.dtype("M8[ns]")
def test_setitem_timestamp_empty_columns(self):
# GH#19843
df = DataFrame(index=range(3))
df["now"] = Timestamp("20130101", tz="UTC")
expected = DataFrame(
[[Timestamp("20130101", tz="UTC")]] * 3, index=range(3), columns=["now"]
)
tm.assert_frame_equal(df, expected)
def test_setitem_wrong_length_categorical_dtype_raises(self):
# GH#29523
cat = Categorical.from_codes([0, 1, 1, 0, 1, 2], ["a", "b", "c"])
df = DataFrame(range(10), columns=["bar"])
msg = (
rf"Length of values \({len(cat)}\) "
rf"does not match length of index \({len(df)}\)"
)
with pytest.raises(ValueError, match=msg):
df["foo"] = cat
def test_setitem_with_sparse_value(self):
# GH#8131
df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]})
sp_array = SparseArray([0, 0, 1])
df["new_column"] = sp_array
expected = Series(sp_array, name="new_column")
tm.assert_series_equal(df["new_column"], expected)
def test_setitem_with_unaligned_sparse_value(self):
df = DataFrame({"c_1": ["a", "b", "c"], "n_1": [1.0, 2.0, 3.0]})
sp_series = Series(SparseArray([0, 0, 1]), index=[2, 1, 0])
df["new_column"] = sp_series
expected = Series(SparseArray([1, 0, 0]), name="new_column")
tm.assert_series_equal(df["new_column"], expected)
def test_setitem_period_preserves_dtype(self):
# GH: 26861
data = [Period("2003-12", "D")]
result = DataFrame([])
result["a"] = data
expected = DataFrame({"a": data}, columns=["a"])
tm.assert_frame_equal(result, expected)
def test_setitem_dict_preserves_dtypes(self):
# https://github.com/pandas-dev/pandas/issues/34573
expected = DataFrame(
{
"a": Series([0, 1, 2], dtype="int64"),
"b": Series([1, 2, 3], dtype=float),
"c": Series([1, 2, 3], dtype=float),
"d": Series([1, 2, 3], dtype="uint32"),
}
)
df = DataFrame(
{
"a": Series([], dtype="int64"),
"b": Series([], dtype=float),
"c": Series([], dtype=float),
"d": Series([], dtype="uint32"),
}
)
for idx, b in enumerate([1, 2, 3]):
df.loc[df.shape[0]] = {
"a": int(idx),
"b": float(b),
"c": float(b),
"d": np.uint32(b),
}
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize(
"obj,dtype",
[
(Period("2020-01"), PeriodDtype("M")),
(Interval(left=0, right=5), IntervalDtype("int64", "right")),
(
Timestamp("2011-01-01", tz="US/Eastern").as_unit("s"),
DatetimeTZDtype(unit="s", tz="US/Eastern"),
),
],
)
def test_setitem_extension_types(self, obj, dtype):
# GH: 34832
expected = DataFrame({"idx": [1, 2, 3], "obj": Series([obj] * 3, dtype=dtype)})
df = DataFrame({"idx": [1, 2, 3]})
df["obj"] = obj
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize(
"ea_name",
[
dtype.name
for dtype in ea_registry.dtypes
# property would require instantiation
if not isinstance(dtype.name, property)
]
+ ["datetime64[ns, UTC]", "period[D]"],
)
def test_setitem_with_ea_name(self, ea_name):
# GH 38386
result = DataFrame([0])
result[ea_name] = [1]
expected = DataFrame({0: [0], ea_name: [1]})
tm.assert_frame_equal(result, expected)
def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self):
# GH#7492
data_ns = np.array([1, "nat"], dtype="datetime64[ns]")
result = Series(data_ns).to_frame()
result["new"] = data_ns
expected = DataFrame({0: [1, None], "new": [1, None]}, dtype="datetime64[ns]")
tm.assert_frame_equal(result, expected)
# OutOfBoundsDatetime error shouldn't occur; as of 2.0 we preserve "M8[s]"
data_s = np.array([1, "nat"], dtype="datetime64[s]")
result["new"] = data_s
tm.assert_series_equal(result[0], expected[0])
tm.assert_numpy_array_equal(result["new"].to_numpy(), data_s)
@pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"])
def test_frame_setitem_datetime64_col_other_units(self, unit):
# Check that non-nano dt64 values get cast to dt64 on setitem
# into a not-yet-existing column
n = 100
dtype = np.dtype(f"M8[{unit}]")
vals = np.arange(n, dtype=np.int64).view(dtype)
if unit in ["s", "ms"]:
# supported unit
ex_vals = vals
else:
# we get the nearest supported units, i.e. "s"
ex_vals = vals.astype("datetime64[s]")
df = DataFrame({"ints": np.arange(n)}, index=np.arange(n))
df[unit] = vals
assert df[unit].dtype == ex_vals.dtype
assert (df[unit].values == ex_vals).all()
@pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"])
def test_frame_setitem_existing_datetime64_col_other_units(self, unit):
# Check that non-nano dt64 values get cast to dt64 on setitem
# into an already-existing dt64 column
n = 100
dtype = np.dtype(f"M8[{unit}]")
vals = np.arange(n, dtype=np.int64).view(dtype)
ex_vals = vals.astype("datetime64[ns]")
df = DataFrame({"ints": np.arange(n)}, index=np.arange(n))
df["dates"] = np.arange(n, dtype=np.int64).view("M8[ns]")
# We overwrite existing dt64 column with new, non-nano dt64 vals
df["dates"] = vals
assert (df["dates"].values == ex_vals).all()
def test_setitem_dt64tz(self, timezone_frame):
df = timezone_frame
idx = df["B"].rename("foo")
# setitem
df["C"] = idx
tm.assert_series_equal(df["C"], Series(idx, name="C"))
df["D"] = "foo"
df["D"] = idx
tm.assert_series_equal(df["D"], Series(idx, name="D"))
del df["D"]
# assert that A & C are not sharing the same base (e.g. they
# are copies)
# Note: This does not hold with Copy on Write (because of lazy copying)
v1 = df._mgr.blocks[1].values
v2 = df._mgr.blocks[2].values
tm.assert_extension_array_equal(v1, v2)
v1base = v1._ndarray.base
v2base = v2._ndarray.base
assert id(v1base) == id(v2base)
# with nan
df2 = df.copy()
df2.iloc[1, 1] = NaT
df2.iloc[1, 2] = NaT
result = df2["B"]
tm.assert_series_equal(notna(result), Series([True, False, True], name="B"))
tm.assert_series_equal(df2.dtypes, df.dtypes)
def test_setitem_periodindex(self):
rng = period_range("1/1/2000", periods=5, name="index")
df = DataFrame(np.random.default_rng(2).standard_normal((5, 3)), index=rng)
df["Index"] = rng
rs = Index(df["Index"])
tm.assert_index_equal(rs, rng, check_names=False)
assert rs.name == "Index"
assert rng.name == "index"
rs = df.reset_index().set_index("index")
assert isinstance(rs.index, PeriodIndex)
tm.assert_index_equal(rs.index, rng)
def test_setitem_complete_column_with_array(self):
# GH#37954
df = DataFrame({"a": ["one", "two", "three"], "b": [1, 2, 3]})
arr = np.array([[1, 1], [3, 1], [5, 1]])
df[["c", "d"]] = arr
expected = DataFrame(
{
"a": ["one", "two", "three"],
"b": [1, 2, 3],
"c": [1, 3, 5],
"d": [1, 1, 1],
}
)
expected["c"] = expected["c"].astype(arr.dtype)
expected["d"] = expected["d"].astype(arr.dtype)
assert expected["c"].dtype == arr.dtype
assert expected["d"].dtype == arr.dtype
tm.assert_frame_equal(df, expected)
def test_setitem_period_d_dtype(self):
# GH 39763
rng = period_range("2016-01-01", periods=9, freq="D", name="A")
result = DataFrame(rng)
expected = DataFrame(
{"A": ["NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT", "NaT"]},
dtype="period[D]",
)
result.iloc[:] = rng._na_value
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("dtype", ["f8", "i8", "u8"])
def test_setitem_bool_with_numeric_index(self, dtype):
# GH#36319
cols = Index([1, 2, 3], dtype=dtype)
df = DataFrame(np.random.default_rng(2).standard_normal((3, 3)), columns=cols)
df[False] = ["a", "b", "c"]
expected_cols = Index([1, 2, 3, False], dtype=object)
if dtype == "f8":
expected_cols = Index([1.0, 2.0, 3.0, False], dtype=object)
tm.assert_index_equal(df.columns, expected_cols)
@pytest.mark.parametrize("indexer", ["B", ["B"]])
def test_setitem_frame_length_0_str_key(self, indexer):
# GH#38831
df = DataFrame(columns=["A", "B"])
other = DataFrame({"B": [1, 2]})
df[indexer] = other
expected = DataFrame({"A": [np.nan] * 2, "B": [1, 2]})
expected["A"] = expected["A"].astype("object")
tm.assert_frame_equal(df, expected)
def test_setitem_frame_duplicate_columns(self):
# GH#15695
cols = ["A", "B", "C"] * 2
df = DataFrame(index=range(3), columns=cols)
df.loc[0, "A"] = (0, 3)
df.loc[:, "B"] = (1, 4)
df["C"] = (2, 5)
expected = DataFrame(
[
[0, 1, 2, 3, 4, 5],
[np.nan, 1, 2, np.nan, 4, 5],
[np.nan, 1, 2, np.nan, 4, 5],
],
dtype="object",
)
# set these with unique columns to be extra-unambiguous
expected[2] = expected[2].astype(np.int64)
expected[5] = expected[5].astype(np.int64)
expected.columns = cols
tm.assert_frame_equal(df, expected)
def test_setitem_frame_duplicate_columns_size_mismatch(self):
# GH#39510
cols = ["A", "B", "C"] * 2
df = DataFrame(index=range(3), columns=cols)
with pytest.raises(ValueError, match="Columns must be same length as key"):
df[["A"]] = (0, 3, 5)
df2 = df.iloc[:, :3] # unique columns
with pytest.raises(ValueError, match="Columns must be same length as key"):
df2[["A"]] = (0, 3, 5)
@pytest.mark.parametrize("cols", [["a", "b", "c"], ["a", "a", "a"]])
def test_setitem_df_wrong_column_number(self, cols):
# GH#38604
df = DataFrame([[1, 2, 3]], columns=cols)
rhs = DataFrame([[10, 11]], columns=["d", "e"])
msg = "Columns must be same length as key"
with pytest.raises(ValueError, match=msg):
df["a"] = rhs
def test_setitem_listlike_indexer_duplicate_columns(self):
# GH#38604
df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"])
rhs = DataFrame([[10, 11, 12]], columns=["a", "b", "b"])
df[["a", "b"]] = rhs
expected = DataFrame([[10, 11, 12]], columns=["a", "b", "b"])
tm.assert_frame_equal(df, expected)
df[["c", "b"]] = rhs
expected = DataFrame([[10, 11, 12, 10]], columns=["a", "b", "b", "c"])
tm.assert_frame_equal(df, expected)
def test_setitem_listlike_indexer_duplicate_columns_not_equal_length(self):
# GH#39403
df = DataFrame([[1, 2, 3]], columns=["a", "b", "b"])
rhs = DataFrame([[10, 11]], columns=["a", "b"])
msg = "Columns must be same length as key"
with pytest.raises(ValueError, match=msg):
df[["a", "b"]] = rhs
def test_setitem_intervals(self):
df = DataFrame({"A": range(10)})
ser = cut(df["A"], 5)
assert isinstance(ser.cat.categories, IntervalIndex)
# B & D end up as Categoricals
# the remainder are converted to in-line objects
# containing an IntervalIndex.values
df["B"] = ser
df["C"] = np.array(ser)
df["D"] = ser.values
df["E"] = np.array(ser.values)
df["F"] = ser.astype(object)
assert isinstance(df["B"].dtype, CategoricalDtype)
assert isinstance(df["B"].cat.categories.dtype, IntervalDtype)
assert isinstance(df["D"].dtype, CategoricalDtype)
assert isinstance(df["D"].cat.categories.dtype, IntervalDtype)
# These go through the Series constructor and so get inferred back
# to IntervalDtype
assert isinstance(df["C"].dtype, IntervalDtype)
assert isinstance(df["E"].dtype, IntervalDtype)
# But the Series constructor doesn't do inference on Series objects,
# so setting df["F"] doesn't get cast back to IntervalDtype
assert is_object_dtype(df["F"])
# they compare equal as Index
# when converted to numpy objects
c = lambda x: Index(np.array(x))
tm.assert_index_equal(c(df.B), c(df.B))
tm.assert_index_equal(c(df.B), c(df.C), check_names=False)
tm.assert_index_equal(c(df.B), c(df.D), check_names=False)
tm.assert_index_equal(c(df.C), c(df.D), check_names=False)
# B & D are the same Series
tm.assert_series_equal(df["B"], df["B"])
tm.assert_series_equal(df["B"], df["D"], check_names=False)
# C & E are the same Series
tm.assert_series_equal(df["C"], df["C"])
tm.assert_series_equal(df["C"], df["E"], check_names=False)
def test_setitem_categorical(self):
# GH#35369
df = DataFrame({"h": Series(list("mn")).astype("category")})
df.h = df.h.cat.reorder_categories(["n", "m"])
expected = DataFrame(
{"h": Categorical(["m", "n"]).reorder_categories(["n", "m"])}
)
tm.assert_frame_equal(df, expected)
def test_setitem_with_empty_listlike(self):
# GH#17101
index = Index([], name="idx")
result = DataFrame(columns=["A"], index=index)
result["A"] = []
expected = DataFrame(columns=["A"], index=index)
tm.assert_index_equal(result.index, expected.index)
@pytest.mark.parametrize(
"cols, values, expected",
[
(["C", "D", "D", "a"], [1, 2, 3, 4], 4), # with duplicates
(["D", "C", "D", "a"], [1, 2, 3, 4], 4), # mixed order
(["C", "B", "B", "a"], [1, 2, 3, 4], 4), # other duplicate cols
(["C", "B", "a"], [1, 2, 3], 3), # no duplicates
(["B", "C", "a"], [3, 2, 1], 1), # alphabetical order
(["C", "a", "B"], [3, 2, 1], 2), # in the middle
],
)
def test_setitem_same_column(self, cols, values, expected):
# GH#23239
df = DataFrame([values], columns=cols)
df["a"] = df["a"]
result = df["a"].values[0]
assert result == expected
def test_setitem_multi_index(self):
# GH#7655, test that assigning to a sub-frame of a frame
# with multi-index columns aligns both rows and columns
it = ["jim", "joe", "jolie"], ["first", "last"], ["left", "center", "right"]
cols = MultiIndex.from_product(it)
index = date_range("20141006", periods=20)
vals = np.random.default_rng(2).integers(1, 1000, (len(index), len(cols)))
df = DataFrame(vals, columns=cols, index=index)
i, j = df.index.values.copy(), it[-1][:]
np.random.default_rng(2).shuffle(i)
df["jim"] = df["jolie"].loc[i, ::-1]
tm.assert_frame_equal(df["jim"], df["jolie"])
np.random.default_rng(2).shuffle(j)
df[("joe", "first")] = df[("jolie", "last")].loc[i, j]
tm.assert_frame_equal(df[("joe", "first")], df[("jolie", "last")])
np.random.default_rng(2).shuffle(j)
df[("joe", "last")] = df[("jolie", "first")].loc[i, j]
tm.assert_frame_equal(df[("joe", "last")], df[("jolie", "first")])
@pytest.mark.parametrize(
"columns,box,expected",
[
(
["A", "B", "C", "D"],
7,
DataFrame(
[[7, 7, 7, 7], [7, 7, 7, 7], [7, 7, 7, 7]],
columns=["A", "B", "C", "D"],
),
),
(
["C", "D"],
[7, 8],
DataFrame(
[[1, 2, 7, 8], [3, 4, 7, 8], [5, 6, 7, 8]],
columns=["A", "B", "C", "D"],
),
),
(
["A", "B", "C"],
np.array([7, 8, 9], dtype=np.int64),
DataFrame([[7, 8, 9], [7, 8, 9], [7, 8, 9]], columns=["A", "B", "C"]),
),
(
["B", "C", "D"],
[[7, 8, 9], [10, 11, 12], [13, 14, 15]],
DataFrame(
[[1, 7, 8, 9], [3, 10, 11, 12], [5, 13, 14, 15]],
columns=["A", "B", "C", "D"],
),
),
(
["C", "A", "D"],
np.array([[7, 8, 9], [10, 11, 12], [13, 14, 15]], dtype=np.int64),
DataFrame(
[[8, 2, 7, 9], [11, 4, 10, 12], [14, 6, 13, 15]],
columns=["A", "B", "C", "D"],
),
),
(
["A", "C"],
DataFrame([[7, 8], [9, 10], [11, 12]], columns=["A", "C"]),
DataFrame(
[[7, 2, 8], [9, 4, 10], [11, 6, 12]], columns=["A", "B", "C"]
),
),
],
)
def test_setitem_list_missing_columns(self, columns, box, expected):
# GH#29334
df = DataFrame([[1, 2], [3, 4], [5, 6]], columns=["A", "B"])
df[columns] = box
tm.assert_frame_equal(df, expected)
def test_setitem_list_of_tuples(self, float_frame):
tuples = list(zip(float_frame["A"], float_frame["B"]))
float_frame["tuples"] = tuples
result = float_frame["tuples"]
expected = Series(tuples, index=float_frame.index, name="tuples")
tm.assert_series_equal(result, expected)
def test_setitem_iloc_generator(self):
# GH#39614
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
indexer = (x for x in [1, 2])
df.iloc[indexer] = 1
expected = DataFrame({"a": [1, 1, 1], "b": [4, 1, 1]})
tm.assert_frame_equal(df, expected)
def test_setitem_iloc_two_dimensional_generator(self):
df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
indexer = (x for x in [1, 2])
df.iloc[indexer, 1] = 1
expected = DataFrame({"a": [1, 2, 3], "b": [4, 1, 1]})
tm.assert_frame_equal(df, expected)
def test_setitem_dtypes_bytes_type_to_object(self):
# GH 20734
index = Series(name="id", dtype="S24")
df = DataFrame(index=index, columns=Index([], dtype="str"))
df["a"] = Series(name="a", index=index, dtype=np.uint32)
df["b"] = Series(name="b", index=index, dtype="S64")
df["c"] = Series(name="c", index=index, dtype="S64")
df["d"] = Series(name="d", index=index, dtype=np.uint8)
result = df.dtypes
expected = Series([np.uint32, object, object, np.uint8], index=list("abcd"))
tm.assert_series_equal(result, expected)
def test_boolean_mask_nullable_int64(self):
# GH 28928
result = DataFrame({"a": [3, 4], "b": [5, 6]}).astype(
{"a": "int64", "b": "Int64"}
)
mask = Series(False, index=result.index)
result.loc[mask, "a"] = result["a"]
result.loc[mask, "b"] = result["b"]
expected = DataFrame({"a": [3, 4], "b": [5, 6]}).astype(
{"a": "int64", "b": "Int64"}
)
tm.assert_frame_equal(result, expected)
def test_setitem_ea_dtype_rhs_series(self):
# GH#47425
df = DataFrame({"a": [1, 2]})
df["a"] = Series([1, 2], dtype="Int64")
expected = DataFrame({"a": [1, 2]}, dtype="Int64")
tm.assert_frame_equal(df, expected)
def test_setitem_npmatrix_2d(self):
# GH#42376
# for use-case df["x"] = sparse.random((10, 10)).mean(axis=1)
expected = DataFrame(
{"np-array": np.ones(10), "np-matrix": np.ones(10)}, index=np.arange(10)
)
a = np.ones((10, 1))
df = DataFrame(index=np.arange(10), columns=Index([], dtype="str"))
df["np-array"] = a
# Instantiation of `np.matrix` gives PendingDeprecationWarning
with tm.assert_produces_warning(
PendingDeprecationWarning,
match="matrix subclass is not the recommended way to represent matrices",
):
df["np-matrix"] = np.matrix(a)
tm.assert_frame_equal(df, expected)
@pytest.mark.parametrize("vals", [{}, {"d": "a"}])
def test_setitem_aligning_dict_with_index(self, vals):
# GH#47216
df = DataFrame({"a": [1, 2], "b": [3, 4], **vals})
df.loc[:, "a"] = {1: 100, 0: 200}
df.loc[:, "c"] = {0: 5, 1: 6}
df.loc[:, "e"] = {1: 5}
expected = DataFrame(
{"a": [200, 100], "b": [3, 4], **vals, "c": [5, 6], "e": [np.nan, 5]}
)
tm.assert_frame_equal(df, expected)
def test_setitem_rhs_dataframe(self):
# GH#47578
df = DataFrame({"a": [1, 2]})
df["a"] = DataFrame({"a": [10, 11]}, index=[1, 2])
expected = DataFrame({"a": [np.nan, 10]})
tm.assert_frame_equal(df, expected)
df = DataFrame({"a": [1, 2]})
df.isetitem(0, DataFrame({"a": [10, 11]}, index=[1, 2]))
tm.assert_frame_equal(df, expected)
def test_setitem_frame_overwrite_with_ea_dtype(self, any_numeric_ea_dtype):
# GH#46896
df = DataFrame(columns=["a", "b"], data=[[1, 2], [3, 4]])
df["a"] = DataFrame({"a": [10, 11]}, dtype=any_numeric_ea_dtype)
expected = DataFrame(
{
"a": Series([10, 11], dtype=any_numeric_ea_dtype),
"b": [2, 4],
}
)
tm.assert_frame_equal(df, expected)
def test_setitem_string_option_object_index(self):
# GH#55638
pytest.importorskip("pyarrow")
df = DataFrame({"a": [1, 2]})
with pd.option_context("future.infer_string", True):
df["b"] = Index(["a", "b"], dtype=object)
expected = DataFrame({"a": [1, 2], "b": Series(["a", "b"], dtype=object)})
tm.assert_frame_equal(df, expected)
def test_setitem_frame_midx_columns(self):
# GH#49121
df = DataFrame({("a", "b"): [10]})
expected = df.copy()
col_name = ("a", "b")
df[col_name] = df[[col_name]]
tm.assert_frame_equal(df, expected)
def test_loc_setitem_ea_dtype(self):
# GH#55604
df = DataFrame({"a": np.array([10], dtype="i8")})
df.loc[:, "a"] = Series([11], dtype="Int64")
expected = DataFrame({"a": np.array([11], dtype="i8")})
tm.assert_frame_equal(df, expected)
df = DataFrame({"a": np.array([10], dtype="i8")})
df.iloc[:, 0] = Series([11], dtype="Int64")
tm.assert_frame_equal(df, expected)
def test_setitem_index_object_dtype_not_inferring(self):
# GH#56102
idx = Index([Timestamp("2019-12-31")], dtype=object)
df = DataFrame({"a": [1]})
df.loc[:, "b"] = idx
df["c"] = idx
expected = DataFrame(
{
"a": [1],
"b": idx,
"c": idx,
}
)
tm.assert_frame_equal(df, expected)
| TestDataFrameSetItem |
python | dagster-io__dagster | helm/dagster/schema/schema/utils/helm_template.py | {
"start": 623,
"end": 4577
} | class ____:
helm_dir_path: str
subchart_paths: list[str]
output: Optional[str] = None
model: Optional[Any] = None
release_name: str = "release-name"
api_client: ApiClient = ApiClient() # noqa: RUF009
namespace: str = "default"
def render(
self,
values: Optional[Union[DagsterHelmValues, DagsterUserDeploymentsHelmValues]] = None,
values_dict: Optional[dict[str, Any]] = None,
chart_version: Optional[str] = None,
) -> list[Any]:
check.invariant(
(values is None) != (values_dict is None), "Must provide either values or values_dict"
)
with NamedTemporaryFile() as tmp_file:
helm_dir_path = os.path.join(git_repo_root(), self.helm_dir_path)
values_json = (
json.loads(values.model_dump_json(exclude_none=True, by_alias=True))
if values
else values_dict
)
pprint(values_json) # noqa: T203
content = yaml.dump(values_json)
tmp_file.write(content.encode())
tmp_file.flush()
command = [
"helm",
"template",
self.release_name,
helm_dir_path,
"--debug",
"--namespace",
self.namespace,
"--values",
tmp_file.name,
]
with self._with_chart_yaml(helm_dir_path, chart_version):
templates = subprocess.check_output(command)
# HACK! Helm's --show-only option doesn't surface errors. For tests where we want to
# assert on things like {{ fail ... }}, we need to render the chart without --show-only.
# If that succeeds, we then carry on to calling with --show-only so that we can
# assert on specific objects in the chart.
if self.output:
command += ["--show-only", self.output]
templates = subprocess.check_output(command)
print("\n--- Helm Templates ---") # noqa: T201
print(templates.decode()) # noqa: T201
k8s_objects = [k8s_object for k8s_object in yaml.full_load_all(templates) if k8s_object]
if self.model:
k8s_objects = [
self.api_client._ApiClient__deserialize_model( # noqa: SLF001
k8s_object,
self.model,
)
for k8s_object in k8s_objects
]
return k8s_objects
@contextmanager
def _with_chart_yaml(self, helm_dir_path: str, chart_version: Optional[str]):
if not chart_version:
yield
else:
umbrella_chart_path = os.path.join(helm_dir_path, "Chart.yaml")
subchart_chart_paths = [
os.path.join(helm_dir_path, subchart_path, "Chart.yaml")
for subchart_path in self.subchart_paths
]
chart_paths = subchart_chart_paths + [umbrella_chart_path]
chart_copy_paths = []
for chart_path in chart_paths:
_, chart_copy_path = mkstemp()
shutil.copy2(chart_path, chart_copy_path)
chart_copy_paths.append(chart_copy_path)
with open(chart_path, encoding="utf8") as chart_file:
old_chart_yaml = yaml.safe_load(chart_file)
with open(chart_path, "w", encoding="utf8") as chart_file:
new_chart_yaml = old_chart_yaml.copy()
new_chart_yaml["version"] = chart_version
yaml.dump(new_chart_yaml, chart_file)
yield
for chart_path, chart_copy_path in zip(chart_paths, chart_copy_paths):
shutil.copy2(chart_copy_path, chart_path)
os.remove(chart_copy_path)
| HelmTemplate |
python | pytorch__pytorch | torch/_inductor/standalone_compile.py | {
"start": 972,
"end": 3686
} | class ____(ABC):
"""
CompiledArtifact class represents the inductor cache artifacts that
can be invoked in order to avoid repeated compilation.
CompiledArtifact can be obtained by calling standalone_compile(gm, example_inputs)
to create a fresh CompiledArtifact from a GraphModule and example inputs.
Later this CompiledArtifact can be saved to disk, either as a binary or unpacked
into the provided folder via the CompiledArtifact.save function.
CompiledArtifact.load provides a way to create a CompiledArtifact from the
binary or unpacked data.
Finally, the CompiledArtifact can be invoked via the __call__ method
to execute the cached artifact.
"""
def __init__(
self,
compiled_fn: Callable[..., Any],
artifacts: Optional[tuple[bytes, CacheInfo]],
):
self._compiled_fn = compiled_fn
self._artifacts = artifacts
@abstractmethod
def __call__(self, *args: Any) -> Any: ...
@abstractmethod
def save(
self, *, path: str, format: Literal["binary", "unpacked"] = "binary"
) -> None: ...
@staticmethod
def load(
*, path: str, format: Literal["binary", "unpacked"] = "binary"
) -> CompiledArtifact:
if format == "unpacked":
# If format is unpacked, it must be a CacheCompiledArtifact
return CacheCompiledArtifact.load(path=path, format=format)
assert format == "binary"
with open(path, "rb") as file:
from torch.utils._appending_byte_serializer import BytesReader
from .codecache import torch_key
result_bytes = file.read()
reader = BytesReader(result_bytes)
header = reader.read_bytes()
if header == AOTCompiledArtifact.AOT_HEADER:
assert reader.read_bytes() == torch_key()
artifact = reader.read_bytes()
assert reader.is_finished()
return AOTCompiledArtifact.deserialize(artifact)
# Otherwise, it's in the CacheCompiledArtifact format
elif header == CacheCompiledArtifact.CACHE_HEADER:
assert reader.read_bytes() == torch_key()
key = reader.read_str()
artifact_bytes = reader.read_bytes()
assert reader.is_finished()
torch.compiler.load_cache_artifacts(artifact_bytes)
return CacheCompiledArtifact._load_impl(nullcontext(), key)
else:
raise RuntimeError(
"Invalid header, expected CacheCompiledArtifact or AOTCompiledArtifact, got: "
+ header.decode("utf-8")
)
| CompiledArtifact |
python | realpython__materials | python-class/week.py | {
"start": 24,
"end": 296
} | class ____(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
@classmethod
def favorite_day(cls):
return cls.FRIDAY
def __str__(self):
return f"Current day: {self.name}"
| WeekDay |
python | huggingface__transformers | src/transformers/models/dinat/modeling_dinat.py | {
"start": 27617,
"end": 31486
} | class ____(DinatPreTrainedModel, BackboneMixin):
def __init__(self, config):
super().__init__(config)
super()._init_backbone(config)
requires_backends(self, ["natten"])
self.embeddings = DinatEmbeddings(config)
self.encoder = DinatEncoder(config)
self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))]
# Add layer norms to hidden states of out_features
hidden_states_norms = {}
for stage, num_channels in zip(self._out_features, self.channels):
hidden_states_norms[stage] = nn.LayerNorm(num_channels)
self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
# Initialize weights and apply final processing
self.post_init()
def get_input_embeddings(self):
return self.embeddings.patch_embeddings
@auto_docstring
def forward(
self,
pixel_values: torch.Tensor,
output_hidden_states: Optional[bool] = None,
output_attentions: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> BackboneOutput:
r"""
Examples:
```python
>>> from transformers import AutoImageProcessor, AutoBackbone
>>> import torch
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> processor = AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224")
>>> model = AutoBackbone.from_pretrained(
... "shi-labs/nat-mini-in1k-224", out_features=["stage1", "stage2", "stage3", "stage4"]
... )
>>> inputs = processor(image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 512, 7, 7]
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
embedding_output = self.embeddings(pixel_values)
outputs = self.encoder(
embedding_output,
output_attentions=output_attentions,
output_hidden_states=True,
output_hidden_states_before_downsampling=True,
return_dict=True,
)
hidden_states = outputs.reshaped_hidden_states
feature_maps = ()
for stage, hidden_state in zip(self.stage_names, hidden_states):
if stage in self.out_features:
batch_size, num_channels, height, width = hidden_state.shape
hidden_state = hidden_state.permute(0, 2, 3, 1).contiguous()
hidden_state = hidden_state.view(batch_size, height * width, num_channels)
hidden_state = self.hidden_states_norms[stage](hidden_state)
hidden_state = hidden_state.view(batch_size, height, width, num_channels)
hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
feature_maps += (hidden_state,)
if not return_dict:
output = (feature_maps,)
if output_hidden_states:
output += (outputs.hidden_states,)
return output
return BackboneOutput(
feature_maps=feature_maps,
hidden_states=outputs.hidden_states if output_hidden_states else None,
attentions=outputs.attentions,
)
__all__ = ["DinatForImageClassification", "DinatModel", "DinatPreTrainedModel", "DinatBackbone"]
| DinatBackbone |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context_creation_job.py | {
"start": 13721,
"end": 20602
} | class ____(ExecutionContextManager[PlanExecutionContext]):
def __init__(
self,
job: IJob,
execution_plan: ExecutionPlan,
run_config: Mapping[str, object],
dagster_run: DagsterRun,
instance: DagsterInstance,
retry_mode: RetryMode,
scoped_resources_builder_cm: Optional[
Callable[..., EventGenerationManager[ScopedResourcesBuilder]]
] = None,
raise_on_error: Optional[bool] = False,
output_capture: Optional[dict["StepOutputHandle", Any]] = None,
step_dependency_config: StepDependencyConfig = StepDependencyConfig.default(),
):
super().__init__(
execution_context_event_generator(
job,
execution_plan,
run_config,
dagster_run,
instance,
retry_mode,
scoped_resources_builder_cm,
raise_on_error=raise_on_error,
output_capture=output_capture,
step_dependency_config=step_dependency_config,
)
)
@property
def context_type(self) -> type[PlanExecutionContext]:
return PlanExecutionContext
# perform any plan validation that is dependent on access to the pipeline context
def _validate_plan_with_context(job_context: IPlanContext, execution_plan: ExecutionPlan) -> None:
validate_reexecution_memoization(job_context, execution_plan)
def create_executor(context_creation_data: ContextCreationData) -> "Executor":
check.inst_param(context_creation_data, "context_creation_data", ContextCreationData)
init_context = InitExecutorContext(
job=context_creation_data.job,
executor_def=context_creation_data.executor_def,
executor_config=context_creation_data.resolved_run_config.execution.execution_engine_config,
instance=context_creation_data.instance,
)
check_cross_process_constraints(init_context)
creation_fn = check.not_none(context_creation_data.executor_def.executor_creation_fn)
return creation_fn(init_context)
@contextmanager
def scoped_job_context(
execution_plan: ExecutionPlan,
job: IJob,
run_config: Mapping[str, object],
dagster_run: DagsterRun,
instance: DagsterInstance,
scoped_resources_builder_cm: Callable[
..., EventGenerationManager[ScopedResourcesBuilder]
] = resource_initialization_manager,
raise_on_error: Optional[bool] = False,
) -> Generator[PlanExecutionContext, None, None]:
"""Utility context manager which acts as a very thin wrapper around
`pipeline_initialization_manager`, iterating through all the setup/teardown events and
discarding them. It yields the resulting `pipeline_context`.
Should only be used where we need to reconstruct the pipeline context, ignoring any yielded
events (e.g. JobExecutionResult, dagstermill, unit tests, etc)
"""
check.inst_param(execution_plan, "execution_plan", ExecutionPlan)
check.inst_param(job, "job", IJob)
check.mapping_param(run_config, "run_config", key_type=str)
check.inst_param(dagster_run, "dagster_run", DagsterRun)
check.inst_param(instance, "instance", DagsterInstance)
check.callable_param(scoped_resources_builder_cm, "scoped_resources_builder_cm")
initialization_manager = PlanExecutionContextManager(
job,
execution_plan,
run_config,
dagster_run,
instance,
RetryMode.DISABLED,
scoped_resources_builder_cm=scoped_resources_builder_cm,
raise_on_error=raise_on_error,
)
for _ in initialization_manager.prepare_context():
pass
try:
yield check.inst(initialization_manager.get_context(), PlanExecutionContext)
finally:
for _ in initialization_manager.shutdown_context():
pass
def create_log_manager(
context_creation_data: ContextCreationData,
) -> "DagsterLogManager":
from dagster._core.log_manager import DagsterLogManager
check.inst_param(context_creation_data, "context_creation_data", ContextCreationData)
job_def, resolved_run_config, dagster_run = (
context_creation_data.job_def,
context_creation_data.resolved_run_config,
context_creation_data.dagster_run,
)
# The following logic is tightly coupled to the processing of logger config in
# python_modules/dagster/dagster/_core/system_config/objects.py#config_map_loggers
# Changes here should be accompanied checked against that function, which applies config mapping
# via ConfigurableDefinition (@configured) to incoming logger configs. See docstring for more details.
loggers = []
for logger_key, logger_def in job_def.loggers.items() or default_loggers().items():
if logger_key in resolved_run_config.loggers:
loggers.append(
logger_def.logger_fn(
InitLoggerContext(
resolved_run_config.loggers.get(logger_key, {}).get("config"),
logger_def,
job_def=job_def,
run_id=dagster_run.run_id,
)
)
)
if not loggers:
for logger_def, logger_config in default_system_loggers(context_creation_data.instance):
loggers.append(
logger_def.logger_fn(
InitLoggerContext(
logger_config,
logger_def,
job_def=job_def,
run_id=dagster_run.run_id,
)
)
)
return DagsterLogManager.create(
loggers=loggers, dagster_run=dagster_run, instance=context_creation_data.instance
)
def create_context_free_log_manager(
instance: DagsterInstance, dagster_run: DagsterRun
) -> "DagsterLogManager":
"""In the event of pipeline initialization failure, we want to be able to log the failure
without a dependency on the PlanExecutionContext to initialize DagsterLogManager.
Args:
dagster_run (PipelineRun)
pipeline_def (JobDefinition)
"""
from dagster._core.log_manager import DagsterLogManager
check.inst_param(instance, "instance", DagsterInstance)
check.inst_param(dagster_run, "dagster_run", DagsterRun)
loggers = []
# Use the default logger
for logger_def, logger_config in default_system_loggers(instance):
loggers += [
logger_def.logger_fn(
InitLoggerContext(
logger_config,
logger_def,
job_def=None,
run_id=dagster_run.run_id,
)
)
]
return DagsterLogManager.create(loggers=loggers, instance=instance, dagster_run=dagster_run)
| PlanExecutionContextManager |
python | huggingface__transformers | src/transformers/models/minimax/modeling_minimax.py | {
"start": 24853,
"end": 27471
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MiniMaxConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MiniMaxAttention(config, layer_idx)
self.input_layernorm = MiniMaxRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = MiniMaxRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.layer_idx = layer_idx
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.mlp_alpha_factor = config.mlp_alpha_factor
self.mlp_beta_factor = config.mlp_beta_factor
self.mlp = MiniMaxSparseMoeBlock(config)
if self.layer_type == "linear_attention":
self.self_attn = MiniMaxLightningAttention(config, layer_idx)
self.attn_alpha_factor = config.linear_attn_alpha_factor
self.attn_beta_factor = config.linear_attn_beta_factor
else:
self.self_attn = MiniMaxAttention(config, layer_idx)
self.attn_alpha_factor = config.full_attn_alpha_factor
self.attn_beta_factor = config.full_attn_beta_factor
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
hidden_states = self.input_layernorm(hidden_states)
residual = hidden_states
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
position_embeddings=position_embeddings,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
**kwargs,
)
hidden_states = residual * self.attn_alpha_factor + hidden_states * self.attn_beta_factor
hidden_states = self.post_attention_layernorm(hidden_states)
residual = hidden_states
hidden_states = self.mlp(hidden_states)
hidden_states = residual * self.mlp_alpha_factor + hidden_states * self.mlp_beta_factor
return hidden_states
@auto_docstring
| MiniMaxDecoderLayer |
python | pytorch__pytorch | test/inductor/test_provenance_tracing.py | {
"start": 18399,
"end": 20303
} | class ____(TestCase):
def get_node_with_target(self, gm, target):
"""
Return first node in gm with target
"""
return next(iter([node for node in gm.graph.nodes if node.target == target]))
@requires_gpu_and_triton # test only works for cuda pattern matcher
def test_pattern_matcher_transfer_meta(self):
"""
Test that stack trace is transferred when node is decomposed in post_grad_passes
"""
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.fc1 = torch.nn.Linear(10, 16)
self.relu = torch.nn.ReLU()
self.sigmoid = torch.nn.Sigmoid()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.sigmoid(x)
return x * 3
x = torch.randn(8, 10).to(GPU_TYPE)
example_inputs = (x,)
model = Model().to(GPU_TYPE)
# mimic the before_post_grad graph
ep = torch.export.export(model, example_inputs).run_decompositions()
gm = ep.module()
# Set fake mode for V
fake_inputs = [
node.meta.get("val") for node in gm.graph.nodes if node.op == "placeholder"
]
fake_mode = detect_fake_mode(fake_inputs)
V.set_fake_mode(fake_mode)
addmm_node = self.get_node_with_target(gm, torch.ops.aten.addmm.default)
stack_trace = addmm_node.meta["stack_trace"]
post_grad_passes(gm, True) # for this test is_inference doesn't matter
mm_node = self.get_node_with_target(gm, torch.ops.aten.mm.default)
add_node = self.get_node_with_target(gm, torch.ops.aten.add.Tensor)
self.assertEqual(add_node.meta["stack_trace"], stack_trace)
self.assertEqual(mm_node.meta["stack_trace"], stack_trace)
| TestProvenanceTracingNodeMeta |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/sqlite/base.py | {
"start": 67876,
"end": 70036
} | class ____(compiler.IdentifierPreparer):
reserved_words = {
"add",
"after",
"all",
"alter",
"analyze",
"and",
"as",
"asc",
"attach",
"autoincrement",
"before",
"begin",
"between",
"by",
"cascade",
"case",
"cast",
"check",
"collate",
"column",
"commit",
"conflict",
"constraint",
"create",
"cross",
"current_date",
"current_time",
"current_timestamp",
"database",
"default",
"deferrable",
"deferred",
"delete",
"desc",
"detach",
"distinct",
"drop",
"each",
"else",
"end",
"escape",
"except",
"exclusive",
"exists",
"explain",
"false",
"fail",
"for",
"foreign",
"from",
"full",
"glob",
"group",
"having",
"if",
"ignore",
"immediate",
"in",
"index",
"indexed",
"initially",
"inner",
"insert",
"instead",
"intersect",
"into",
"is",
"isnull",
"join",
"key",
"left",
"like",
"limit",
"match",
"natural",
"not",
"notnull",
"null",
"of",
"offset",
"on",
"or",
"order",
"outer",
"plan",
"pragma",
"primary",
"query",
"raise",
"references",
"reindex",
"rename",
"replace",
"restrict",
"right",
"rollback",
"row",
"select",
"set",
"table",
"temp",
"temporary",
"then",
"to",
"transaction",
"trigger",
"true",
"union",
"unique",
"update",
"using",
"vacuum",
"values",
"view",
"virtual",
"when",
"where",
}
| SQLiteIdentifierPreparer |
python | pytorch__pytorch | torch/nn/modules/linear.py | {
"start": 4876,
"end": 5206
} | class ____(Linear):
def __init__(
self,
in_features: int,
out_features: int,
bias: bool = True,
device=None,
dtype=None,
) -> None:
super().__init__(
in_features, out_features, bias=bias, device=device, dtype=dtype
)
| NonDynamicallyQuantizableLinear |
python | kubernetes-client__python | kubernetes/client/models/v2_metric_value_status.py | {
"start": 383,
"end": 5872
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'average_utilization': 'int',
'average_value': 'str',
'value': 'str'
}
attribute_map = {
'average_utilization': 'averageUtilization',
'average_value': 'averageValue',
'value': 'value'
}
def __init__(self, average_utilization=None, average_value=None, value=None, local_vars_configuration=None): # noqa: E501
"""V2MetricValueStatus - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._average_utilization = None
self._average_value = None
self._value = None
self.discriminator = None
if average_utilization is not None:
self.average_utilization = average_utilization
if average_value is not None:
self.average_value = average_value
if value is not None:
self.value = value
@property
def average_utilization(self):
"""Gets the average_utilization of this V2MetricValueStatus. # noqa: E501
currentAverageUtilization is the current value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. # noqa: E501
:return: The average_utilization of this V2MetricValueStatus. # noqa: E501
:rtype: int
"""
return self._average_utilization
@average_utilization.setter
def average_utilization(self, average_utilization):
"""Sets the average_utilization of this V2MetricValueStatus.
currentAverageUtilization is the current value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. # noqa: E501
:param average_utilization: The average_utilization of this V2MetricValueStatus. # noqa: E501
:type: int
"""
self._average_utilization = average_utilization
@property
def average_value(self):
"""Gets the average_value of this V2MetricValueStatus. # noqa: E501
averageValue is the current value of the average of the metric across all relevant pods (as a quantity) # noqa: E501
:return: The average_value of this V2MetricValueStatus. # noqa: E501
:rtype: str
"""
return self._average_value
@average_value.setter
def average_value(self, average_value):
"""Sets the average_value of this V2MetricValueStatus.
averageValue is the current value of the average of the metric across all relevant pods (as a quantity) # noqa: E501
:param average_value: The average_value of this V2MetricValueStatus. # noqa: E501
:type: str
"""
self._average_value = average_value
@property
def value(self):
"""Gets the value of this V2MetricValueStatus. # noqa: E501
value is the current value of the metric (as a quantity). # noqa: E501
:return: The value of this V2MetricValueStatus. # noqa: E501
:rtype: str
"""
return self._value
@value.setter
def value(self, value):
"""Sets the value of this V2MetricValueStatus.
value is the current value of the metric (as a quantity). # noqa: E501
:param value: The value of this V2MetricValueStatus. # noqa: E501
:type: str
"""
self._value = value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V2MetricValueStatus):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V2MetricValueStatus):
return True
return self.to_dict() != other.to_dict()
| V2MetricValueStatus |
python | getsentry__sentry | src/sentry/analytics/events/inapp_request.py | {
"start": 67,
"end": 278
} | class ____(analytics.Event, abc.ABC):
organization_id: int
user_id: int | None = None
target_user_id: int
providers: str
subtype: str | None = None
@analytics.eventclass()
| InAppRequestSentEvent |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/tests/test_util.py | {
"start": 20486,
"end": 30550
} | class ____(parameterized.TestCase):
"""Base class for tests including numerical checks and boilerplate."""
# copied from jax.test_util
def setUp(self):
super().setUp()
self._rng = npr.RandomState(zlib.adler32(self._testMethodName.encode()))
# copied from jax.test_util
def rng(self):
return self._rng
# TODO(mattjj): this obscures the error messages from failures, figure out how
# to re-enable it
# def tearDown(self) -> None:
# assert core.reset_trace_state()
def assertArraysAllClose(self, x, y, check_dtypes, atol=None, rtol=None):
"""Assert that x and y are close (up to numerical tolerances)."""
self.assertEqual(x.shape, y.shape)
atol = max(tolerance(_dtype(x), atol), tolerance(_dtype(y), atol))
rtol = max(tolerance(_dtype(x), rtol), tolerance(_dtype(y), rtol))
_assert_numpy_allclose(x, y, atol=atol, rtol=rtol)
if check_dtypes:
self.assertDtypesMatch(x, y)
def assertDtypesMatch(self, x, y):
if FLAGS.enable_x64:
self.assertEqual(_dtype(x), _dtype(y))
def assertAllClose(self, x, y, check_dtypes, atol=None, rtol=None):
"""Assert that x and y, either arrays or nested tuples/lists, are close."""
if isinstance(x, dict):
self.assertIsInstance(y, dict)
self.assertEqual(set(x.keys()), set(y.keys()))
for k in x:
self.assertAllClose(x[k], y[k], check_dtypes, atol=atol, rtol=rtol)
elif is_sequence(x) and not hasattr(x, '__array__'):
self.assertTrue(is_sequence(y) and not hasattr(y, '__array__'))
self.assertEqual(len(x), len(y))
for x_elt, y_elt in zip(x, y):
self.assertAllClose(x_elt, y_elt, check_dtypes, atol=atol, rtol=rtol)
elif hasattr(x, '__array__') or onp.isscalar(x):
self.assertTrue(hasattr(y, '__array__') or onp.isscalar(y))
if check_dtypes:
self.assertDtypesMatch(x, y)
x = numpy_compat.np_asarray(x)
y = numpy_compat.np_asarray(y)
self.assertArraysAllClose(x, y, check_dtypes=False, atol=atol, rtol=rtol)
elif x == y:
return
else:
raise TypeError((type(x), type(y)))
def assertMultiLineStrippedEqual(self, expected, what):
"""Asserts two strings are equal, after stripping each line."""
ignore_space_re = re.compile(r'\s*\n\s*')
expected_clean = re.sub(ignore_space_re, '\n', expected.strip())
what_clean = re.sub(ignore_space_re, '\n', what.strip())
self.assertMultiLineEqual(expected_clean, what_clean,
msg="Found\n{}\nExpecting\n{}".format(what, expected))
def _CheckAgainstNumpy(self, numpy_reference_op, lax_op, args_maker,
check_dtypes=True, tol=None):
args = args_maker()
lax_ans = lax_op(*args)
numpy_ans = numpy_reference_op(*args)
self.assertAllClose(numpy_ans, lax_ans, check_dtypes=check_dtypes,
atol=tol, rtol=tol)
def _CompileAndCheck(self,
fun,
args_maker,
check_dtypes=True,
rtol=None,
atol=None,
check_eval_on_shapes=True,
check_incomplete_shape=True,
check_unknown_rank=True,
static_argnums=(),
check_experimental_compile=True,
check_xla_forced_compile=True):
"""Compiles the function and checks the results.
Args:
fun: the function to be checked.
args_maker: a callable that returns a tuple which will be used as the
positional arguments.
check_dtypes: whether to check that the result dtypes from non-compiled
and compiled runs agree.
rtol: relative tolerance for allclose assertions.
atol: absolute tolerance for allclose assertions.
check_eval_on_shapes: whether to run `eval_on_shapes` on the function and
check that the result shapes and dtypes are correct.
check_incomplete_shape: whether to check that the function can handle
incomplete shapes (including those with and without a known rank).
check_unknown_rank: (only has effect when check_incomplete_shape is True)
whether to check that the function can handle unknown ranks.
static_argnums: indices of arguments to be treated as static arguments for
`jit` and `eval_on_shapes`.
check_experimental_compile: whether to check compilation with
experimental_compile=True (in addition to compilation without the flag).
check_xla_forced_compile: whether to check compilation with
forced_compile=True (in addition to compilation without the flag). This
flag is different from experimental_compile because it enforces
whole-function compilation while the latter doesn't. TPU requires
whole-function compilation.
"""
args = args_maker()
for x in args:
if not hasattr(x, 'dtype'):
# If there is a input that doesn't have dtype info, jit and
# eval_on_shapes may pick a different dtype for it than numpy, so we
# skip the dtype check.
check_dtypes = False
python_ans = fun(*args)
python_shapes = nest.map_structure(onp.shape, python_ans)
onp_shapes = nest.map_structure(
lambda x: onp.shape(numpy_compat.np_asarray(x)), python_ans
)
self.assertEqual(python_shapes, onp_shapes)
def check_compile(**kwargs):
# `wrapped_fun` and `python_should_be_executing` are used to check that
# when the jitted function is called the second time, the original Python
# function won't be executed.
def wrapped_fun(*args):
self.assertTrue(python_should_be_executing)
return fun(*args)
cfun = nje.jit(wrapped_fun, static_argnums=static_argnums, **kwargs)
python_should_be_executing = True
monitored_ans = cfun(*args)
python_should_be_executing = False
compiled_ans = cfun(*args)
self.assertAllClose(python_ans, monitored_ans, check_dtypes, atol, rtol)
self.assertAllClose(python_ans, compiled_ans, check_dtypes, atol, rtol)
# Run `cfun` with a different set of arguments to check that changing
# arguments won't cause recompilation.
new_args = args_maker()
skip_retracing_test = False
for old, new in zip(nest.flatten(args), nest.flatten(new_args)):
if nje.most_precise_int_dtype(old) != nje.most_precise_int_dtype(new):
# If the old and new arguments result in different dtypes (because
# they fall into different value ranges), tf-numpy will retrace, so we
# skip the no-retrace test.
skip_retracing_test = True
if not skip_retracing_test:
python_should_be_executing = True
new_python_ans = fun(*new_args)
python_should_be_executing = False
compiled_ans = cfun(*new_args)
self.assertAllClose(new_python_ans, compiled_ans, check_dtypes, atol,
rtol)
check_compile()
if check_experimental_compile:
check_compile(experimental_compile=True)
if check_xla_forced_compile:
check_compile(xla_forced_compile=True)
if check_eval_on_shapes:
# Check that nje.eval_on_shapes can get complete output shapes given
# complete input shapes.
cfun = nje.eval_on_shapes(fun, static_argnums=static_argnums)
compiled_ans = cfun(*args)
flat_python_ans = nest.flatten(python_ans)
flat_compiled_ans = nest.flatten(compiled_ans)
self.assertEqual(len(flat_python_ans), len(flat_compiled_ans))
for a, b in zip(flat_python_ans, flat_compiled_ans):
if hasattr(a, 'shape'):
self.assertEqual(a.shape, b.shape)
if check_dtypes and hasattr(a, 'dtype'):
self.assertEqual(dtypes.as_dtype(a.dtype), b.dtype)
# If some argument doesn't have a `dtype` attr (e.g. a Python scalar), we
# skip incomplete-shape checks, since shape specs need dtype. It's OK to
# skip since the same incomplete-shape checks will run for []-shaped arrays.
if check_incomplete_shape and all(hasattr(x, 'dtype') for x in args):
# Check partial shapes with known ranks.
# Numpy scalars (created by e.g. np.int32(5)) have `dtype` but not
# `shape`.
if all(hasattr(x, 'shape') for x in args):
specs = [
tensor.TensorSpec([None] * len(x.shape), x.dtype) for x in args
]
cfun = nje.jit(
fun, static_argnums=static_argnums, input_signature=specs
)
compiled_ans = cfun(*args)
self.assertAllClose(python_ans, compiled_ans, check_dtypes, atol, rtol)
if check_unknown_rank:
# Check unknown ranks.
specs = [tensor.TensorSpec(None, x.dtype) for x in args]
cfun = nje.jit(
fun, static_argnums=static_argnums, input_signature=specs)
compiled_ans = cfun(*args)
self.assertAllClose(python_ans, compiled_ans, check_dtypes, atol, rtol)
def check_grads(self, f, args, atol=None, rtol=None, delta=None):
"""Check gradients against finite differences.
Args:
f: function to check at ``f(*args)``.
args: a list or tuple of argument values.
atol: absolute tolerance for gradient equality.
rtol: relative tolerance for gradient equality.
delta: step size used for finite differences.
"""
if delta is None:
# Optimal stepsize for central difference is O(epsilon^{1/3}).
dtype = np_utils.result_type(*args)
epsilon = onp.finfo(dtype).eps
delta = epsilon ** (1.0 / 3.0)
theoretical, numerical = gradient_checker_v2.compute_gradient(
to_tf_fn(f), args, delta=delta)
self.assertAllClose(theoretical, numerical, check_dtypes=False, atol=atol,
rtol=rtol)
@contextmanager
def ignore_warning(**kw):
with warnings.catch_warnings():
warnings.filterwarnings("ignore", **kw)
yield
def disable(_):
def wrapper(self, *args, **kwargs):
self.skipTest('Test is disabled')
return wrapper
| TestCase |
python | h5py__h5py | h5py/tests/test_dataset.py | {
"start": 12576,
"end": 15692
} | class ____(BaseDataset):
"""
Feature: Datasets can be created only if they don't exist in the file
"""
def test_create(self):
""" Create new dataset with no conflicts """
dset = self.f.require_dataset(make_name(), (10, 3), 'f')
self.assertIsInstance(dset, Dataset)
self.assertEqual(dset.shape, (10, 3))
def test_create_existing(self):
""" require_dataset yields existing dataset """
name = make_name()
dset = self.f.require_dataset(name, (10, 3), 'f')
dset[0, 0] = 123
dset2 = self.f.require_dataset(name, (10, 3), 'f')
self.assertEqual(dset, dset2)
def test_create_1D_integer(self):
""" require_dataset with integer shape yields existing dataset"""
name = make_name()
dset = self.f.require_dataset(name, 10, 'f')
dset[0] = 123
dset2 = self.f.require_dataset(name, 10, 'f')
self.assertEqual(dset, dset2)
def test_create_1D_tuple(self):
name = make_name()
dset = self.f.require_dataset(name, (10,), 'f')
dset[0] = 123
dset2 = self.f.require_dataset(name, 10, 'f')
self.assertEqual(dset, dset2)
def test_create_1D_binary(self):
name = make_name()
dset = self.f.require_dataset(name, 10, 'f')
dset[0] = 123
dset2 = self.f.require_dataset(name.encode('utf-8'), (10,), 'f')
self.assertEqual(dset, dset2)
def test_shape_conflict(self):
""" require_dataset with shape conflict yields TypeError """
name = make_name()
self.f.create_dataset(name, (10, 3), 'f')
with self.assertRaises(TypeError):
self.f.require_dataset(name, (10, 4), 'f')
def test_type_conflict(self):
""" require_dataset with object type conflict yields TypeError """
name = make_name()
self.f.create_group(name)
with self.assertRaises(TypeError):
self.f.require_dataset(name, (10, 3), 'f')
def test_dtype_conflict(self):
""" require_dataset with dtype conflict (strict mode) yields TypeError
"""
name = make_name()
dset = self.f.create_dataset(name, (10, 3), 'f')
with self.assertRaises(TypeError):
self.f.require_dataset(name, (10, 3), 'S10')
def test_dtype_exact(self):
""" require_dataset with exactly dtype match """
name = make_name()
dset = self.f.create_dataset(name, (10, 3), 'f')
dset[0, 0] = 123
dset2 = self.f.require_dataset(name, (10, 3), 'f', exact=True)
self.assertEqual(dset, dset2)
def test_dtype_close(self):
""" require_dataset with convertible type succeeds (non-strict mode)
"""
name = make_name()
dset = self.f.create_dataset(name, (10, 3), 'i4')
# Set a value too large for i2 to test for spurious intermediate conversions
dset[0, 0] = 98765
dset2 = self.f.require_dataset(name, (10, 3), 'i2', exact=False)
self.assertEqual(dset, dset2)
self.assertEqual(dset2.dtype, np.dtype('i4'))
| TestCreateRequire |
python | allegroai__clearml | clearml/backend_api/services/v2_23/events.py | {
"start": 57746,
"end": 60556
} | class ____(Request):
"""
Remove old logs from task
:param task: Task ID
:type task: str
:param allow_locked: Allow deleting events even if the task is locked
:type allow_locked: bool
:param threshold_sec: The amount of seconds ago to retain the log records. The
older log records will be deleted. If not passed or 0 then all the log records
for the task will be deleted
:type threshold_sec: int
"""
_service = "events"
_action = "clear_task_log"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"allow_locked": {
"default": False,
"description": "Allow deleting events even if the task is locked",
"type": "boolean",
},
"task": {"description": "Task ID", "type": "string"},
"threshold_sec": {
"description": "The amount of seconds ago to retain the log records. The older log records will be deleted. If not passed or 0 then all the log records for the task will be deleted",
"type": "integer",
},
},
"required": ["task"],
"type": "object",
}
def __init__(
self, task: str, allow_locked: Optional[bool] = False, threshold_sec: Optional[int] = None, **kwargs: Any
) -> None:
super(ClearTaskLogRequest, self).__init__(**kwargs)
self.task = task
self.allow_locked = allow_locked
self.threshold_sec = threshold_sec
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
@schema_property("allow_locked")
def allow_locked(self) -> Optional[bool]:
return self._property_allow_locked
@allow_locked.setter
def allow_locked(self, value: Optional[bool]) -> None:
if value is None:
self._property_allow_locked = None
return
self.assert_isinstance(value, "allow_locked", (bool,))
self._property_allow_locked = value
@schema_property("threshold_sec")
def threshold_sec(self) -> Optional[int]:
return self._property_threshold_sec
@threshold_sec.setter
def threshold_sec(self, value: Optional[int]) -> None:
if value is None:
self._property_threshold_sec = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "threshold_sec", six.integer_types)
self._property_threshold_sec = value
| ClearTaskLogRequest |
python | great-expectations__great_expectations | tests/data_context/abstract_data_context/test_data_docs_config_crud.py | {
"start": 5213,
"end": 6915
} | class ____:
@pytest.mark.unit
def test_delete_data_docs_site(self, ephemeral_context_with_defaults: EphemeralDataContext):
# Check fixture configuration
existing_site_name = "local_site"
assert existing_site_name in ephemeral_context_with_defaults.get_site_names()
ephemeral_context_with_defaults.delete_data_docs_site(existing_site_name)
# Check that the site is no longer present
assert existing_site_name not in ephemeral_context_with_defaults.get_site_names()
@pytest.mark.unit
def test_delete_data_docs_site_persists(
self, ephemeral_context_with_defaults: EphemeralDataContext
):
# Check fixture configuration
existing_site_name = "local_site"
assert existing_site_name in ephemeral_context_with_defaults.get_site_names()
with mock.patch(
"great_expectations.data_context.EphemeralDataContext._save_project_config"
) as mock_save_project_config:
ephemeral_context_with_defaults.delete_data_docs_site(existing_site_name)
mock_save_project_config.assert_called_once()
@pytest.mark.unit
def test_delete_data_docs_site_missing_site_raises_exception(
self,
ephemeral_context_with_defaults: EphemeralDataContext,
):
# Check fixture configuration
assert "missing" not in ephemeral_context_with_defaults.get_site_names()
with pytest.raises(gx_exceptions.InvalidKeyError) as e:
ephemeral_context_with_defaults.delete_data_docs_site("missing")
assert "Data Docs Site `missing` does not already exist in the Data Context." in str(
e.value
)
| TestDeleteDataDocsSite |
python | apache__airflow | providers/standard/src/airflow/providers/standard/decorators/stub.py | {
"start": 1112,
"end": 3020
} | class ____(DecoratedOperator):
custom_operator_name: str = "@task.stub"
def __init__(
self,
*,
python_callable: Callable,
task_id: str,
**kwargs,
) -> None:
super().__init__(
python_callable=python_callable,
task_id=task_id,
**kwargs,
)
# Validate python callable
module = ast.parse(self.get_python_source())
if len(module.body) != 1:
raise RuntimeError("Expected a single statement")
fn = module.body[0]
if not isinstance(fn, ast.FunctionDef):
raise RuntimeError("Expected a single sync function")
for stmt in fn.body:
if isinstance(stmt, ast.Pass):
continue
if isinstance(stmt, ast.Expr):
if isinstance(stmt.value, ast.Constant) and isinstance(stmt.value.value, (str, type(...))):
continue
raise ValueError(
f"Functions passed to @task.stub must be an empty function (`pass`, or `...` only) (got {stmt})"
)
...
def execute(self, context: Context) -> Any:
raise RuntimeError(
"@task.stub should not be executed directly -- we expected this to go to a remote worker. "
"Check your pool and worker configs"
)
def stub(
python_callable: Callable | None = None,
queue: str | None = None,
executor: str | None = None,
**kwargs,
) -> TaskDecorator:
"""
Define a stub task in the DAG.
Stub tasks exist in the Dag graph only, but the execution must happen in an external
environment via the Task Execution Interface.
"""
return task_decorator_factory(
decorated_operator_class=_StubOperator,
python_callable=python_callable,
queue=queue,
executor=executor,
**kwargs,
)
| _StubOperator |
python | great-expectations__great_expectations | great_expectations/render/components.py | {
"start": 31223,
"end": 33374
} | class ____(Schema):
schema = fields.Dict(required=False, allow_none=True)
header = fields.Dict(required=False, allow_none=True)
# for StringValueType
template = fields.String(required=False, allow_none=True)
params = fields.Dict(required=False, allow_none=True)
code_block = fields.Dict(required=False, allow_none=True)
# for TableType
header_row = fields.List(fields.Dict, required=False, allow_none=True)
table = fields.List(fields.List(fields.Dict, required=False, allow_none=True))
# for GraphType
graph = fields.Dict(required=False, allow_none=True)
meta_notes = fields.Dict(required=False, allow_none=True)
@post_load
def create_value_obj(self, data, **kwargs):
return RenderedAtomicValue(**data)
REMOVE_KEYS_IF_NONE: Final[tuple[str, ...]] = (
"header",
"template",
"table",
"params",
"header_row",
"table",
"graph",
"meta_notes",
"code_block",
)
@staticmethod
def remove_null_attrs(data: dict) -> dict:
"""Removes the attributes in RenderedAtomicValueSchema.REMOVE_KEYS_IF_NONE if
their values are None."""
cleaned_serialized_dict = deepcopy(data)
for key in RenderedAtomicValueSchema.REMOVE_KEYS_IF_NONE:
if (
key == "graph"
and key in cleaned_serialized_dict
and cleaned_serialized_dict.get(key, {}).get("graph") is None
):
cleaned_serialized_dict.pop(key)
elif key == "meta_notes" and key in cleaned_serialized_dict:
meta_notes = cleaned_serialized_dict.get(key, {})
if meta_notes is None or not meta_notes.get("content"):
cleaned_serialized_dict.pop(key)
elif key in cleaned_serialized_dict and cleaned_serialized_dict[key] is None:
cleaned_serialized_dict.pop(key)
return cleaned_serialized_dict
@post_dump
def clean_null_attrs(self, data, **kwargs: dict):
return RenderedAtomicValueSchema.remove_null_attrs(data=data)
| RenderedAtomicValueSchema |
python | pandas-dev__pandas | pandas/tests/series/indexing/test_setitem.py | {
"start": 41123,
"end": 41659
} | class ____(SetitemCastingEquivalents):
# https://github.com/pandas-dev/pandas/issues/39584#issuecomment-941212124
@pytest.fixture
def obj(self):
return Series([1, 2, 3], dtype="i4")
@pytest.fixture
def key(self):
return 0
@pytest.fixture
def expected(self, val):
if val % 1 != 0:
dtype = "f8"
else:
dtype = "i8"
return Series([val, 2, 3], dtype=dtype)
@pytest.fixture
def raises(self):
return True
| TestSmallIntegerSetitemUpcast |
python | great-expectations__great_expectations | tests/integration/metrics/query/test_data_source_table.py | {
"start": 2207,
"end": 3685
} | class ____:
@multi_source_batch_setup(
multi_source_test_configs=ALL_COMPARISON_TO_BASE_SOURCES,
base_data=BASE_DATA_FRAME,
comparison_data=COMPARISON_DATA_FRAME,
)
def test_success_sql(self, multi_source_batch: MultiSourceBatch) -> None:
query = f"SELECT * FROM {multi_source_batch.comparison_table_name} WHERE name = 'A';"
batch = multi_source_batch.base_batch
metric = QueryDataSourceTable(
query=query, data_source_name=multi_source_batch.comparison_data_source_name
)
metric_result = batch.compute_metrics(metric)
assert isinstance(metric_result, QueryDataSourceTableResult)
assert len(metric_result.value) == 2
@multi_source_batch_setup(
multi_source_test_configs=ALL_COMPARISON_TO_BASE_SOURCES,
base_data=BASE_DATA_FRAME,
comparison_data=BIG_COMPARISON_DATA_FRAME,
)
def test_result_is_limited_to_200_rows(self, multi_source_batch: MultiSourceBatch) -> None:
query = f"SELECT * FROM {multi_source_batch.comparison_table_name} WHERE id > 0"
batch = multi_source_batch.base_batch
metric = QueryDataSourceTable(
query=query, data_source_name=multi_source_batch.comparison_data_source_name
)
metric_result = batch.compute_metrics(metric)
assert isinstance(metric_result, QueryDataSourceTableResult)
assert len(metric_result.value) == MAX_RESULT_RECORDS
| TestQueryRowCount |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 826821,
"end": 838725
} | class ____(DatumChannelMixin, core.PositionDatumDefBase):
"""
ThetaDatum schema wrapper.
Parameters
----------
bandPosition : float
Relative position on a band of a stacked, binned, time unit, or band scale. For
example, the marks will be positioned at the beginning of the band if set to ``0``,
and at the middle of the band if set to ``0.5``.
datum : str, bool, dict, float, :class:`ExprRef`, :class:`DateTime`, :class:`RepeatRef`, :class:`PrimitiveValue`, None
A constant value in data domain.
scale : dict, :class:`Scale`, None
An object defining properties of the channel's scale, which is the function that
transforms values in the data domain (numbers, dates, strings, etc) to visual values
(pixels, colors, sizes) of the encoding channels.
If ``null``, the scale will be `disabled and the data value will be directly encoded
<https://vega.github.io/vega-lite/docs/scale.html#disable>`__.
**Default value:** If undefined, default `scale properties
<https://vega.github.io/vega-lite/docs/scale.html>`__ are applied.
**See also:** `scale <https://vega.github.io/vega-lite/docs/scale.html>`__
documentation.
stack : bool, :class:`StackOffset`, Literal['zero', 'center', 'normalize'], None
Type of stacking offset if the field should be stacked. ``stack`` is only applicable
for ``x``, ``y``, ``theta``, and ``radius`` channels with continuous domains. For
example, ``stack`` of ``y`` can be used to customize stacking for a vertical bar
chart.
``stack`` can be one of the following values:
* ``"zero"`` or ``true``: stacking with baseline offset at zero value of the scale
(for creating typical stacked `bar
<https://vega.github.io/vega-lite/docs/stack.html#bar>`__ and `area
<https://vega.github.io/vega-lite/docs/stack.html#area>`__ chart).
* ``"normalize"`` - stacking with normalized domain (for creating `normalized
stacked bar and area charts
<https://vega.github.io/vega-lite/docs/stack.html#normalized>`__ and pie charts
`with percentage tooltip
<https://vega.github.io/vega-lite/docs/arc.html#tooltip>`__).
* ``"center"`` - stacking with center baseline (for `streamgraph
<https://vega.github.io/vega-lite/docs/stack.html#streamgraph>`__).
* ``null`` or ``false`` - No-stacking. This will produce layered `bar
<https://vega.github.io/vega-lite/docs/stack.html#layered-bar-chart>`__ and area
chart.
**Default value:** ``zero`` for plots with all of the following conditions are true:
(1) the mark is ``bar``, ``area``, or ``arc``; (2) the stacked measure channel (x or
y) has a linear scale; (3) At least one of non-position channels mapped to an
unaggregated field that is different from x and y. Otherwise, ``null`` by default.
**See also:** `stack <https://vega.github.io/vega-lite/docs/stack.html>`__
documentation.
title : str, :class:`Text`, Sequence[str], None
A title for the field. If ``null``, the title will be removed.
**Default value:** derived from the field's name and transformation function
(``aggregate``, ``bin`` and ``timeUnit``). If the field has an aggregate function,
the function is displayed as part of the title (e.g., ``"Sum of Profit"``). If the
field is binned or has a time unit applied, the applied function is shown in
parentheses (e.g., ``"Profit (binned)"``, ``"Transaction Date (year-month)"``).
Otherwise, the title is simply the field name.
**Notes**:
1) You can customize the default field title format by providing the `fieldTitle
<https://vega.github.io/vega-lite/docs/config.html#top-level-config>`__ property in
the `config <https://vega.github.io/vega-lite/docs/config.html>`__ or `fieldTitle
function via the compile function's options
<https://vega.github.io/vega-lite/usage/compile.html#field-title>`__.
2) If both field definition's ``title`` and axis, header, or legend ``title`` are
defined, axis/header/legend title will be used.
type : :class:`Type`, Literal['quantitative', 'ordinal', 'temporal', 'nominal', 'geojson']
The type of measurement (``"quantitative"``, ``"temporal"``, ``"ordinal"``, or
``"nominal"``) for the encoded field or constant value (``datum``). It can also be a
``"geojson"`` type for encoding `'geoshape'
<https://vega.github.io/vega-lite/docs/geoshape.html>`__.
Vega-Lite automatically infers data types in many cases as discussed below. However,
type is required for a field if: (1) the field is not nominal and the field encoding
has no specified ``aggregate`` (except ``argmin`` and ``argmax``), ``bin``, scale
type, custom ``sort`` order, nor ``timeUnit`` or (2) if you wish to use an ordinal
scale for a field with ``bin`` or ``timeUnit``.
**Default value:**
1) For a data ``field``, ``"nominal"`` is the default data type unless the field
encoding has ``aggregate``, ``channel``, ``bin``, scale type, ``sort``, or
``timeUnit`` that satisfies the following criteria:
* ``"quantitative"`` is the default type if (1) the encoded field contains ``bin``
or ``aggregate`` except ``"argmin"`` and ``"argmax"``, (2) the encoding channel is
``latitude`` or ``longitude`` channel or (3) if the specified scale type is `a
quantitative scale <https://vega.github.io/vega-lite/docs/scale.html#type>`__.
* ``"temporal"`` is the default type if (1) the encoded field contains ``timeUnit``
or (2) the specified scale type is a time or utc scale
* ``"ordinal"`` is the default type if (1) the encoded field contains a `custom sort
order
<https://vega.github.io/vega-lite/docs/sort.html#specifying-custom-sort-order>`__,
(2) the specified scale type is an ordinal/point/band scale, or (3) the encoding
channel is ``order``.
2) For a constant value in data domain (``datum``):
* ``"quantitative"`` if the datum is a number
* ``"nominal"`` if the datum is a string
* ``"temporal"`` if the datum is `a date time object
<https://vega.github.io/vega-lite/docs/datetime.html>`__
**Note:**
* Data ``type`` describes the semantics of the data rather than the primitive data
types (number, string, etc.). The same primitive data type can have different
types of measurement. For example, numeric data can represent quantitative,
ordinal, or nominal data.
* Data values for a temporal field can be either a date-time string (e.g.,
``"2015-03-07 12:32:17"``, ``"17:01"``, ``"2015-03-16"``. ``"2015"``) or a
timestamp number (e.g., ``1552199579097``).
* When using with `bin <https://vega.github.io/vega-lite/docs/bin.html>`__, the
``type`` property can be either ``"quantitative"`` (for using a linear bin scale)
or `"ordinal" (for using an ordinal bin scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `timeUnit
<https://vega.github.io/vega-lite/docs/timeunit.html>`__, the ``type`` property
can be either ``"temporal"`` (default, for using a temporal scale) or `"ordinal"
(for using an ordinal scale)
<https://vega.github.io/vega-lite/docs/type.html#cast-bin>`__.
* When using with `aggregate
<https://vega.github.io/vega-lite/docs/aggregate.html>`__, the ``type`` property
refers to the post-aggregation data type. For example, we can calculate count
``distinct`` of a categorical field ``"cat"`` using ``{"aggregate": "distinct",
"field": "cat"}``. The ``"type"`` of the aggregate output is ``"quantitative"``.
* Secondary channels (e.g., ``x2``, ``y2``, ``xError``, ``yError``) do not have
``type`` as they must have exactly the same type as their primary channels (e.g.,
``x``, ``y``).
**See also:** `type <https://vega.github.io/vega-lite/docs/type.html>`__
documentation.
"""
_class_is_valid_at_instantiation = False
_encoding_name = "theta"
@overload
def bandPosition(self, _: float, /) -> ThetaDatum: ...
@overload
def scale(self, _: Scale | None, /) -> ThetaDatum: ...
@overload
def scale(
self,
*,
align: Optional[float | Parameter | SchemaBase | Map] = Undefined,
base: Optional[float | Parameter | SchemaBase | Map] = Undefined,
bins: Optional[SchemaBase | Sequence[float] | Map] = Undefined,
clamp: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
constant: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domain: Optional[
Parameter
| SchemaBase
| Literal["unaggregated"]
| Sequence[
str | bool | float | Temporal | Parameter | SchemaBase | Map | None
]
| Map
] = Undefined,
domainMax: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainMid: Optional[float | Parameter | SchemaBase | Map] = Undefined,
domainMin: Optional[
float | Temporal | Parameter | SchemaBase | Map
] = Undefined,
domainRaw: Optional[Parameter | SchemaBase | Map] = Undefined,
exponent: Optional[float | Parameter | SchemaBase | Map] = Undefined,
interpolate: Optional[
Parameter | SchemaBase | Map | ScaleInterpolateEnum_T
] = Undefined,
nice: Optional[
bool | float | Parameter | SchemaBase | Map | TimeInterval_T
] = Undefined,
padding: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingInner: Optional[float | Parameter | SchemaBase | Map] = Undefined,
paddingOuter: Optional[float | Parameter | SchemaBase | Map] = Undefined,
range: Optional[
SchemaBase
| Sequence[str | float | Parameter | SchemaBase | Sequence[float] | Map]
| Map
| RangeEnum_T
] = Undefined,
rangeMax: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
rangeMin: Optional[str | float | Parameter | SchemaBase | Map] = Undefined,
reverse: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
round: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
scheme: Optional[Parameter | SchemaBase | Map | ColorScheme_T] = Undefined,
type: Optional[SchemaBase | ScaleType_T] = Undefined,
zero: Optional[bool | Parameter | SchemaBase | Map] = Undefined,
) -> ThetaDatum: ...
@overload
def stack(self, _: bool | StackOffset_T | None, /) -> ThetaDatum: ...
@overload
def title(self, _: str | Sequence[str] | None, /) -> ThetaDatum: ...
@overload
def type(self, _: Type_T, /) -> ThetaDatum: ...
def __init__(
self,
datum,
bandPosition: Optional[float] = Undefined,
scale: Optional[SchemaBase | Map | None] = Undefined,
stack: Optional[bool | SchemaBase | StackOffset_T | None] = Undefined,
title: Optional[str | SchemaBase | Sequence[str] | None] = Undefined,
type: Optional[SchemaBase | Type_T] = Undefined,
**kwds,
):
super().__init__(
datum=datum,
bandPosition=bandPosition,
scale=scale,
stack=stack,
title=title,
type=type,
**kwds,
)
@with_property_setters
| ThetaDatum |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 4863,
"end": 6591
} | class ____(str, BaseEnum):
"""The available generative search modules in Weaviate.
These modules generate text from text-based inputs.
See the [docs](https://weaviate.io/developers/weaviate/modules/reader-generator-modules) for more details.
Attributes:
AWS: Weaviate module backed by AWS Bedrock generative models.
ANTHROPIC: Weaviate module backed by Anthropic generative models.
ANYSCALE: Weaviate module backed by Anyscale generative models.
COHERE: Weaviate module backed by Cohere generative models.
CONTEXTUALAI: Weaviate module backed by ContextualAI generative models.
DATABRICKS: Weaviate module backed by Databricks generative models.
FRIENDLIAI: Weaviate module backed by FriendliAI generative models.
MISTRAL: Weaviate module backed by Mistral generative models.
NVIDIA: Weaviate module backed by NVIDIA generative models.
OLLAMA: Weaviate module backed by generative models deployed on Ollama infrastructure.
OPENAI: Weaviate module backed by OpenAI and Azure-OpenAI generative models.
PALM: Weaviate module backed by PaLM generative models.
"""
AWS = "generative-aws"
ANTHROPIC = "generative-anthropic"
ANYSCALE = "generative-anyscale"
COHERE = "generative-cohere"
CONTEXTUALAI = "generative-contextualai"
DATABRICKS = "generative-databricks"
DUMMY = "generative-dummy"
FRIENDLIAI = "generative-friendliai"
MISTRAL = "generative-mistral"
NVIDIA = "generative-nvidia"
OLLAMA = "generative-ollama"
OPENAI = "generative-openai"
PALM = "generative-palm" # rename to google once all versions support it
XAI = "generative-xai"
| GenerativeSearches |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/input_manager.py | {
"start": 1579,
"end": 6659
} | class ____(ResourceDefinition, IInputManagerDefinition):
"""Definition of an input manager resource.
Input managers load op inputs.
An InputManagerDefinition is a :py:class:`ResourceDefinition` whose resource_fn returns an
:py:class:`InputManager`.
The easiest way to create an InputManagerDefinition is with the
:py:func:`@input_manager <input_manager>` decorator.
"""
def __init__(
self,
resource_fn: ResourceFunction,
config_schema: Optional[CoercableToConfigSchema] = None,
description: Optional[str] = None,
input_config_schema: Optional[CoercableToConfigSchema] = None,
required_resource_keys: Optional[AbstractSet[str]] = None,
version: Optional[str] = None,
):
self._input_config_schema = convert_user_facing_definition_config_schema(
input_config_schema
)
super().__init__(
resource_fn=resource_fn,
config_schema=config_schema,
description=description,
required_resource_keys=required_resource_keys,
version=version,
)
@property
def input_config_schema(self) -> IDefinitionConfigSchema:
return self._input_config_schema
def copy_for_configured(
self,
description: Optional[str],
config_schema: CoercableToConfigSchema,
) -> "InputManagerDefinition":
return InputManagerDefinition(
config_schema=config_schema,
description=description or self.description,
resource_fn=self.resource_fn,
required_resource_keys=self.required_resource_keys,
input_config_schema=self.input_config_schema,
)
@overload
def input_manager(
config_schema: InputLoadFn,
) -> InputManagerDefinition: ...
@overload
def input_manager(
config_schema: Optional[CoercableToConfigSchema] = None,
description: Optional[str] = None,
input_config_schema: Optional[CoercableToConfigSchema] = None,
required_resource_keys: Optional[AbstractSet[str]] = None,
version: Optional[str] = None,
) -> Callable[[InputLoadFn], InputManagerDefinition]: ...
@public
def input_manager(
config_schema: Union[InputLoadFn, Optional[CoercableToConfigSchema]] = None,
description: Optional[str] = None,
input_config_schema: Optional[CoercableToConfigSchema] = None,
required_resource_keys: Optional[AbstractSet[str]] = None,
version: Optional[str] = None,
) -> Union[InputManagerDefinition, Callable[[InputLoadFn], InputManagerDefinition]]:
"""Define an input manager.
Input managers load op inputs, either from upstream outputs or by providing default values.
The decorated function should accept a :py:class:`InputContext` and resource config, and return
a loaded object that will be passed into one of the inputs of an op.
The decorator produces an :py:class:`InputManagerDefinition`.
Args:
config_schema (Optional[ConfigSchema]): The schema for the resource-level config. If not
set, Dagster will accept any config provided.
description (Optional[str]): A human-readable description of the resource.
input_config_schema (Optional[ConfigSchema]): A schema for the input-level config. Each
input that uses this input manager can be configured separately using this config.
If not set, Dagster will accept any config provided.
required_resource_keys (Optional[Set[str]]): Keys for the resources required by the input
manager.
version (Optional[str]): The version of the input manager definition.
**Examples:**
.. code-block:: python
from dagster import input_manager, op, job, In
@input_manager
def csv_loader(_):
return read_csv("some/path")
@op(ins={"input1": In(input_manager_key="csv_loader_key")})
def my_op(_, input1):
do_stuff(input1)
@job(resource_defs={"csv_loader_key": csv_loader})
def my_job():
my_op()
@input_manager(config_schema={"base_dir": str})
def csv_loader(context):
return read_csv(context.resource_config["base_dir"] + "/some/path")
@input_manager(input_config_schema={"path": str})
def csv_loader(context):
return read_csv(context.config["path"])
"""
if _is_input_load_fn(config_schema):
return _InputManagerDecoratorCallable()(config_schema)
def _wrap(load_fn: InputLoadFn) -> InputManagerDefinition:
return _InputManagerDecoratorCallable(
config_schema=cast("CoercableToConfigSchema", config_schema),
description=description,
version=version,
input_config_schema=input_config_schema,
required_resource_keys=required_resource_keys,
)(load_fn)
return _wrap
def _is_input_load_fn(obj: Union[InputLoadFn, CoercableToConfigSchema]) -> TypeGuard[InputLoadFn]:
return callable(obj) and not is_callable_valid_config_arg(obj)
| InputManagerDefinition |
python | ApeWorX__ape | src/ape/plugins/__init__.py | {
"start": 470,
"end": 583
} | class ____(Exception):
pass
# Combine all the plugins together via subclassing (merges `hookspec`s)
| PluginError |
python | huggingface__transformers | src/transformers/generation/watermarking.py | {
"start": 12814,
"end": 15681
} | class ____(nn.Module):
"""Watermarked likelihood model for binary-valued g-values.
This takes in g-values and returns p(g_values|watermarked).
"""
def __init__(self, watermarking_depth: int):
"""Initializes the model parameters."""
super().__init__()
self.watermarking_depth = watermarking_depth
self.beta = torch.nn.Parameter(-2.5 + 0.001 * torch.randn(1, 1, watermarking_depth))
self.delta = torch.nn.Parameter(0.001 * torch.randn(1, 1, self.watermarking_depth, watermarking_depth))
def _compute_latents(self, g_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
"""Computes the unique token probability distribution given g-values.
Args:
g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
PRF values.
Returns:
p_one_unique_token and p_two_unique_tokens, both of shape
[batch_size, seq_len, watermarking_depth]. p_one_unique_token[i,t,l]
gives the probability of there being one unique token in a tournament
match on layer l, on timestep t, for batch item i.
p_one_unique_token[i,t,l] + p_two_unique_token[i,t,l] = 1.
"""
# Tile g-values to produce feature vectors for predicting the latents
# for each layer in the tournament; our model for the latents psi is a
# logistic regression model psi = sigmoid(delta * x + beta).
# [batch_size, seq_len, watermarking_depth, watermarking_depth]
x = torch.repeat_interleave(torch.unsqueeze(g_values, dim=-2), self.watermarking_depth, axis=-2)
# mask all elements above -1 diagonal for autoregressive factorization
x = torch.tril(x, diagonal=-1)
# [batch_size, seq_len, watermarking_depth]
# (i, j, k, l) x (i, j, k, l) -> (i, j, k) einsum equivalent
logits = (self.delta[..., None, :] @ x.type(self.delta.dtype)[..., None]).squeeze() + self.beta
p_two_unique_tokens = torch.sigmoid(logits)
p_one_unique_token = 1 - p_two_unique_tokens
return p_one_unique_token, p_two_unique_tokens
def forward(self, g_values: torch.Tensor) -> torch.Tensor:
"""Computes the likelihoods P(g_values|watermarked).
Args:
g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
g-values (values 0 or 1)
Returns:
p(g_values|watermarked) of shape [batch_size, seq_len, watermarking_depth].
"""
p_one_unique_token, p_two_unique_tokens = self._compute_latents(g_values)
# P(g_tl | watermarked) is equal to
# 0.5 * [ (g_tl+0.5) * p_two_unique_tokens + p_one_unique_token].
return 0.5 * ((g_values + 0.5) * p_two_unique_tokens + p_one_unique_token)
| BayesianDetectorWatermarkedLikelihood |
python | ray-project__ray | python/ray/air/tests/test_air_usage.py | {
"start": 2941,
"end": 6123
} | class ____(Callback):
pass
_TEST_CALLBACKS = [
wandb.WandbLoggerCallback,
mlflow.MLflowLoggerCallback,
comet.CometLoggerCallback,
_CustomLoggerCallback,
_CustomLoggerCallback,
_CustomCallback,
]
def test_tag_setup_wandb(mock_record):
from ray.air.integrations.wandb import _setup_wandb
with patch.dict(os.environ, {wandb.WANDB_MODE_ENV_VAR: "disabled"}):
_setup_wandb(trial_id="a", trial_name="b", config={}, _wandb=MagicMock())
assert mock_record[TagKey.AIR_SETUP_WANDB_INTEGRATION_USED] == "1"
def test_tag_setup_mlflow(mock_record, monkeypatch):
from ray.air.integrations.mlflow import setup_mlflow
monkeypatch.setattr(ray.air.integrations.mlflow, "_MLflowLoggerUtil", MagicMock())
setup_mlflow()
assert mock_record[TagKey.AIR_SETUP_MLFLOW_INTEGRATION_USED] == "1"
@pytest.mark.parametrize(
"callback_classes_expected",
[
(None, None),
([], None),
([lambda: None], None),
(
DEFAULT_CALLBACK_CLASSES,
{cls.__name__: 1 for cls in DEFAULT_CALLBACK_CLASSES},
),
(
_TEST_CALLBACKS,
{
"WandbLoggerCallback": 1,
"MLflowLoggerCallback": 1,
"CometLoggerCallback": 1,
"CustomLoggerCallback": 2,
"CustomCallback": 1,
},
),
],
)
def test_tag_callbacks(mock_record, callback_classes_expected):
callback_classes, expected = callback_classes_expected
callbacks = (
[callback_cls() for callback_cls in callback_classes]
if callback_classes
else None
)
air_usage.tag_callbacks(callbacks)
callback_usage_str = mock_record.pop(TagKey.AIR_CALLBACKS, None)
callback_counts = json.loads(callback_usage_str) if callback_usage_str else None
assert callback_counts == expected
def test_tag_env_vars(ray_start_4_cpus, mock_record, tuner):
"""Test that env vars are recorded properly, and arbitrary user environment
variables are ignored."""
env_vars_to_record = {
"TUNE_GLOBAL_CHECKPOINT_S": "20",
"TUNE_MAX_PENDING_TRIALS_PG": "1",
}
untracked_env_vars = {"RANDOM_USER_ENV_VAR": "asdf"}
with patch.dict(os.environ, {**env_vars_to_record, **untracked_env_vars}):
tuner.fit()
recorded_env_vars = json.loads(mock_record[TagKey.AIR_ENV_VARS])
assert sorted(env_vars_to_record) == sorted(recorded_env_vars)
@pytest.mark.parametrize("entrypoint", list(AirEntrypoint))
def test_tag_air_entrypoint(ray_start_4_cpus, mock_record, entrypoint, tuner, trainer):
if entrypoint == AirEntrypoint.TUNE_RUN:
tune.run(train_fn)
elif entrypoint == AirEntrypoint.TUNE_RUN_EXPERIMENTS:
experiment_spec = Experiment("experiment", train_fn)
tune.run_experiments(experiments=experiment_spec)
elif entrypoint == AirEntrypoint.TUNER:
tuner.fit()
elif entrypoint == AirEntrypoint.TRAINER:
trainer.fit()
assert mock_record[TagKey.AIR_ENTRYPOINT] == entrypoint.value
if __name__ == "__main__":
import sys
sys.exit(pytest.main(["-v", "-x", __file__]))
| _CustomCallback |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 38531,
"end": 38798
} | class ____:
def __str__(self) -> str:
return ".cast_symbool_to_symint_guardless()"
def get(self, b: bool) -> IntLikeType:
"""Get the int value from bool"""
return cast_symbool_to_symint_guardless(b)
@dataclass(frozen=True)
| ConvertIntKey |
python | dagster-io__dagster | python_modules/libraries/dagster-cloud-cli/dagster_cloud_cli/gql.py | {
"start": 1532,
"end": 3672
} | class ____:
def __init__(
self,
name: str,
python_file: Optional[str] = None,
package_name: Optional[str] = None,
image: Optional[str] = None,
module_name: Optional[str] = None,
working_directory: Optional[str] = None,
executable_path: Optional[str] = None,
attribute: Optional[str] = None,
commit_hash: Optional[str] = None,
url: Optional[str] = None,
):
self.name = name
if len([val for val in [python_file, package_name, module_name] if val]) != 1:
raise Exception(
"Must specify exactly one of --python-file or --package-name or --module-name."
)
self.python_file = python_file
self.package_name = package_name
self.image = image
self.module_name = module_name
self.working_directory = working_directory
self.executable_path = executable_path
self.attribute = attribute
self.commit_hash = commit_hash
self.url = url
def get_location_input(self):
location_input = {"name": self.name}
if self.python_file:
location_input["pythonFile"] = self.python_file
if self.package_name:
location_input["packageName"] = self.package_name
if self.image:
location_input["image"] = self.image
if self.module_name:
location_input["moduleName"] = self.module_name
if self.working_directory:
location_input["workingDirectory"] = self.working_directory
if self.executable_path:
location_input["executablePath"] = self.executable_path
if self.attribute:
location_input["attribute"] = self.attribute
if self.commit_hash:
location_input["commitHash"] = self.commit_hash
if self.url:
location_input["url"] = self.url
return location_input
AGENT_STATUS_QUERY = """
query CliAgentStatus {
agents {
status
errors {
error {
message
}
}
}
}
"""
| CliInputCodeLocation |
python | jmcnamara__XlsxWriter | xlsxwriter/test/worksheet/test_prepare_formula.py | {
"start": 301,
"end": 10929
} | class ____(unittest.TestCase):
"""
Test the _prepare_formula Worksheet method for different formula types.
"""
def test_prepare_formula(self):
self.fh = StringIO()
self.worksheet = Worksheet()
self.worksheet._set_filehandle(self.fh)
self.worksheet.use_future_functions = True
testcases = [
["=foo()", "foo()"],
["{foo()}", "foo()"],
["{=foo()}", "foo()"],
# Dynamic functions.
["SEQUENCE(10)", "_xlfn.SEQUENCE(10)"],
["UNIQUES(A1:A10)", "UNIQUES(A1:A10)"],
["UUNIQUE(A1:A10)", "UUNIQUE(A1:A10)"],
["SINGLE(A1:A3)", "_xlfn.SINGLE(A1:A3)"],
["UNIQUE(A1:A10)", "_xlfn.UNIQUE(A1:A10)"],
["_xlfn.SEQUENCE(10)", "_xlfn.SEQUENCE(10)"],
["SORT(A1:A10)", "_xlfn._xlws.SORT(A1:A10)"],
["RANDARRAY(10,1)", "_xlfn.RANDARRAY(10,1)"],
["ANCHORARRAY(C1)", "_xlfn.ANCHORARRAY(C1)"],
["SORTBY(A1:A10,B1)", "_xlfn.SORTBY(A1:A10,B1)"],
["FILTER(A1:A10,1)", "_xlfn._xlws.FILTER(A1:A10,1)"],
["XMATCH(B1:B2,A1:A10)", "_xlfn.XMATCH(B1:B2,A1:A10)"],
["COUNTA(ANCHORARRAY(C1))", "COUNTA(_xlfn.ANCHORARRAY(C1))"],
["SEQUENCE(10)*SEQUENCE(10)", "_xlfn.SEQUENCE(10)*_xlfn.SEQUENCE(10)"],
[
'XLOOKUP("India",A22:A23,B22:B23)',
'_xlfn.XLOOKUP("India",A22:A23,B22:B23)',
],
[
"XLOOKUP(B1,A1:A10,ANCHORARRAY(D1))",
"_xlfn.XLOOKUP(B1,A1:A10,_xlfn.ANCHORARRAY(D1))",
],
[
"LAMBDA(_xlpm.number, _xlpm.number + 1)(1)",
"_xlfn.LAMBDA(_xlpm.number, _xlpm.number + 1)(1)",
],
# Newer dynamic functions (some duplicates with above).
["BYCOL(E1:G2)", "_xlfn.BYCOL(E1:G2)"],
["BYROW(E1:G2)", "_xlfn.BYROW(E1:G2)"],
["CHOOSECOLS(E1:G2,1)", "_xlfn.CHOOSECOLS(E1:G2,1)"],
["CHOOSEROWS(E1:G2,1)", "_xlfn.CHOOSEROWS(E1:G2,1)"],
["DROP(E1:G2,1)", "_xlfn.DROP(E1:G2,1)"],
["EXPAND(E1:G2,2)", "_xlfn.EXPAND(E1:G2,2)"],
["FILTER(E1:G2,H1:H2)", "_xlfn._xlws.FILTER(E1:G2,H1:H2)"],
["HSTACK(E1:G2)", "_xlfn.HSTACK(E1:G2)"],
[
"LAMBDA(_xlpm.number, _xlpm.number + 1)",
"_xlfn.LAMBDA(_xlpm.number, _xlpm.number + 1)",
],
[
"MAKEARRAY(1,1,LAMBDA(_xlpm.row,_xlpm.col,TRUE)",
"_xlfn.MAKEARRAY(1,1,_xlfn.LAMBDA(_xlpm.row,_xlpm.col,TRUE)",
],
["MAP(E1:G2,LAMBDA()", "_xlfn.MAP(E1:G2,_xlfn.LAMBDA()"],
["RANDARRAY(1)", "_xlfn.RANDARRAY(1)"],
[
'REDUCE("1,2,3",E1:G2,LAMBDA()',
'_xlfn.REDUCE("1,2,3",E1:G2,_xlfn.LAMBDA()',
],
['SCAN("1,2,3",E1:G2,LAMBDA()', '_xlfn.SCAN("1,2,3",E1:G2,_xlfn.LAMBDA()'],
["SEQUENCE(E1:E2)", "_xlfn.SEQUENCE(E1:E2)"],
["SORT(F1)", "_xlfn._xlws.SORT(F1)"],
["SORTBY(E1:G1,E2:G2)", "_xlfn.SORTBY(E1:G1,E2:G2)"],
["SWITCH(WEEKDAY(E1)", "_xlfn.SWITCH(WEEKDAY(E1)"],
["TAKE(E1:G2,1)", "_xlfn.TAKE(E1:G2,1)"],
['TEXTSPLIT("foo bar", " ")', '_xlfn.TEXTSPLIT("foo bar", " ")'],
["TOCOL(E1:G1)", "_xlfn.TOCOL(E1:G1)"],
["TOROW(E1:E2)", "_xlfn.TOROW(E1:E2)"],
["UNIQUE(E1:G1)", "_xlfn.UNIQUE(E1:G1)"],
["VSTACK(E1:G2)", "_xlfn.VSTACK(E1:G2)"],
["WRAPCOLS(E1:F1,2)", "_xlfn.WRAPCOLS(E1:F1,2)"],
["WRAPROWS(E1:F1,2)", "_xlfn.WRAPROWS(E1:F1,2)"],
["XLOOKUP(M34,I35:I42,J35:K42)", "_xlfn.XLOOKUP(M34,I35:I42,J35:K42)"],
# Future functions.
["COT()", "_xlfn.COT()"],
["CSC()", "_xlfn.CSC()"],
["IFS()", "_xlfn.IFS()"],
["LET()", "_xlfn.LET()"],
["PHI()", "_xlfn.PHI()"],
["RRI()", "_xlfn.RRI()"],
["SEC()", "_xlfn.SEC()"],
["XOR()", "_xlfn.XOR()"],
["ACOT()", "_xlfn.ACOT()"],
["BASE()", "_xlfn.BASE()"],
["COTH()", "_xlfn.COTH()"],
["CSCH()", "_xlfn.CSCH()"],
["DAYS()", "_xlfn.DAYS()"],
["IFNA()", "_xlfn.IFNA()"],
["SECH()", "_xlfn.SECH()"],
["ACOTH()", "_xlfn.ACOTH()"],
["BITOR()", "_xlfn.BITOR()"],
["F.INV()", "_xlfn.F.INV()"],
["GAMMA()", "_xlfn.GAMMA()"],
["GAUSS()", "_xlfn.GAUSS()"],
["IMCOT()", "_xlfn.IMCOT()"],
["IMCSC()", "_xlfn.IMCSC()"],
["IMSEC()", "_xlfn.IMSEC()"],
["IMTAN()", "_xlfn.IMTAN()"],
["MUNIT()", "_xlfn.MUNIT()"],
["SHEET()", "_xlfn.SHEET()"],
["T.INV()", "_xlfn.T.INV()"],
["VAR.P()", "_xlfn.VAR.P()"],
["VAR.S()", "_xlfn.VAR.S()"],
["ARABIC()", "_xlfn.ARABIC()"],
["BITAND()", "_xlfn.BITAND()"],
["BITXOR()", "_xlfn.BITXOR()"],
["CONCAT()", "_xlfn.CONCAT()"],
["F.DIST()", "_xlfn.F.DIST()"],
["F.TEST()", "_xlfn.F.TEST()"],
["IMAGE()", "_xlfn.IMAGE()"],
["IMCOSH()", "_xlfn.IMCOSH()"],
["IMCSCH()", "_xlfn.IMCSCH()"],
["IMSECH()", "_xlfn.IMSECH()"],
["IMSINH()", "_xlfn.IMSINH()"],
["MAXIFS()", "_xlfn.MAXIFS()"],
["MINIFS()", "_xlfn.MINIFS()"],
["SHEETS()", "_xlfn.SHEETS()"],
["SKEW.P()", "_xlfn.SKEW.P()"],
["SWITCH()", "_xlfn.SWITCH()"],
["T.DIST()", "_xlfn.T.DIST()"],
["T.TEST()", "_xlfn.T.TEST()"],
["Z.TEST()", "_xlfn.Z.TEST()"],
["XMATCH()", "_xlfn.XMATCH()"],
["COMBINA()", "_xlfn.COMBINA()"],
["DECIMAL()", "_xlfn.DECIMAL()"],
["RANK.EQ()", "_xlfn.RANK.EQ()"],
["STDEV.P()", "_xlfn.STDEV.P()"],
["STDEV.S()", "_xlfn.STDEV.S()"],
["UNICHAR()", "_xlfn.UNICHAR()"],
["UNICODE()", "_xlfn.UNICODE()"],
["BETA.INV()", "_xlfn.BETA.INV()"],
["F.INV.RT()", "_xlfn.F.INV.RT()"],
["ISO.CEILING()", "ISO.CEILING()"],
["NORM.INV()", "_xlfn.NORM.INV()"],
["RANK.AVG()", "_xlfn.RANK.AVG()"],
["T.INV.2T()", "_xlfn.T.INV.2T()"],
["TEXTJOIN()", "_xlfn.TEXTJOIN()"],
["TEXTJOIN()", "_xlfn.TEXTJOIN()"],
["AGGREGATE()", "_xlfn.AGGREGATE()"],
["BETA.DIST()", "_xlfn.BETA.DIST()"],
["BINOM.INV()", "_xlfn.BINOM.INV()"],
["BITLSHIFT()", "_xlfn.BITLSHIFT()"],
["BITRSHIFT()", "_xlfn.BITRSHIFT()"],
["CHISQ.INV()", "_xlfn.CHISQ.INV()"],
["ECMA.CEILING()", "ECMA.CEILING()"],
["F.DIST.RT()", "_xlfn.F.DIST.RT()"],
["FILTERXML()", "_xlfn.FILTERXML()"],
["GAMMA.INV()", "_xlfn.GAMMA.INV()"],
["ISFORMULA()", "_xlfn.ISFORMULA()"],
["MODE.MULT()", "_xlfn.MODE.MULT()"],
["MODE.SNGL()", "_xlfn.MODE.SNGL()"],
["NORM.DIST()", "_xlfn.NORM.DIST()"],
["PDURATION()", "_xlfn.PDURATION()"],
["T.DIST.2T()", "_xlfn.T.DIST.2T()"],
["T.DIST.RT()", "_xlfn.T.DIST.RT()"],
["WORKDAY.INTL()", "WORKDAY.INTL()"],
["ISOMITTED()", "_xlfn.ISOMITTED()"],
["TEXTAFTER()", "_xlfn.TEXTAFTER()"],
["BINOM.DIST()", "_xlfn.BINOM.DIST()"],
["CHISQ.DIST()", "_xlfn.CHISQ.DIST()"],
["CHISQ.TEST()", "_xlfn.CHISQ.TEST()"],
["EXPON.DIST()", "_xlfn.EXPON.DIST()"],
["FLOOR.MATH()", "_xlfn.FLOOR.MATH()"],
["GAMMA.DIST()", "_xlfn.GAMMA.DIST()"],
["ISOWEEKNUM()", "_xlfn.ISOWEEKNUM()"],
["NORM.S.INV()", "_xlfn.NORM.S.INV()"],
["WEBSERVICE()", "_xlfn.WEBSERVICE()"],
["TEXTBEFORE()", "_xlfn.TEXTBEFORE()"],
["ERF.PRECISE()", "_xlfn.ERF.PRECISE()"],
["FORMULATEXT()", "_xlfn.FORMULATEXT()"],
["LOGNORM.INV()", "_xlfn.LOGNORM.INV()"],
["NORM.S.DIST()", "_xlfn.NORM.S.DIST()"],
["NUMBERVALUE()", "_xlfn.NUMBERVALUE()"],
["QUERYSTRING()", "_xlfn.QUERYSTRING()"],
["ARRAYTOTEXT()", "_xlfn.ARRAYTOTEXT()"],
["VALUETOTEXT()", "_xlfn.VALUETOTEXT()"],
["CEILING.MATH()", "_xlfn.CEILING.MATH()"],
["CHISQ.INV.RT()", "_xlfn.CHISQ.INV.RT()"],
["CONFIDENCE.T()", "_xlfn.CONFIDENCE.T()"],
["COVARIANCE.P()", "_xlfn.COVARIANCE.P()"],
["COVARIANCE.S()", "_xlfn.COVARIANCE.S()"],
["ERFC.PRECISE()", "_xlfn.ERFC.PRECISE()"],
["FORECAST.ETS()", "_xlfn.FORECAST.ETS()"],
["HYPGEOM.DIST()", "_xlfn.HYPGEOM.DIST()"],
["LOGNORM.DIST()", "_xlfn.LOGNORM.DIST()"],
["PERMUTATIONA()", "_xlfn.PERMUTATIONA()"],
["POISSON.DIST()", "_xlfn.POISSON.DIST()"],
["QUARTILE.EXC()", "_xlfn.QUARTILE.EXC()"],
["QUARTILE.INC()", "_xlfn.QUARTILE.INC()"],
["WEIBULL.DIST()", "_xlfn.WEIBULL.DIST()"],
["CHISQ.DIST.RT()", "_xlfn.CHISQ.DIST.RT()"],
["FLOOR.PRECISE()", "_xlfn.FLOOR.PRECISE()"],
["NEGBINOM.DIST()", "_xlfn.NEGBINOM.DIST()"],
["NETWORKDAYS.INTL()", "NETWORKDAYS.INTL()"],
["PERCENTILE.EXC()", "_xlfn.PERCENTILE.EXC()"],
["PERCENTILE.INC()", "_xlfn.PERCENTILE.INC()"],
["CEILING.PRECISE()", "_xlfn.CEILING.PRECISE()"],
["CONFIDENCE.NORM()", "_xlfn.CONFIDENCE.NORM()"],
["FORECAST.LINEAR()", "_xlfn.FORECAST.LINEAR()"],
["GAMMALN.PRECISE()", "_xlfn.GAMMALN.PRECISE()"],
["PERCENTRANK.EXC()", "_xlfn.PERCENTRANK.EXC()"],
["PERCENTRANK.INC()", "_xlfn.PERCENTRANK.INC()"],
["BINOM.DIST.RANGE()", "_xlfn.BINOM.DIST.RANGE()"],
["FORECAST.ETS.STAT()", "_xlfn.FORECAST.ETS.STAT()"],
["FORECAST.ETS.CONFINT()", "_xlfn.FORECAST.ETS.CONFINT()"],
["FORECAST.ETS.SEASONALITY()", "_xlfn.FORECAST.ETS.SEASONALITY()"],
["Z.TEST(Z.TEST(Z.TEST()))", "_xlfn.Z.TEST(_xlfn.Z.TEST(_xlfn.Z.TEST()))"],
]
for testcase in testcases:
formula = testcase[0]
exp = testcase[1]
got = self.worksheet._prepare_formula(formula)
self.assertEqual(exp, got)
| TestPrepareFormula |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/operators/databricks_workflow.py | {
"start": 10285,
"end": 15019
} | class ____(TaskGroup):
"""
A task group that takes a list of tasks and creates a databricks workflow.
The DatabricksWorkflowTaskGroup takes a list of tasks and creates a databricks workflow
based on the metadata produced by those tasks. For a task to be eligible for this
TaskGroup, it must contain the ``_convert_to_databricks_workflow_task`` method. If any tasks
do not contain this method then the Taskgroup will raise an error at parse time.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DatabricksWorkflowTaskGroup`
:param databricks_conn_id: The name of the databricks connection to use.
:param existing_clusters: A list of existing clusters to use for this workflow.
:param extra_job_params: A dictionary containing properties which will override the default
Databricks Workflow Job definitions.
:param jar_params: A list of jar parameters to pass to the workflow. These parameters will be passed to all jar
tasks in the workflow.
:param job_clusters: A list of job clusters to use for this workflow.
:param max_concurrent_runs: The maximum number of concurrent runs for this workflow.
:param notebook_packages: A list of dictionary of Python packages to be installed. Packages defined
at the workflow task group level are installed for each of the notebook tasks under it. And
packages defined at the notebook task level are installed specific for the notebook task.
:param notebook_params: A dictionary of notebook parameters to pass to the workflow. These parameters
will be passed to all notebook tasks in the workflow.
:param python_params: A list of python parameters to pass to the workflow. These parameters will be passed to
all python tasks in the workflow.
:param spark_submit_params: A list of spark submit parameters to pass to the workflow. These parameters
will be passed to all spark submit tasks.
"""
is_databricks = True
def __init__(
self,
databricks_conn_id: str,
existing_clusters: list[str] | None = None,
extra_job_params: dict[str, Any] | None = None,
jar_params: list[str] | None = None,
job_clusters: list[dict] | None = None,
max_concurrent_runs: int = 1,
notebook_packages: list[dict[str, Any]] | None = None,
notebook_params: dict | None = None,
python_params: list | None = None,
spark_submit_params: list | None = None,
**kwargs,
):
self.databricks_conn_id = databricks_conn_id
self.existing_clusters = existing_clusters or []
self.extra_job_params = extra_job_params or {}
self.jar_params = jar_params or []
self.job_clusters = job_clusters or []
self.max_concurrent_runs = max_concurrent_runs
self.notebook_packages = notebook_packages or []
self.notebook_params = notebook_params or {}
self.python_params = python_params or []
self.spark_submit_params = spark_submit_params or []
super().__init__(**kwargs)
def __exit__(
self, _type: type[BaseException] | None, _value: BaseException | None, _tb: TracebackType | None
) -> None:
"""Exit the context manager and add tasks to a single ``_CreateDatabricksWorkflowOperator``."""
roots = list(self.get_roots())
tasks = _flatten_node(self)
create_databricks_workflow_task = _CreateDatabricksWorkflowOperator(
dag=self.dag,
task_group=self,
task_id="launch",
databricks_conn_id=self.databricks_conn_id,
existing_clusters=self.existing_clusters,
extra_job_params=self.extra_job_params,
job_clusters=self.job_clusters,
max_concurrent_runs=self.max_concurrent_runs,
notebook_params=self.notebook_params,
)
for task in tasks:
if not (
hasattr(task, "_convert_to_databricks_workflow_task")
and callable(task._convert_to_databricks_workflow_task)
):
raise AirflowException(
f"Task {task.task_id} does not support conversion to databricks workflow task."
)
task.workflow_run_metadata = create_databricks_workflow_task.output
create_databricks_workflow_task.relevant_upstreams.append(task.task_id)
create_databricks_workflow_task.add_task(task.task_id, task)
for root_task in roots:
root_task.set_upstream(create_databricks_workflow_task)
super().__exit__(_type, _value, _tb)
| DatabricksWorkflowTaskGroup |
python | scipy__scipy | scipy/special/tests/test_logsumexp.py | {
"start": 12888,
"end": 16075
} | class ____:
def test_softmax_fixtures(self, xp):
xp_assert_close(softmax(xp.asarray([1000., 0., 0., 0.])),
xp.asarray([1., 0., 0., 0.]), rtol=1e-13)
xp_assert_close(softmax(xp.asarray([1., 1.])),
xp.asarray([.5, .5]), rtol=1e-13)
xp_assert_close(softmax(xp.asarray([0., 1.])),
xp.asarray([1., np.e])/(1 + np.e),
rtol=1e-13)
# Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
# converted to float.
x = xp.arange(4, dtype=xp.float64)
expected = xp.asarray([0.03205860328008499,
0.08714431874203256,
0.23688281808991013,
0.6439142598879722], dtype=xp.float64)
xp_assert_close(softmax(x), expected, rtol=1e-13)
# Translation property. If all the values are changed by the same amount,
# the softmax result does not change.
xp_assert_close(softmax(x + 100), expected, rtol=1e-13)
# When axis=None, softmax operates on the entire array, and preserves
# the shape.
xp_assert_close(softmax(xp.reshape(x, (2, 2))),
xp.reshape(expected, (2, 2)), rtol=1e-13)
def test_softmax_multi_axes(self, xp):
xp_assert_close(softmax(xp.asarray([[1000., 0.], [1000., 0.]]), axis=0),
xp.asarray([[.5, .5], [.5, .5]]), rtol=1e-13)
xp_assert_close(softmax(xp.asarray([[1000., 0.], [1000., 0.]]), axis=1),
xp.asarray([[1., 0.], [1., 0.]]), rtol=1e-13)
# Expected value computed using mpmath (with mpmath.mp.dps = 200) and then
# converted to float.
x = xp.asarray([[-25., 0., 25., 50.],
[ 1., 325., 749., 750.]])
expected = xp.asarray([[2.678636961770877e-33,
1.9287498479371314e-22,
1.3887943864771144e-11,
0.999999999986112],
[0.0,
1.9444526359919372e-185,
0.2689414213699951,
0.7310585786300048]])
xp_assert_close(softmax(x, axis=1), expected, rtol=1e-13)
xp_assert_close(softmax(x.T, axis=0), expected.T, rtol=1e-13)
# 3-d input, with a tuple for the axis.
x3d = xp.reshape(x, (2, 2, 2))
xp_assert_close(softmax(x3d, axis=(1, 2)),
xp.reshape(expected, (2, 2, 2)), rtol=1e-13)
@pytest.mark.xfail_xp_backends("array_api_strict", reason="int->float promotion")
def test_softmax_int_array(self, xp):
xp_assert_close(softmax(xp.asarray([1000, 0, 0, 0])),
xp.asarray([1., 0., 0., 0.]), rtol=1e-13)
def test_softmax_scalar(self):
xp_assert_close(softmax(1000), np.asarray(1.), rtol=1e-13)
def test_softmax_array_like(self):
xp_assert_close(softmax([1000, 0, 0, 0]),
np.asarray([1., 0., 0., 0.]), rtol=1e-13)
@make_xp_test_case(log_softmax)
| TestSoftmax |
python | pydata__xarray | xarray/tests/test_backends.py | {
"start": 296605,
"end": 300527
} | class ____:
@property
def netcdfc_version(self):
return Version(nc4.getlibversion().split()[0].split("-development")[0])
def _create_nczarr(self, filename):
if self.netcdfc_version < Version("4.8.1"):
pytest.skip("requires netcdf-c>=4.8.1")
if platform.system() == "Windows" and self.netcdfc_version == Version("4.8.1"):
# Bug in netcdf-c==4.8.1 (typo: Nan instead of NaN)
# https://github.com/Unidata/netcdf-c/issues/2265
pytest.skip("netcdf-c==4.8.1 has issues on Windows")
ds = create_test_data()
# Drop dim3: netcdf-c does not support dtype='<U1'
# https://github.com/Unidata/netcdf-c/issues/2259
ds = ds.drop_vars("dim3")
# engine="netcdf4" is not required for backwards compatibility
ds.to_netcdf(f"file://{filename}#mode=nczarr")
return ds
def test_open_nczarr(self) -> None:
with create_tmp_file(suffix=".zarr") as tmp:
expected = self._create_nczarr(tmp)
actual = xr.open_zarr(tmp, consolidated=False)
assert_identical(expected, actual)
def test_overwriting_nczarr(self) -> None:
with create_tmp_file(suffix=".zarr") as tmp:
ds = self._create_nczarr(tmp)
expected = ds[["var1"]]
expected.to_zarr(tmp, mode="w")
actual = xr.open_zarr(tmp, consolidated=False)
assert_identical(expected, actual)
@pytest.mark.parametrize("mode", ["a", "r+"])
@pytest.mark.filterwarnings("ignore:.*non-consolidated metadata.*")
def test_raise_writing_to_nczarr(self, mode) -> None:
if self.netcdfc_version > Version("4.8.1"):
pytest.skip("netcdf-c>4.8.1 adds the _ARRAY_DIMENSIONS attribute")
with create_tmp_file(suffix=".zarr") as tmp:
ds = self._create_nczarr(tmp)
with pytest.raises(
KeyError, match="missing the attribute `_ARRAY_DIMENSIONS`,"
):
ds.to_zarr(tmp, mode=mode)
@requires_netCDF4
@requires_dask
@pytest.mark.usefixtures("default_zarr_format")
def test_pickle_open_mfdataset_dataset():
with open_example_mfdataset(["bears.nc"]) as ds:
assert_identical(ds, pickle.loads(pickle.dumps(ds)))
@requires_zarr
@pytest.mark.usefixtures("default_zarr_format")
def test_zarr_closing_internal_zip_store():
store_name = "tmp.zarr.zip"
original_da = DataArray(np.arange(12).reshape((3, 4)))
original_da.to_zarr(store_name, mode="w")
with open_dataarray(store_name, engine="zarr") as loaded_da:
assert_identical(original_da, loaded_da)
@requires_zarr
@pytest.mark.parametrize("create_default_indexes", [True, False])
def test_zarr_create_default_indexes(tmp_path, create_default_indexes) -> None:
store_path = tmp_path / "tmp.zarr"
original_ds = xr.Dataset({"data": ("x", np.arange(3))}, coords={"x": [-1, 0, 1]})
original_ds.to_zarr(store_path, mode="w")
with open_dataset(
store_path, engine="zarr", create_default_indexes=create_default_indexes
) as loaded_ds:
if create_default_indexes:
assert list(loaded_ds.xindexes) == ["x"] and isinstance(
loaded_ds.xindexes["x"], PandasIndex
)
else:
assert len(loaded_ds.xindexes) == 0
@requires_zarr
@pytest.mark.usefixtures("default_zarr_format")
def test_raises_key_error_on_invalid_zarr_store(tmp_path):
root = zarr.open_group(tmp_path / "tmp.zarr")
if Version(zarr.__version__) < Version("3.0.0"):
root.create_dataset("bar", shape=(3, 5), dtype=np.float32)
else:
root.create_array("bar", shape=(3, 5), dtype=np.float32)
with pytest.raises(KeyError, match=r"xarray to determine variable dimensions"):
xr.open_zarr(tmp_path / "tmp.zarr", consolidated=False)
@requires_zarr
@pytest.mark.usefixtures("default_zarr_format")
| TestNCZarr |
python | pennersr__django-allauth | allauth/socialaccount/providers/okta/provider.py | {
"start": 310,
"end": 1356
} | class ____(OAuth2Provider):
id = "okta"
name = "Okta"
account_class = OktaAccount
oauth2_adapter_class = OktaOAuth2Adapter
def get_default_scope(self):
return ["openid", "profile", "email", "offline_access"]
def extract_uid(self, data):
uid_field = self.app.settings.get("uid_field", "sub")
return str(data[uid_field])
def extract_extra_data(self, data):
return data
def extract_email_addresses(self, data):
return [
EmailAddress(
email=data["email"], verified=bool(data["email_verified"]), primary=True
)
]
def extract_common_fields(self, data):
ret = dict(
email=data["email"],
last_name=data["family_name"],
first_name=data["given_name"],
)
preferred_username = data.get("preferred_username")
if preferred_username:
ret["username"] = preferred_username.partition("@")[0]
return ret
provider_classes = [OktaProvider]
| OktaProvider |
python | getsentry__sentry-python | tests/utils/test_transaction.py | {
"start": 103,
"end": 1367
} | class ____:
def myfunc(self):
pass
def myfunc():
pass
@partial
def my_partial():
pass
my_lambda = lambda: None
my_partial_lambda = partial(lambda: None)
def test_transaction_from_function():
x = transaction_from_function
assert x(MyClass) == "tests.utils.test_transaction.MyClass"
assert x(MyClass.myfunc) == "tests.utils.test_transaction.MyClass.myfunc"
assert x(myfunc) == "tests.utils.test_transaction.myfunc"
assert x(None) is None
assert x(42) is None
assert x(lambda: None).endswith("<lambda>")
assert x(my_lambda) == "tests.utils.test_transaction.<lambda>"
assert (
x(my_partial) == "partial(<function tests.utils.test_transaction.my_partial>)"
)
assert (
x(my_partial_lambda)
== "partial(<function tests.utils.test_transaction.<lambda>>)"
)
def test_transaction_from_function_partialmethod():
x = transaction_from_function
class MyPartialClass:
@partialmethod
def my_partial_method(self):
pass
assert (
x(MyPartialClass.my_partial_method)
== "partialmethod(<function tests.utils.test_transaction.test_transaction_from_function_partialmethod.<locals>.MyPartialClass.my_partial_method>)"
)
| MyClass |
python | pytest-dev__pytest | doc/en/example/multipython.py | {
"start": 540,
"end": 1958
} | class ____:
def __init__(self, version, picklefile):
self.pythonpath = shutil.which(version)
if not self.pythonpath:
pytest.skip(f"{version!r} not found")
self.picklefile = picklefile
def dumps(self, obj):
dumpfile = self.picklefile.with_name("dump.py")
dumpfile.write_text(
textwrap.dedent(
rf"""
import pickle
f = open({str(self.picklefile)!r}, 'wb')
s = pickle.dump({obj!r}, f, protocol=2)
f.close()
"""
)
)
subprocess.run((self.pythonpath, str(dumpfile)), check=True)
def load_and_is_true(self, expression):
loadfile = self.picklefile.with_name("load.py")
loadfile.write_text(
textwrap.dedent(
rf"""
import pickle
f = open({str(self.picklefile)!r}, 'rb')
obj = pickle.load(f)
f.close()
res = eval({expression!r})
if not res:
raise SystemExit(1)
"""
)
)
print(loadfile)
subprocess.run((self.pythonpath, str(loadfile)), check=True)
@pytest.mark.parametrize("obj", [42, {}, {1: 3}])
def test_basic_objects(python1, python2, obj):
python1.dumps(obj)
python2.load_and_is_true(f"obj == {obj}")
| Python |
python | PyCQA__pylint | pylint/lint/pylinter.py | {
"start": 8408,
"end": 53204
} | class ____(
_ArgumentsManager,
_MessageStateHandler,
reporters.ReportsHandlerMixIn,
checkers.BaseChecker,
):
"""Lint Python modules using external checkers.
This is the main checker controlling the other ones and the reports
generation. It is itself both a raw checker and an astroid checker in order
to:
* handle message activation / deactivation at the module level
* handle some basic but necessary stats' data (number of classes, methods...)
IDE plugin developers: you may have to call
`astroid.MANAGER.clear_cache()` across runs if you want
to ensure the latest code version is actually checked.
This class needs to support pickling for parallel linting to work. The exception
is reporter member; see check_parallel function for more details.
"""
name = MAIN_CHECKER_NAME
msgs = MSGS
# Will be used like this : datetime.now().strftime(crash_file_path)
crash_file_path: str = "pylint-crash-%Y-%m-%d-%H-%M-%S.txt"
option_groups_descs = {
"Messages control": "Options controlling analysis messages",
"Reports": "Options related to output formatting and reporting",
}
def __init__(
self,
options: Options = (),
reporter: reporters.BaseReporter | reporters.MultiReporter | None = None,
option_groups: tuple[tuple[str, str], ...] = (),
pylintrc: str | None = None,
) -> None:
_ArgumentsManager.__init__(self, prog="pylint")
_MessageStateHandler.__init__(self, self)
if pylintrc is not None:
warnings.warn(
"The pylintrc argument will be removed in pylint 5.0.",
DeprecationWarning,
stacklevel=2,
)
# Some stuff has to be done before initialization of other ancestors...
# messages store / checkers / reporter / astroid manager
# Attributes for reporters
self.reporter: reporters.BaseReporter | reporters.MultiReporter
if reporter:
self.set_reporter(reporter)
else:
self.set_reporter(TextReporter())
self._reporters: dict[str, type[reporters.BaseReporter]] = {}
"""Dictionary of possible but non-initialized reporters."""
# Attributes for checkers and plugins
self._checkers: defaultdict[str, list[checkers.BaseChecker]] = (
collections.defaultdict(list)
)
"""Dictionary of registered and initialized checkers."""
self._dynamic_plugins: dict[str, ModuleType | ModuleNotFoundError | bool] = {}
"""Set of loaded plugin names."""
self._registered_checkers: set[tuple[str, checkers.BaseChecker, int]] = set()
"""Set of tuples with loaded checker name, reference to checker
and checker object id.
"""
self._registered_dynamic_plugin_checkers: set[
tuple[str, checkers.BaseChecker, int]
] = set()
"""Set of tuples with loaded dynamic plugin checker name, reference to
checker and checker object id.
"""
# Attributes related to stats
self.stats = LinterStats()
# Attributes related to (command-line) options and their parsing
self.options: Options = options + _make_linter_options(self)
for opt_group in option_groups:
self.option_groups_descs[opt_group[0]] = opt_group[1]
self._option_groups: tuple[tuple[str, str], ...] = (
*option_groups,
*PyLinter.option_groups_descs.items(),
)
self.fail_on_symbols: list[str] = []
"""List of message symbols on which pylint should fail, set by --fail-on."""
self._error_mode = False
reporters.ReportsHandlerMixIn.__init__(self)
checkers.BaseChecker.__init__(self, self)
# provided reports
self.reports = (
("RP0001", "Messages by category", report_total_messages_stats),
(
"RP0002",
"% errors / warnings by module",
report_messages_by_module_stats,
),
("RP0003", "Messages", report_messages_stats),
)
# Attributes related to registering messages and their handling
self.msgs_store = MessageDefinitionStore(self.config.py_version)
self.msg_status = 0
self._by_id_managed_msgs: list[ManagedMessage] = []
self._freeze_register_msgs = False
# Attributes related to visiting files
self.file_state = FileState("", self.msgs_store, is_base_filestate=True)
self.current_name: str = ""
self.current_file: str | None = None
self._ignore_file = False
self._ignore_paths: list[Pattern[str]] = []
self.verbose = False
self.register_checker(self)
def load_default_plugins(self) -> None:
checkers.initialize(self)
reporters.initialize(self)
def load_plugin_modules(self, modnames: Iterable[str], force: bool = False) -> None:
"""Check a list of pylint plugins modules, load and register them.
If a module cannot be loaded, never try to load it again and instead
store the error message for later use in ``load_plugin_configuration``
below.
If `force` is True (useful when multiprocessing), then the plugin is
reloaded regardless if an entry exists in self._dynamic_plugins.
"""
for modname in modnames:
if modname in self._dynamic_plugins and not force:
continue
try:
module = astroid.modutils.load_module_from_name(modname)
module.register(self)
self._dynamic_plugins[modname] = module
except ModuleNotFoundError as mnf_e:
self._dynamic_plugins[modname] = mnf_e
def load_plugin_configuration(self) -> None:
"""Call the configuration hook for plugins.
This walks through the list of plugins, grabs the "load_configuration"
hook, if exposed, and calls it to allow plugins to configure specific
settings.
The result of attempting to load the plugin of the given name
is stored in the dynamic plugins dictionary in ``load_plugin_modules`` above.
..note::
This function previously always tried to load modules again, which
led to some confusion and silent failure conditions as described
in GitHub issue #7264. Making it use the stored result is more efficient, and
means that we avoid the ``init-hook`` problems from before.
"""
for modname, module_or_error in self._dynamic_plugins.items():
if isinstance(module_or_error, ModuleNotFoundError):
self.add_message(
"bad-plugin-value", args=(modname, module_or_error), line=0
)
elif hasattr(module_or_error, "load_configuration"):
module_or_error.load_configuration(self)
# We re-set all the dictionary values to True here to make sure the dict
# is pickle-able. This is only a problem in multiprocessing/parallel mode.
# (e.g. invoking pylint -j 2)
self._dynamic_plugins = {
modname: not isinstance(val, ModuleNotFoundError)
for modname, val in self._dynamic_plugins.items()
}
def _load_reporters(self, reporter_names: str) -> None:
"""Load the reporters if they are available on _reporters."""
if not self._reporters:
return
sub_reporters = []
output_files = []
with contextlib.ExitStack() as stack:
for reporter_name in reporter_names.split(","):
reporter_name, *reporter_output = reporter_name.split(":", 1)
reporter = self._load_reporter_by_name(reporter_name)
sub_reporters.append(reporter)
if reporter_output:
output_file = stack.enter_context(
open(reporter_output[0], "w", encoding="utf-8")
)
reporter.out = output_file
output_files.append(output_file)
# Extend the lifetime of all opened output files
close_output_files = stack.pop_all().close
if len(sub_reporters) > 1 or output_files:
self.set_reporter(
reporters.MultiReporter(
sub_reporters,
close_output_files,
)
)
else:
self.set_reporter(sub_reporters[0])
def _load_reporter_by_name(self, reporter_name: str) -> reporters.BaseReporter:
name = reporter_name.lower()
if name in self._reporters:
return self._reporters[name]()
try:
reporter_class = _load_reporter_by_class(reporter_name)
except (ImportError, AttributeError, AssertionError) as e:
raise exceptions.InvalidReporterError(name) from e
return reporter_class()
def set_reporter(
self, reporter: reporters.BaseReporter | reporters.MultiReporter
) -> None:
"""Set the reporter used to display messages and reports."""
self.reporter = reporter
reporter.linter = self
def register_reporter(self, reporter_class: type[reporters.BaseReporter]) -> None:
"""Registers a reporter class on the _reporters attribute."""
self._reporters[reporter_class.name] = reporter_class
def report_order(self) -> list[BaseChecker]:
reports = sorted(self._reports, key=lambda x: getattr(x, "name", ""))
try:
# Remove the current reporter and add it
# at the end of the list.
reports.pop(reports.index(self))
except ValueError:
pass
else:
reports.append(self)
return reports
# checkers manipulation methods ############################################
def register_checker(self, checker: checkers.BaseChecker) -> None:
"""This method auto registers the checker."""
self._checkers[checker.name].append(checker)
self._registered_checkers.add((checker.name, checker, id(checker)))
for r_id, r_title, r_cb in checker.reports:
self.register_report(r_id, r_title, r_cb, checker)
if not self._freeze_register_msgs and hasattr(checker, "msgs"):
self.msgs_store.register_messages_from_checker(checker)
for message in checker.messages:
if not message.default_enabled:
self.disable(message.msgid)
# Register the checker, but disable all of its messages.
if not (self._freeze_register_msgs or getattr(checker, "enabled", True)):
self.disable(checker.name)
def _deregister_checkers(
self, checker_collection: Collection[tuple[str, checkers.BaseChecker, int]]
) -> None:
"""De-registered a collection of checkers with its reports.
Leave messages in place as re-registering them is a no-op.
"""
for checker_name, checker, _ in checker_collection:
self._checkers[checker_name].remove(checker)
if checker.reports:
self.deregister_reports(checker)
def enable_fail_on_messages(self) -> None:
"""Enable 'fail on' msgs.
Convert values in config.fail_on (which might be msg category, msg id,
or symbol) to specific msgs, then enable and flag them for later.
"""
fail_on_vals = self.config.fail_on
if not fail_on_vals:
return
fail_on_cats = set()
fail_on_msgs = set()
for val in fail_on_vals:
# If value is a category, add category, else add message
if val in MSG_TYPES:
fail_on_cats.add(val)
else:
fail_on_msgs.add(val)
# For every message in every checker, if cat or msg flagged, enable check
for all_checkers in self._checkers.values():
for checker in all_checkers:
for msg in checker.messages:
if msg.msgid in fail_on_msgs or msg.symbol in fail_on_msgs:
# message id/symbol matched, enable and flag it
self.enable(msg.msgid)
self.fail_on_symbols.append(msg.symbol)
elif msg.msgid[0] in fail_on_cats:
# message starts with a category value, flag (but do not enable) it
self.fail_on_symbols.append(msg.symbol)
def any_fail_on_issues(self) -> bool:
return any(x in self.fail_on_symbols for x in self.stats.by_msg.keys())
def pass_fail_on_config_to_color_reporter(self) -> None:
"""Pass fail_on symbol configuration to colorized text reporter."""
if isinstance(self.reporter, ColorizedTextReporter):
self.reporter.set_fail_on_symbols(self.fail_on_symbols)
elif isinstance(self.reporter, reporters.MultiReporter):
for _reporter in self.reporter._sub_reporters:
if isinstance(self.reporter, ColorizedTextReporter):
self.reporter.set_fail_on_symbols(self.fail_on_symbols)
def disable_reporters(self) -> None:
"""Disable all reporters."""
for _reporters in self._reports.values():
for report_id, _, _ in _reporters:
self.disable_report(report_id)
def _parse_error_mode(self) -> None:
"""Parse the current state of the error mode.
Error mode: enable only errors; no reports, no persistent.
"""
if not self._error_mode:
return
self.disable_noerror_messages()
self.disable("miscellaneous")
self.set_option("reports", False)
self.set_option("persistent", False)
self.set_option("score", False)
# code checking methods ###################################################
def get_checkers(self) -> list[BaseChecker]:
"""Return all available checkers as an ordered list."""
return sorted(c for _checkers in self._checkers.values() for c in _checkers)
def get_checker_names(self) -> list[str]:
"""Get all the checker names that this linter knows about."""
return sorted(
{
checker.name
for checker in self.get_checkers()
if checker.name != MAIN_CHECKER_NAME
}
)
def prepare_checkers(self) -> list[BaseChecker]:
"""Return checkers needed for activated messages and reports."""
if not self.config.reports:
self.disable_reporters()
# get needed checkers
needed_checkers: list[BaseChecker] = [self]
for checker in self.get_checkers()[1:]:
messages = {msg for msg in checker.msgs if self.is_message_enabled(msg)}
if messages or any(self.report_is_enabled(r[0]) for r in checker.reports):
needed_checkers.append(checker)
return needed_checkers
# pylint: disable=unused-argument
@staticmethod
def should_analyze_file(modname: str, path: str, is_argument: bool = False) -> bool:
"""Returns whether a module should be checked.
This implementation returns True for all python source files (.py and .pyi),
indicating that all files should be linted.
Subclasses may override this method to indicate that modules satisfying
certain conditions should not be linted.
:param str modname: The name of the module to be checked.
:param str path: The full path to the source code of the module.
:param bool is_argument: Whether the file is an argument to pylint or not.
Files which respect this property are always
checked, since the user requested it explicitly.
:returns: True if the module should be checked.
"""
if is_argument:
return True
return path.endswith((".py", ".pyi"))
# pylint: enable=unused-argument
def initialize(self) -> None:
"""Initialize linter for linting.
This method is called before any linting is done.
"""
self._ignore_paths = self.config.ignore_paths
# initialize msgs_state now that all messages have been registered into
# the store
for msg in self.msgs_store.messages:
if not msg.may_be_emitted(self.config.py_version):
self._msgs_state[msg.msgid] = False
def _discover_files(self, files_or_modules: Sequence[str]) -> Iterator[str]:
"""Discover python modules and packages in sub-directory.
Returns iterator of paths to discovered modules and packages.
"""
for something in files_or_modules:
if os.path.isdir(something) and not os.path.isfile(
os.path.join(something, "__init__.py")
):
skip_subtrees: list[str] = []
for root, _, files in os.walk(something):
if any(root.startswith(s) for s in skip_subtrees):
# Skip subtree of already discovered package.
continue
if _is_ignored_file(
root,
self.config.ignore,
self.config.ignore_patterns,
self.config.ignore_paths,
):
skip_subtrees.append(root)
continue
if "__init__.py" in files:
skip_subtrees.append(root)
yield root
else:
yield from (
os.path.join(root, file)
for file in files
if file.endswith((".py", ".pyi"))
)
else:
yield something
def check(self, files_or_modules: Sequence[str]) -> None:
"""Main checking entry: check a list of files or modules from their name.
files_or_modules is either a string or list of strings presenting modules to check.
"""
self.initialize()
if self.config.recursive:
files_or_modules = tuple(self._discover_files(files_or_modules))
if self.config.from_stdin:
if len(files_or_modules) != 1:
raise exceptions.InvalidArgsError(
"Missing filename required for --from-stdin"
)
extra_packages_paths = list(
dict.fromkeys(
[
discover_package_path(file_or_module, self.config.source_roots)
for file_or_module in files_or_modules
]
).keys()
)
# TODO: Move the parallel invocation into step 3 of the checking process
if not self.config.from_stdin and self.config.jobs > 1:
original_sys_path = sys.path[:]
check_parallel(
self,
self.config.jobs,
self._iterate_file_descrs(files_or_modules),
extra_packages_paths,
)
sys.path = original_sys_path
return
progress_reporter = ProgressReporter(self.verbose)
# 1) Get all FileItems
with augmented_sys_path(extra_packages_paths):
if self.config.from_stdin:
fileitems = self._get_file_descr_from_stdin(files_or_modules[0])
data: str | None = _read_stdin()
else:
fileitems = self._iterate_file_descrs(files_or_modules)
data = None
# The contextmanager also opens all checkers and sets up the PyLinter class
with augmented_sys_path(extra_packages_paths):
with self._astroid_module_checker() as check_astroid_module:
# 2) Get the AST for each FileItem
ast_per_fileitem = self._get_asts(fileitems, data, progress_reporter)
# 3) Lint each ast
self._lint_files(
ast_per_fileitem, check_astroid_module, progress_reporter
)
def _get_asts(
self,
fileitems: Iterator[FileItem],
data: str | None,
progress_reporter: ProgressReporter,
) -> dict[FileItem, nodes.Module | None]:
"""Get the AST for all given FileItems."""
ast_per_fileitem: dict[FileItem, nodes.Module | None] = {}
progress_reporter.start_get_asts()
for fileitem in fileitems:
progress_reporter.get_ast_for_file(fileitem.filepath)
self.set_current_module(fileitem.name, fileitem.filepath)
try:
ast_per_fileitem[fileitem] = self.get_ast(
fileitem.filepath, fileitem.name, data
)
except astroid.AstroidBuildingError as ex:
template_path = prepare_crash_report(
ex, fileitem.filepath, self.crash_file_path
)
msg = get_fatal_error_message(fileitem.filepath, template_path)
self.add_message(
"astroid-error",
args=(fileitem.filepath, msg),
confidence=HIGH,
)
return ast_per_fileitem
def check_single_file_item(self, file: FileItem) -> None:
"""Check single file item.
The arguments are the same that are documented in _check_files
initialize() should be called before calling this method
"""
with self._astroid_module_checker() as check_astroid_module:
self._check_file(self.get_ast, check_astroid_module, file)
def _lint_files(
self,
ast_mapping: dict[FileItem, nodes.Module | None],
check_astroid_module: Callable[[nodes.Module], bool | None],
progress_reporter: ProgressReporter,
) -> None:
"""Lint all AST modules from a mapping.."""
progress_reporter.start_linting()
for fileitem, module in ast_mapping.items():
progress_reporter.lint_file(fileitem.filepath)
if module is None:
continue
try:
self._lint_file(fileitem, module, check_astroid_module)
self.stats.modules_names.add(fileitem.filepath)
except Exception as ex: # pylint: disable=broad-except
template_path = prepare_crash_report(
ex, fileitem.filepath, self.crash_file_path
)
msg = get_fatal_error_message(fileitem.filepath, template_path)
if isinstance(ex, astroid.AstroidError):
self.add_message(
"astroid-error", args=(fileitem.filepath, msg), confidence=HIGH
)
else:
self.add_message("fatal", args=msg, confidence=HIGH)
def _lint_file(
self,
file: FileItem,
module: nodes.Module,
check_astroid_module: Callable[[nodes.Module], bool | None],
) -> None:
"""Lint a file using the passed utility function check_astroid_module).
:param FileItem file: data about the file
:param nodes.Module module: the ast module to lint
:param Callable check_astroid_module: callable checking an AST taking the following
arguments
- ast: AST of the module
:raises AstroidError: for any failures stemming from astroid
"""
self.set_current_module(file.name, file.filepath)
self._ignore_file = False
self.file_state = FileState(file.modpath, self.msgs_store, module)
# fix the current file (if the source file was not available or
# if it's actually a c extension)
self.current_file = module.file
try:
check_astroid_module(module)
except Exception as e:
raise astroid.AstroidError from e
# warn about spurious inline messages handling
spurious_messages = self.file_state.iter_spurious_suppression_messages(
self.msgs_store
)
for msgid, line, args in spurious_messages:
self.add_message(msgid, line, None, args)
def _check_file(
self,
get_ast: GetAstProtocol,
check_astroid_module: Callable[[nodes.Module], bool | None],
file: FileItem,
) -> None:
"""Check a file using the passed utility functions (get_ast and
check_astroid_module).
:param callable get_ast: callable returning AST from defined file taking the
following arguments
- filepath: path to the file to check
- name: Python module name
:param callable check_astroid_module: callable checking an AST taking the following
arguments
- ast: AST of the module
:param FileItem file: data about the file
:raises AstroidError: for any failures stemming from astroid
"""
self.set_current_module(file.name, file.filepath)
# get the module representation
ast_node = get_ast(file.filepath, file.name)
if ast_node is None:
return
self._ignore_file = False
self.file_state = FileState(file.modpath, self.msgs_store, ast_node)
# fix the current file (if the source file was not available or
# if it's actually a c extension)
self.current_file = ast_node.file
try:
check_astroid_module(ast_node)
except Exception as e: # pragma: no cover
raise astroid.AstroidError from e
# warn about spurious inline messages handling
spurious_messages = self.file_state.iter_spurious_suppression_messages(
self.msgs_store
)
for msgid, line, args in spurious_messages:
self.add_message(msgid, line, None, args)
def _get_file_descr_from_stdin(self, filepath: str) -> Iterator[FileItem]:
"""Return file description (tuple of module name, file path, base name) from
given file path.
This method is used for creating suitable file description for _check_files when the
source is standard input.
"""
if _is_ignored_file(
filepath,
self.config.ignore,
self.config.ignore_patterns,
self.config.ignore_paths,
):
self.stats.skipped += 1
return
try:
# Note that this function does not really perform an
# __import__ but may raise an ImportError exception, which
# we want to catch here.
modname = ".".join(astroid.modutils.modpath_from_file(filepath))
except ImportError:
modname = os.path.splitext(os.path.basename(filepath))[0]
yield FileItem(modname, filepath, filepath)
def _iterate_file_descrs(
self, files_or_modules: Sequence[str]
) -> Iterator[FileItem]:
"""Return generator yielding file descriptions (tuples of module name, file
path, base name).
The returned generator yield one item for each Python module that should be linted.
"""
for descr in self._expand_files(files_or_modules).values():
name, filepath, is_arg = descr["name"], descr["path"], descr["isarg"]
if descr["isignored"]:
self.stats.skipped += 1
elif self.should_analyze_file(name, filepath, is_argument=is_arg):
yield FileItem(name, filepath, descr["basename"])
def _expand_files(
self, files_or_modules: Sequence[str]
) -> dict[str, ModuleDescriptionDict]:
"""Get modules and errors from a list of modules and handle errors."""
result, errors = expand_modules(
files_or_modules,
self.config.source_roots,
self.config.ignore,
self.config.ignore_patterns,
self._ignore_paths,
)
for error in errors:
message = modname = error["mod"]
key = error["key"]
self.set_current_module(modname)
if key == "fatal":
message = str(error["ex"]).replace(os.getcwd() + os.sep, "")
self.add_message(key, args=message)
return result
def set_current_module(self, modname: str, filepath: str | None = None) -> None:
"""Set the name of the currently analyzed module and
init statistics for it.
"""
if not modname and filepath is None:
return
self.reporter.on_set_current_module(modname or "", filepath)
self.current_name = modname
self.current_file = filepath or modname
self.stats.init_single_module(modname or "")
# If there is an actual filepath we might need to update the config attribute
if filepath:
namespace = self._get_namespace_for_file(
Path(filepath), self._directory_namespaces
)
if namespace:
self.config = namespace or self._base_config
def _get_namespace_for_file(
self, filepath: Path, namespaces: DirectoryNamespaceDict
) -> argparse.Namespace | None:
for directory in namespaces:
if Path.is_relative_to(filepath, directory):
namespace = self._get_namespace_for_file(
filepath, namespaces[directory][1]
)
if namespace is None:
return namespaces[directory][0]
return None
@contextlib.contextmanager
def _astroid_module_checker(
self,
) -> Iterator[Callable[[nodes.Module], bool | None]]:
"""Context manager for checking ASTs.
The value in the context is callable accepting AST as its only argument.
"""
walker = ASTWalker(self)
_checkers = self.prepare_checkers()
tokencheckers = [
c for c in _checkers if isinstance(c, checkers.BaseTokenChecker)
]
rawcheckers = [
c for c in _checkers if isinstance(c, checkers.BaseRawFileChecker)
]
for checker in _checkers:
checker.open()
walker.add_checker(checker)
yield functools.partial(
self.check_astroid_module,
walker=walker,
tokencheckers=tokencheckers,
rawcheckers=rawcheckers,
)
# notify global end
self.stats.statement = walker.nbstatements
for checker in reversed(_checkers):
checker.close()
def get_ast(
self, filepath: str, modname: str, data: str | None = None
) -> nodes.Module | None:
"""Return an ast(roid) representation of a module or a string.
:param filepath: path to checked file.
:param str modname: The name of the module to be checked.
:param str data: optional contents of the checked file.
:returns: the AST
:rtype: astroid.nodes.Module
:raises AstroidBuildingError: Whenever we encounter an unexpected exception
"""
try:
if data is None:
return MANAGER.ast_from_file(filepath, modname, source=True)
return astroid.builder.AstroidBuilder(MANAGER).string_build(
data, modname, filepath
)
except astroid.AstroidSyntaxError as ex:
line = getattr(ex.error, "lineno", None)
if line is None:
line = 0
self.add_message(
"syntax-error",
line=line,
col_offset=getattr(ex.error, "offset", None),
args=f"Parsing failed: '{ex.error}'",
confidence=HIGH,
)
except astroid.AstroidBuildingError as ex:
self.add_message("parse-error", args=ex)
except Exception as ex:
traceback.print_exc()
# We raise BuildingError here as this is essentially an astroid issue
# Creating an issue template and adding the 'astroid-error' message is handled
# by caller: _check_files
raise astroid.AstroidBuildingError(
"Building error when trying to create ast representation of module '{modname}'",
modname=modname,
) from ex
return None
def check_astroid_module(
self,
ast_node: nodes.Module,
walker: ASTWalker,
rawcheckers: list[checkers.BaseRawFileChecker],
tokencheckers: list[checkers.BaseTokenChecker],
) -> bool | None:
"""Check a module from its astroid representation.
For return value see _check_astroid_module
"""
before_check_statements = walker.nbstatements
retval = self._check_astroid_module(
ast_node, walker, rawcheckers, tokencheckers
)
self.stats.by_module[self.current_name]["statement"] = (
walker.nbstatements - before_check_statements
)
return retval
def _check_astroid_module(
self,
node: nodes.Module,
walker: ASTWalker,
rawcheckers: list[checkers.BaseRawFileChecker],
tokencheckers: list[checkers.BaseTokenChecker],
) -> bool | None:
"""Check given AST node with given walker and checkers.
:param astroid.nodes.Module node: AST node of the module to check
:param pylint.utils.ast_walker.ASTWalker walker: AST walker
:param list rawcheckers: List of token checkers to use
:param list tokencheckers: List of raw checkers to use
:returns: True if the module was checked, False if ignored,
None if the module contents could not be parsed
"""
try:
tokens = utils.tokenize_module(node)
except tokenize.TokenError as ex:
self.add_message(
"syntax-error",
line=ex.args[1][0],
col_offset=ex.args[1][1],
args=ex.args[0],
confidence=HIGH,
)
return None
if not node.pure_python:
self.add_message("raw-checker-failed", args=node.name)
else:
# assert astroid.file.endswith('.py')
# Parse module/block level option pragma's
self.process_tokens(tokens)
if self._ignore_file:
return False
# run raw and tokens checkers
for raw_checker in rawcheckers:
raw_checker.process_module(node)
for token_checker in tokencheckers:
token_checker.process_tokens(tokens)
# generate events to astroid checkers
walker.walk(node)
return True
def open(self) -> None:
"""Initialize counters."""
MANAGER.always_load_extensions = self.config.unsafe_load_any_extension
MANAGER.max_inferable_values = self.config.limit_inference_results
MANAGER.extension_package_whitelist.update(self.config.extension_pkg_allow_list)
MANAGER.module_denylist.update(self.config.ignored_modules)
MANAGER.prefer_stubs = self.config.prefer_stubs
if self.config.extension_pkg_whitelist:
MANAGER.extension_package_whitelist.update(
self.config.extension_pkg_whitelist
)
self.stats.reset_message_count()
def generate_reports(self, verbose: bool = False) -> int | None:
"""Close the whole package /module, it's time to make reports !
if persistent run, pickle results for later comparison
"""
# Display whatever messages are left on the reporter.
self.reporter.display_messages(report_nodes.Section())
if not self.file_state._is_base_filestate:
# load previous results if any
previous_stats = load_results(self.file_state.base_name)
self.reporter.on_close(self.stats, previous_stats)
if self.config.reports:
sect = self.make_reports(self.stats, previous_stats)
else:
sect = report_nodes.Section()
if self.config.reports:
self.reporter.display_reports(sect)
score_value = self._report_evaluation(verbose)
# save results if persistent run
if self.config.persistent:
save_results(self.stats, self.file_state.base_name)
else:
self.reporter.on_close(self.stats, LinterStats())
score_value = None
return score_value
def _report_evaluation(self, verbose: bool = False) -> int | None:
"""Make the global evaluation report."""
# check with at least a statement (usually 0 when there is a
# syntax error preventing pylint from further processing)
note = None
previous_stats = load_results(self.file_state.base_name)
if self.stats.statement == 0:
return note
# get a global note for the code
evaluation = self.config.evaluation
try:
stats_dict = {
"fatal": self.stats.fatal,
"error": self.stats.error,
"warning": self.stats.warning,
"refactor": self.stats.refactor,
"convention": self.stats.convention,
"statement": self.stats.statement,
"info": self.stats.info,
}
note = eval(evaluation, {}, stats_dict) # pylint: disable=eval-used
except Exception as ex: # pylint: disable=broad-except
msg = f"An exception occurred while rating: {ex}"
else:
self.stats.global_note = note
msg = f"Your code has been rated at {note:.2f}/10"
if previous_stats:
pnote = previous_stats.global_note
if pnote is not None:
msg += f" (previous run: {pnote:.2f}/10, {note - pnote:+.2f})"
if verbose:
checked_files_count = self.stats.node_count["module"]
unchecked_files_count = self.stats.undocumented["module"]
checked_files = ", ".join(self.stats.modules_names)
msg += (
f"\nChecked {checked_files_count} files/modules ({checked_files}),"
f" skipped {unchecked_files_count} files/modules"
)
if self.config.score:
sect = report_nodes.EvaluationSection(msg)
self.reporter.display_reports(sect)
return note
def _add_one_message(
self,
message_definition: MessageDefinition,
line: int | None,
node: nodes.NodeNG | None,
args: Any | None,
confidence: interfaces.Confidence | None,
col_offset: int | None,
end_lineno: int | None,
end_col_offset: int | None,
) -> None:
"""After various checks have passed a single Message is
passed to the reporter and added to stats.
"""
message_definition.check_message_definition(line, node)
# Look up "location" data of node if not yet supplied
if node:
if node.position:
if not line:
line = node.position.lineno
if not col_offset:
col_offset = node.position.col_offset
if not end_lineno:
end_lineno = node.position.end_lineno
if not end_col_offset:
end_col_offset = node.position.end_col_offset
else:
if not line:
line = node.fromlineno
if not col_offset:
col_offset = node.col_offset
if not end_lineno:
end_lineno = node.end_lineno
if not end_col_offset:
end_col_offset = node.end_col_offset
# should this message be displayed
if not self.is_message_enabled(message_definition.msgid, line, confidence):
self.file_state.handle_ignored_message(
self._get_message_state_scope(
message_definition.msgid, line, confidence
),
message_definition.msgid,
line,
)
return
# update stats
msg_cat = MSG_TYPES[message_definition.msgid[0]]
self.msg_status |= MSG_TYPES_STATUS[message_definition.msgid[0]]
self.stats.increase_single_message_count(msg_cat, 1)
self.stats.increase_single_module_message_count(self.current_name, msg_cat, 1)
try:
self.stats.by_msg[message_definition.symbol] += 1
except KeyError:
self.stats.by_msg[message_definition.symbol] = 1
# Interpolate arguments into message string
msg = message_definition.msg
if args is not None:
msg %= args
# get module and object
if node is None:
module, obj = self.current_name, ""
abspath = self.current_file
else:
module, obj = utils.get_module_and_frameid(node)
abspath = node.root().file
if abspath is not None:
path = abspath.replace(self.reporter.path_strip_prefix, "", 1)
else:
path = "configuration"
# add the message
self.reporter.handle_message(
Message(
message_definition.msgid,
message_definition.symbol,
MessageLocationTuple(
abspath or "",
path,
module or "",
obj,
line or 1,
col_offset or 0,
end_lineno,
end_col_offset,
),
msg,
confidence,
)
)
def add_message(
self,
msgid: str,
line: int | None = None,
node: nodes.NodeNG | None = None,
args: Any | None = None,
confidence: interfaces.Confidence | None = None,
col_offset: int | None = None,
end_lineno: int | None = None,
end_col_offset: int | None = None,
) -> None:
"""Adds a message given by ID or name.
If provided, the message string is expanded using args.
AST checkers must provide the node argument (but may optionally
provide line if the line number is different), raw and token checkers
must provide the line argument.
"""
if confidence is None:
confidence = interfaces.UNDEFINED
message_definitions = self.msgs_store.get_message_definitions(msgid)
for message_definition in message_definitions:
self._add_one_message(
message_definition,
line,
node,
args,
confidence,
col_offset,
end_lineno,
end_col_offset,
)
def add_ignored_message(
self,
msgid: str,
line: int,
node: nodes.NodeNG | None = None,
confidence: interfaces.Confidence | None = interfaces.UNDEFINED,
) -> None:
"""Prepares a message to be added to the ignored message storage.
Some checks return early in special cases and never reach add_message(),
even though they would normally issue a message.
This creates false positives for useless-suppression.
This function avoids this by adding those message to the ignored msgs attribute
"""
message_definitions = self.msgs_store.get_message_definitions(msgid)
for message_definition in message_definitions:
message_definition.check_message_definition(line, node)
self.file_state.handle_ignored_message(
self._get_message_state_scope(
message_definition.msgid, line, confidence
),
message_definition.msgid,
line,
)
def _emit_stashed_messages(self) -> None:
for keys, values in self._stashed_messages.items():
modname, symbol = keys
self.linter.set_current_module(modname)
for args in values:
self.add_message(
symbol,
args=args,
line=0,
confidence=HIGH,
)
self._stashed_messages = collections.defaultdict(list)
| PyLinter |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-assemblyai/llama_index/readers/assemblyai/base.py | {
"start": 801,
"end": 3854
} | class ____(BaseReader):
"""
Reader for AssemblyAI audio transcripts.
It uses the AssemblyAI API to transcribe audio files
and loads the transcribed text into one or more Documents,
depending on the specified format.
To use, you should have the ``assemblyai`` python package installed, and the
environment variable ``ASSEMBLYAI_API_KEY`` set with your API key.
Alternatively, the API key can also be passed as an argument.
Audio files can be specified via an URL or a local file path.
"""
def __init__(
self,
file_path: str,
*,
transcript_format: TranscriptFormat = TranscriptFormat.TEXT,
config: Optional[assemblyai.TranscriptionConfig] = None,
api_key: Optional[str] = None,
):
"""
Initializes the AssemblyAI AudioTranscriptReader.
Args:
file_path: An URL or a local file path.
transcript_format: Transcript format to use.
See class ``TranscriptFormat`` for more info.
config: Transcription options and features. If ``None`` is given,
the Transcriber's default configuration will be used.
api_key: AssemblyAI API key.
"""
if api_key is not None:
assemblyai.settings.api_key = api_key
self.file_path = file_path
self.transcript_format = transcript_format
# Instantiating the Transcriber will raise a ValueError if no API key is set.
self.transcriber = assemblyai.Transcriber(config=config)
def load_data(self) -> List[Document]:
"""
Transcribes the audio file and loads the transcript into documents.
It uses the AssemblyAI API to transcribe the audio file and blocks until
the transcription is finished.
"""
transcript = self.transcriber.transcribe(self.file_path)
if transcript.error:
raise ValueError(f"Could not transcribe file: {transcript.error}")
if self.transcript_format == TranscriptFormat.TEXT:
return [Document(text=transcript.text, metadata=transcript.json_response)]
elif self.transcript_format == TranscriptFormat.SENTENCES:
sentences = transcript.get_sentences()
return [
Document(text=s.text, metadata=s.dict(exclude={"text"}))
for s in sentences
]
elif self.transcript_format == TranscriptFormat.PARAGRAPHS:
paragraphs = transcript.get_paragraphs()
return [
Document(text=p.text, metadata=p.dict(exclude={"text"}))
for p in paragraphs
]
elif self.transcript_format == TranscriptFormat.SUBTITLES_SRT:
return [Document(text=transcript.export_subtitles_srt())]
elif self.transcript_format == TranscriptFormat.SUBTITLES_VTT:
return [Document(text=transcript.export_subtitles_vtt())]
else:
raise ValueError("Unknown transcript format.")
| AssemblyAIAudioTranscriptReader |
python | gevent__gevent | src/gevent/libev/watcher.py | {
"start": 6443,
"end": 6492
} | class ____(_base.ForkMixin, watcher):
pass
| fork |
python | EpistasisLab__tpot | tpot/builtin_modules/genetic_encoders.py | {
"start": 2947,
"end": 4239
} | class ____(TransformerMixin, BaseEstimator ):
"""This class contains the function definition for encoding the input features as a Heterozygote Advantage genetic model.
The encoding used is AA(0)->0, Aa(1)->1, aa(2)->0. """
def fit(self, X, y=None):
"""Do nothing and return the estimator unchanged.
Dummy function to fit in with the sklearn API and hence work in pipelines.
Parameters
----------
X : array-like
"""
return self
def transform(self, X, y=None):
"""Transform the data by applying the Heterosis encoding.
Parameters
----------
X : numpy ndarray, {n_samples, n_components}
New data, where n_samples is the number of samples (number of individuals)
and n_components is the number of components (number of features).
y : None
Unused
Returns
-------
X_transformed: numpy ndarray, {n_samples, n_components}
The encoded feature set
"""
X = check_array(X)
map = {0: 0, 1: 1, 2: 0}
mapping_function = np.vectorize(lambda i: map[i] if i in map else i)
X_transformed = mapping_function(X)
return X_transformed
| HeterosisEncoder |
python | keon__algorithms | tests/test_compression.py | {
"start": 227,
"end": 1277
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.file_in_name = "huffman_coding_in.txt"
cls.file_out_bin_name = "huffman_coding_out.bin"
cls.file_out_name = "huffman_coding_out.txt"
def setUp(self):
import random
random.seed(1951)
with open(self.file_in_name, "wb") as file_in:
for i in range(10000):
file_in.write(bytes([random.randrange(0, 256)]))
def test_huffman_coding(self):
HuffmanCoding.encode_file(self.file_in_name, self.file_out_bin_name)
HuffmanCoding.decode_file(self.file_out_bin_name, self.file_out_name)
with open(self.file_in_name, "rb") as file_1, open(self.file_out_name, "rb") as file_2:
content_1 = file_1.read()
content_2 = file_2.read()
self.assertEqual(content_1, content_2)
def tearDown(self):
import os
os.remove(self.file_in_name)
os.remove(self.file_out_bin_name)
os.remove(self.file_out_name)
| TestHuffmanCoding |
python | wandb__wandb | wandb/vendor/pygments/lexers/dsls.py | {
"start": 23482,
"end": 26223
} | class ____(RegexLexer):
"""
Lexer for `crmsh <http://crmsh.github.io/>`_ configuration files
for Pacemaker clusters.
.. versionadded:: 2.1
"""
name = 'Crmsh'
aliases = ['crmsh', 'pcmk']
filenames = ['*.crmsh', '*.pcmk']
mimetypes = []
elem = words((
'node', 'primitive', 'group', 'clone', 'ms', 'location',
'colocation', 'order', 'fencing_topology', 'rsc_ticket',
'rsc_template', 'property', 'rsc_defaults',
'op_defaults', 'acl_target', 'acl_group', 'user', 'role',
'tag'), suffix=r'(?![\w#$-])')
sub = words((
'params', 'meta', 'operations', 'op', 'rule',
'attributes', 'utilization'), suffix=r'(?![\w#$-])')
acl = words(('read', 'write', 'deny'), suffix=r'(?![\w#$-])')
bin_rel = words(('and', 'or'), suffix=r'(?![\w#$-])')
un_ops = words(('defined', 'not_defined'), suffix=r'(?![\w#$-])')
date_exp = words(('in_range', 'date', 'spec', 'in'), suffix=r'(?![\w#$-])')
acl_mod = (r'(?:tag|ref|reference|attribute|type|xpath)')
bin_ops = (r'(?:lt|gt|lte|gte|eq|ne)')
val_qual = (r'(?:string|version|number)')
rsc_role_action = (r'(?:Master|Started|Slave|Stopped|'
r'start|promote|demote|stop)')
tokens = {
'root': [
(r'^#.*\n?', Comment),
# attr=value (nvpair)
(r'([\w#$-]+)(=)("(?:""|[^"])*"|\S+)',
bygroups(Name.Attribute, Punctuation, String)),
# need this construct, otherwise numeric node ids
# are matched as scores
# elem id:
(r'(node)(\s+)([\w#$-]+)(:)',
bygroups(Keyword, Whitespace, Name, Punctuation)),
# scores
(r'([+-]?([0-9]+|inf)):', Number),
# keywords (elements and other)
(elem, Keyword),
(sub, Keyword),
(acl, Keyword),
# binary operators
(r'(?:%s:)?(%s)(?![\w#$-])' % (val_qual, bin_ops), Operator.Word),
# other operators
(bin_rel, Operator.Word),
(un_ops, Operator.Word),
(date_exp, Operator.Word),
# builtin attributes (e.g. #uname)
(r'#[a-z]+(?![\w#$-])', Name.Builtin),
# acl_mod:blah
(r'(%s)(:)("(?:""|[^"])*"|\S+)' % acl_mod,
bygroups(Keyword, Punctuation, Name)),
# rsc_id[:(role|action)]
# NB: this matches all other identifiers
(r'([\w#$-]+)(?:(:)(%s))?(?![\w#$-])' % rsc_role_action,
bygroups(Name, Punctuation, Operator.Word)),
# punctuation
(r'(\\(?=\n)|[[\](){}/:@])', Punctuation),
(r'\s+|\n', Whitespace),
],
}
| CrmshLexer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.