code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def __init__( self, model_name: str = "gpt-4", temperature: float = 0.0, max_tokens: Optional[int] = None, api_key: Optional[str] = None, base_url: Optional[str] = None, **kwargs ): """ Initialize an OpenAIModel instance. Arg...
Initialize an OpenAIModel instance. Args: model_name: The name of the OpenAI model to use. temperature: Controls randomness in outputs. Lower values are more deterministic. max_tokens: Maximum number of tokens to generate. api_key: OpenAI API key...
__init__
python
nikmcfly/ANUS
anus/models/openai_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/openai_model.py
MIT
def generate( self, prompt: str, system_message: Optional[str] = None, temperature: Optional[float] = None, max_tokens: Optional[int] = None, **kwargs ) -> str: """ Generate text based on a prompt using OpenAI. Args: prom...
Generate text based on a prompt using OpenAI. Args: prompt: The text prompt for generation. system_message: Optional system message for the model. temperature: Controls randomness in outputs. Overrides instance value if provided. max_tokens: Maxi...
generate
python
nikmcfly/ANUS
anus/models/openai_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/openai_model.py
MIT
def generate_with_tools( self, prompt: str, tools: List[Dict[str, Any]], system_message: Optional[str] = None, temperature: Optional[float] = None, max_tokens: Optional[int] = None, **kwargs ) -> Dict[str, Any]: """ Generate text with tool ca...
Generate text with tool calling capabilities. Args: prompt: The text prompt for generation. tools: List of tool schemas available for use. system_message: Optional system message for the model. temperature: Controls randomness in outputs. Overrid...
generate_with_tools
python
nikmcfly/ANUS
anus/models/openai_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/openai_model.py
MIT
def extract_json( self, prompt: str, schema: Dict[str, Any], system_message: Optional[str] = None, temperature: Optional[float] = None, max_tokens: Optional[int] = None, **kwargs ) -> Dict[str, Any]: """ Extract structured JSON data based on ...
Extract structured JSON data based on a prompt. Args: prompt: The text prompt for extraction. schema: JSON schema describing the expected structure. system_message: Optional system message for the model. temperature: Controls randomness in output...
extract_json
python
nikmcfly/ANUS
anus/models/openai_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/openai_model.py
MIT
def get_embedding(self, text: str, **kwargs) -> List[float]: """ Generate an embedding vector for the given text. Args: text: The text to embed. **kwargs: Additional OpenAI-specific parameters. Returns: The embedding vector as a l...
Generate an embedding vector for the given text. Args: text: The text to embed. **kwargs: Additional OpenAI-specific parameters. Returns: The embedding vector as a list of floats.
get_embedding
python
nikmcfly/ANUS
anus/models/openai_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/openai_model.py
MIT
def __init__( self, model_name: str, temperature: float = 0.0, max_tokens: Optional[int] = None, **kwargs ): """ Initialize a BaseModel instance. Args: model_name: The name of the model to use. temperature: Controls r...
Initialize a BaseModel instance. Args: model_name: The name of the model to use. temperature: Controls randomness in outputs. Lower values are more deterministic. max_tokens: Maximum number of tokens to generate. **kwargs: Additional model-specif...
__init__
python
nikmcfly/ANUS
anus/models/base/base_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/base/base_model.py
MIT
def generate( self, prompt: str, system_message: Optional[str] = None, temperature: Optional[float] = None, max_tokens: Optional[int] = None, **kwargs ) -> str: """ Generate text based on a prompt. Args: prompt: The text ...
Generate text based on a prompt. Args: prompt: The text prompt for generation. system_message: Optional system message for models that support it. temperature: Controls randomness in outputs. Overrides instance value if provided. max_tokens: Maxi...
generate
python
nikmcfly/ANUS
anus/models/base/base_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/base/base_model.py
MIT
def generate_with_tools( self, prompt: str, tools: List[Dict[str, Any]], system_message: Optional[str] = None, temperature: Optional[float] = None, max_tokens: Optional[int] = None, **kwargs ) -> Dict[str, Any]: """ Generate text with tool ca...
Generate text with tool calling capabilities. Args: prompt: The text prompt for generation. tools: List of tool schemas available for use. system_message: Optional system message for models that support it. temperature: Controls randomness in out...
generate_with_tools
python
nikmcfly/ANUS
anus/models/base/base_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/base/base_model.py
MIT
def extract_json( self, prompt: str, schema: Dict[str, Any], system_message: Optional[str] = None, temperature: Optional[float] = None, max_tokens: Optional[int] = None, **kwargs ) -> Dict[str, Any]: """ Extract structured JSON data based on ...
Extract structured JSON data based on a prompt. Args: prompt: The text prompt for extraction. schema: JSON schema describing the expected structure. system_message: Optional system message for models that support it. temperature: Controls randomn...
extract_json
python
nikmcfly/ANUS
anus/models/base/base_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/base/base_model.py
MIT
def get_model_details(self) -> Dict[str, Any]: """ Get details about the model. Returns: A dictionary containing model information. """ return { "model_name": self.model_name, "temperature": self.temperature, "max_tokens": ...
Get details about the model. Returns: A dictionary containing model information.
get_model_details
python
nikmcfly/ANUS
anus/models/base/base_model.py
https://github.com/nikmcfly/ANUS/blob/master/anus/models/base/base_model.py
MIT
def execute(self, expression: str, **kwargs) -> Union[Dict[str, Any], ToolResult]: """ Execute the calculator tool. Args: expression: The mathematical expression to evaluate. **kwargs: Additional parameters (ignored). Returns: The...
Execute the calculator tool. Args: expression: The mathematical expression to evaluate. **kwargs: Additional parameters (ignored). Returns: The calculation result.
execute
python
nikmcfly/ANUS
anus/tools/calculator.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/calculator.py
MIT
def _eval_expr(self, node: ast.AST) -> float: """ Recursively evaluate an AST expression node. Args: node: The AST node to evaluate. Returns: The evaluated result. Raises: ValueError: If the expression contain...
Recursively evaluate an AST expression node. Args: node: The AST node to evaluate. Returns: The evaluated result. Raises: ValueError: If the expression contains unsupported operations.
_eval_expr
python
nikmcfly/ANUS
anus/tools/calculator.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/calculator.py
MIT
def execute(self, code: str, **kwargs) -> Union[Dict[str, Any], ToolResult]: """ Execute the provided Python code in a restricted environment. Args: code: The Python code to execute. **kwargs: Additional parameters (ignored). Returns: ...
Execute the provided Python code in a restricted environment. Args: code: The Python code to execute. **kwargs: Additional parameters (ignored). Returns: The execution result.
execute
python
nikmcfly/ANUS
anus/tools/code.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/code.py
MIT
def _validate_code(self, code: str) -> None: """ Validate code for security concerns. Args: code: The code to validate. Raises: ValueError: If the code contains forbidden elements. """ # Check for suspicious imports or calls ...
Validate code for security concerns. Args: code: The code to validate. Raises: ValueError: If the code contains forbidden elements.
_validate_code
python
nikmcfly/ANUS
anus/tools/code.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/code.py
MIT
def _create_restricted_env(self) -> Dict[str, Any]: """ Create a restricted execution environment. Returns: A dictionary with allowed modules and builtins. """ # Start with a clean dictionary restricted_env = {} # Add allowed modules ...
Create a restricted execution environment. Returns: A dictionary with allowed modules and builtins.
_create_restricted_env
python
nikmcfly/ANUS
anus/tools/code.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/code.py
MIT
def execute(self, query: str, **kwargs) -> Union[Dict[str, Any], ToolResult]: """ Execute the search tool. Args: query: The search query. **kwargs: Additional parameters (ignored). Returns: The search results. """ ...
Execute the search tool. Args: query: The search query. **kwargs: Additional parameters (ignored). Returns: The search results.
execute
python
nikmcfly/ANUS
anus/tools/search.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/search.py
MIT
def execute(self, text: str, operation: str, **kwargs) -> Union[Dict[str, Any], ToolResult]: """ Execute the text tool. Args: text: The text to process. operation: The operation to perform. **kwargs: Additional parameters (ignored). ...
Execute the text tool. Args: text: The text to process. operation: The operation to perform. **kwargs: Additional parameters (ignored). Returns: The processed text result.
execute
python
nikmcfly/ANUS
anus/tools/text.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/text.py
MIT
def get_schema(self) -> Dict[str, Any]: """ Get the tool's parameter schema. Returns: A dictionary describing the tool's parameters. """ # Base implementation returns a simple schema return { "name": self.name, "description": s...
Get the tool's parameter schema. Returns: A dictionary describing the tool's parameters.
get_schema
python
nikmcfly/ANUS
anus/tools/base/tool.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool.py
MIT
def register_tool(self, tool: BaseTool) -> None: """ Register a tool instance. Args: tool: The tool instance to register. """ self.tools[tool.name] = tool logging.info(f"Registered tool: {tool.name}")
Register a tool instance. Args: tool: The tool instance to register.
register_tool
python
nikmcfly/ANUS
anus/tools/base/tool_collection.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool_collection.py
MIT
def register_tool_class(self, tool_class: Type[BaseTool]) -> None: """ Register a tool class for later instantiation. Args: tool_class: The tool class to register. """ name = getattr(tool_class, "name", tool_class.__name__.lower()) self.tool_classes[n...
Register a tool class for later instantiation. Args: tool_class: The tool class to register.
register_tool_class
python
nikmcfly/ANUS
anus/tools/base/tool_collection.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool_collection.py
MIT
def get_tool(self, name: str) -> Optional[BaseTool]: """ Get a tool by name. Args: name: The name of the tool. Returns: The tool instance, or None if not found. """ # Check if the tool is already instantiated if name i...
Get a tool by name. Args: name: The name of the tool. Returns: The tool instance, or None if not found.
get_tool
python
nikmcfly/ANUS
anus/tools/base/tool_collection.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool_collection.py
MIT
def execute_tool(self, name: str, **kwargs) -> Any: """ Execute a tool by name. Args: name: The name of the tool to execute. **kwargs: Input parameters for the tool. Returns: The result of the tool execution, or an error message. ...
Execute a tool by name. Args: name: The name of the tool to execute. **kwargs: Input parameters for the tool. Returns: The result of the tool execution, or an error message.
execute_tool
python
nikmcfly/ANUS
anus/tools/base/tool_collection.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool_collection.py
MIT
def discover_tools(self, package_name: str = "anus.tools") -> int: """ Discover tools in the specified package. Args: package_name: The package to search for tools. Returns: The number of tools discovered. """ count = 0 ...
Discover tools in the specified package. Args: package_name: The package to search for tools. Returns: The number of tools discovered.
discover_tools
python
nikmcfly/ANUS
anus/tools/base/tool_collection.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool_collection.py
MIT
def __init__( self, tool_name: str, status: str = "success", result: Any = None, error: Optional[str] = None, metadata: Optional[Dict[str, Any]] = None ): """ Initialize a ToolResult instance. Args: tool_name: Name of the ...
Initialize a ToolResult instance. Args: tool_name: Name of the tool that produced the result. status: Status of the tool execution ("success" or "error"). result: The actual result data. error: Error message if status is "error". meta...
__init__
python
nikmcfly/ANUS
anus/tools/base/tool_result.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool_result.py
MIT
def to_dict(self) -> Dict[str, Any]: """ Convert the result to a dictionary. Returns: A dictionary representation of the result. """ result_dict = { "tool_name": self.tool_name, "status": self.status, "timestamp": self.time...
Convert the result to a dictionary. Returns: A dictionary representation of the result.
to_dict
python
nikmcfly/ANUS
anus/tools/base/tool_result.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/base/tool_result.py
MIT
def validate_input(self, expression: str = None, **kwargs) -> bool: """ Validate the input parameters. Args: expression: The mathematical expression to validate. **kwargs: Additional parameters (ignored). Returns: True if the inpu...
Validate the input parameters. Args: expression: The mathematical expression to validate. **kwargs: Additional parameters (ignored). Returns: True if the input is valid, False otherwise.
validate_input
python
nikmcfly/ANUS
anus/tools/utility/calculator.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/utility/calculator.py
MIT
def _validate_expression(self, expression: str) -> None: """ Validate that an expression is safe to evaluate. Args: expression: The expression to validate. Raises: ValueError: If the expression contains unsafe elements. """ # ...
Validate that an expression is safe to evaluate. Args: expression: The expression to validate. Raises: ValueError: If the expression contains unsafe elements.
_validate_expression
python
nikmcfly/ANUS
anus/tools/utility/calculator.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/utility/calculator.py
MIT
def _safe_math_context(self) -> Dict[str, Any]: """ Create a safe context for math operations. Returns: A dictionary with allowed mathematical functions. """ import math # Allow only safe math functions return { "abs": abs...
Create a safe context for math operations. Returns: A dictionary with allowed mathematical functions.
_safe_math_context
python
nikmcfly/ANUS
anus/tools/utility/calculator.py
https://github.com/nikmcfly/ANUS/blob/master/anus/tools/utility/calculator.py
MIT
def __init__(self, verbose: bool = False, config_path: str = "config.yaml"): """ Initialize a CLI instance. Args: verbose: Whether to enable verbose output. config_path: Path to the configuration file. """ super().__init__() self.verbose =...
Initialize a CLI instance. Args: verbose: Whether to enable verbose output. config_path: Path to the configuration file.
__init__
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def display_welcome(self) -> None: """ Display a welcome message. Includes a random ANUS joke to brighten your day. """ term_width = shutil.get_terminal_size().columns print("=" * term_width) print("ANUS - Autonomous Networked Utility System".cen...
Display a welcome message. Includes a random ANUS joke to brighten your day.
display_welcome
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def start_interactive_mode(self, orchestrator: Optional[AgentOrchestrator] = None) -> None: """ Start the interactive command-line interface. Args: orchestrator: Optional orchestrator instance. If not provided, one will be created. """ if orchestrator: ...
Start the interactive command-line interface. Args: orchestrator: Optional orchestrator instance. If not provided, one will be created.
start_interactive_mode
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def display_result(self, result: Dict[str, Any]) -> None: """ Display the result of a task execution. Args: result: The task execution result. """ self.current_result = result term_width = shutil.get_terminal_size().columns p...
Display the result of a task execution. Args: result: The task execution result.
display_result
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def do_task(self, arg: str) -> None: """ Execute a task. Usage: task [mode] <task description> Args: arg: Task description and optional mode. """ # Make sure orchestrator is initialized if not self.orchestrator: self.orche...
Execute a task. Usage: task [mode] <task description> Args: arg: Task description and optional mode.
do_task
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def do_joke(self, arg: str) -> None: """ Display a random ANUS joke. Usage: joke """ joke = random.choice(self._anus_jokes) term_width = shutil.get_terminal_size().columns print() print("=" * term_width) print("ANUS WISDO...
Display a random ANUS joke. Usage: joke
do_joke
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def emptyline(self) -> None: """ Handle empty lines in the CLI. """ # 1 in 10 chance to show a joke on empty line if random.random() < 0.1: print(f"ANUS is waiting... {random.choice(self._anus_jokes)}")
Handle empty lines in the CLI.
emptyline
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def _pretty_print(self, data: Any) -> None: """ Pretty print data. Args: data: Data to print. """ if isinstance(data, (dict, list)): try: print(json.dumps(data, indent=2)) except Exception: print(data) ...
Pretty print data. Args: data: Data to print.
_pretty_print
python
nikmcfly/ANUS
anus/ui/cli.py
https://github.com/nikmcfly/ANUS/blob/master/anus/ui/cli.py
MIT
def get_executor(self, step_type: Optional[str] = None) -> BaseAgent: """ Get an appropriate executor agent for the current step. Can be extended to select agents based on step type/requirements. """ # If step type is provided and matches an agent key, use that agent if s...
Get an appropriate executor agent for the current step. Can be extended to select agents based on step type/requirements.
get_executor
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
async def execute(self, input_text: str) -> str: """Execute the planning flow with agents.""" try: if not self.primary_agent: raise ValueError("No primary agent available") # Create initial plan if input provided if input_text: await s...
Execute the planning flow with agents.
execute
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
async def _create_initial_plan(self, request: str) -> None: """Create an initial plan based on the request using the flow's LLM and PlanningTool.""" logger.info(f"Creating initial plan with ID: {self.active_plan_id}") # Create a system message for plan creation system_message = Message....
Create an initial plan based on the request using the flow's LLM and PlanningTool.
_create_initial_plan
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
async def _get_current_step_info(self) -> tuple[Optional[int], Optional[dict]]: """ Parse the current plan to identify the first non-completed step's index and info. Returns (None, None) if no active step is found. """ if ( not self.active_plan_id or self....
Parse the current plan to identify the first non-completed step's index and info. Returns (None, None) if no active step is found.
_get_current_step_info
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
async def _execute_step(self, executor: BaseAgent, step_info: dict) -> str: """Execute the current step with the specified agent using agent.run().""" # Prepare context for the agent with current plan status plan_status = await self._get_plan_text() step_text = step_info.get("text", f"St...
Execute the current step with the specified agent using agent.run().
_execute_step
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
async def _mark_step_completed(self) -> None: """Mark the current step as completed.""" if self.current_step_index is None: return try: # Mark the step as completed await self.planning_tool.execute( command="mark_step", plan_id...
Mark the current step as completed.
_mark_step_completed
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
async def _get_plan_text(self) -> str: """Get the current plan as formatted text.""" try: result = await self.planning_tool.execute( command="get", plan_id=self.active_plan_id ) return result.output if hasattr(result, "output") else str(result) ...
Get the current plan as formatted text.
_get_plan_text
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
async def _finalize_plan(self) -> str: """Finalize the plan and provide a summary using the flow's LLM directly.""" plan_text = await self._get_plan_text() # Create a summary using the flow's LLM directly try: system_message = Message.system_message( "You are...
Finalize the plan and provide a summary using the flow's LLM directly.
_finalize_plan
python
nikmcfly/ANUS
instructions/Planning Script.py
https://github.com/nikmcfly/ANUS/blob/master/instructions/Planning Script.py
MIT
def depth2pts_outside(ray_o, ray_d, depth): ''' ray_o, ray_d: [..., 3] depth: [...]; inverse of distance to sphere origin ''' # note: d1 becomes negative if this mid point is behind camera d1 = -torch.sum(ray_d * ray_o, dim=-1) / torch.sum(ray_d * ray_d, dim=-1) p_mid = ray_o + d1.unsqueeze(...
ray_o, ray_d: [..., 3] depth: [...]; inverse of distance to sphere origin
depth2pts_outside
python
Kai-46/nerfplusplus
ddp_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/ddp_model.py
BSD-2-Clause
def intersect_sphere(ray_o, ray_d): ''' ray_o, ray_d: [..., 3] compute the depth of the intersection point between this ray and unit sphere ''' # note: d1 becomes negative if this mid point is behind camera d1 = -torch.sum(ray_d * ray_o, dim=-1) / torch.sum(ray_d * ray_d, dim=-1) p = ray_o +...
ray_o, ray_d: [..., 3] compute the depth of the intersection point between this ray and unit sphere
intersect_sphere
python
Kai-46/nerfplusplus
ddp_train_nerf.py
https://github.com/Kai-46/nerfplusplus/blob/master/ddp_train_nerf.py
BSD-2-Clause
def sample_pdf(bins, weights, N_samples, det=False): ''' :param bins: tensor of shape [..., M+1], M is the number of bins :param weights: tensor of shape [..., M] :param N_samples: number of samples along each ray :param det: if True, will perform deterministic sampling :return: [..., N_samples]...
:param bins: tensor of shape [..., M+1], M is the number of bins :param weights: tensor of shape [..., M] :param N_samples: number of samples along each ray :param det: if True, will perform deterministic sampling :return: [..., N_samples]
sample_pdf
python
Kai-46/nerfplusplus
ddp_train_nerf.py
https://github.com/Kai-46/nerfplusplus/blob/master/ddp_train_nerf.py
BSD-2-Clause
def __init__(self, input_dim, max_freq_log2, N_freqs, log_sampling=True, include_input=True, periodic_fns=(torch.sin, torch.cos)): ''' :param input_dim: dimension of input to be embedded :param max_freq_log2: log2 of max freq; min freq is 1 by defaul...
:param input_dim: dimension of input to be embedded :param max_freq_log2: log2 of max freq; min freq is 1 by default :param N_freqs: number of frequency bands :param log_sampling: if True, frequency bands are linerly sampled in log-space :param include_input: if True, raw input ...
__init__
python
Kai-46/nerfplusplus
nerf_network.py
https://github.com/Kai-46/nerfplusplus/blob/master/nerf_network.py
BSD-2-Clause
def forward(self, input): ''' :param input: tensor of shape [..., self.input_dim] :return: tensor of shape [..., self.out_dim] ''' assert (input.shape[-1] == self.input_dim) out = [] if self.include_input: out.append(input) for i in range(len...
:param input: tensor of shape [..., self.input_dim] :return: tensor of shape [..., self.out_dim]
forward
python
Kai-46/nerfplusplus
nerf_network.py
https://github.com/Kai-46/nerfplusplus/blob/master/nerf_network.py
BSD-2-Clause
def __init__(self, D=8, W=256, input_ch=3, input_ch_viewdirs=3, skips=[4], use_viewdirs=False): ''' :param D: network depth :param W: network width :param input_ch: input channels for encodings of (x, y, z) :param input_ch_viewdirs: input channels for encodings o...
:param D: network depth :param W: network width :param input_ch: input channels for encodings of (x, y, z) :param input_ch_viewdirs: input channels for encodings of view directions :param skips: skip connection in network :param use_viewdirs: if True, will use the view d...
__init__
python
Kai-46/nerfplusplus
nerf_network.py
https://github.com/Kai-46/nerfplusplus/blob/master/nerf_network.py
BSD-2-Clause
def get_rays_single_image(H, W, intrinsics, c2w): ''' :param H: image height :param W: image width :param intrinsics: 4 by 4 intrinsic matrix :param c2w: 4 by 4 camera to world extrinsic matrix :return: ''' u, v = np.meshgrid(np.arange(W), np.arange(H)) u = u.reshape(-1).astype(dtyp...
:param H: image height :param W: image width :param intrinsics: 4 by 4 intrinsic matrix :param c2w: 4 by 4 camera to world extrinsic matrix :return:
get_rays_single_image
python
Kai-46/nerfplusplus
nerf_sample_ray_split.py
https://github.com/Kai-46/nerfplusplus/blob/master/nerf_sample_ray_split.py
BSD-2-Clause
def random_sample(self, N_rand, center_crop=False): ''' :param N_rand: number of rays to be casted :return: ''' if center_crop: half_H = self.H // 2 half_W = self.W // 2 quad_H = half_H // 2 quad_W = half_W // 2 # pixel...
:param N_rand: number of rays to be casted :return:
random_sample
python
Kai-46/nerfplusplus
nerf_sample_ray_split.py
https://github.com/Kai-46/nerfplusplus/blob/master/nerf_sample_ray_split.py
BSD-2-Clause
def read_next_bytes(fid, num_bytes, format_char_sequence, endian_character="<"): """Read and unpack the next bytes from a binary file. :param fid: :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc. :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}. :pa...
Read and unpack the next bytes from a binary file. :param fid: :param num_bytes: Sum of combination of {2, 4, 8}, e.g. 2, 6, 16, 30, etc. :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}. :param endian_character: Any of {@, =, <, >, !} :return: Tuple of read and unpacked val...
read_next_bytes
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def write_next_bytes(fid, data, format_char_sequence, endian_character="<"): """pack and write to a binary file. :param fid: :param data: data to send, if multiple elements are sent at the same time, they should be encapsuled either in a list or a tuple :param format_char_sequence: List of {c, e, f,...
pack and write to a binary file. :param fid: :param data: data to send, if multiple elements are sent at the same time, they should be encapsuled either in a list or a tuple :param format_char_sequence: List of {c, e, f, d, h, H, i, I, l, L, q, Q}. should be the same length as the data list or tuple...
write_next_bytes
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def read_cameras_text(path): """ see: src/base/reconstruction.cc void Reconstruction::WriteCamerasText(const std::string& path) void Reconstruction::ReadCamerasText(const std::string& path) """ cameras = {} with open(path, "r") as fid: while True: line = fid.readl...
see: src/base/reconstruction.cc void Reconstruction::WriteCamerasText(const std::string& path) void Reconstruction::ReadCamerasText(const std::string& path)
read_cameras_text
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def read_cameras_binary(path_to_model_file): """ see: src/base/reconstruction.cc void Reconstruction::WriteCamerasBinary(const std::string& path) void Reconstruction::ReadCamerasBinary(const std::string& path) """ cameras = {} with open(path_to_model_file, "rb") as fid: num_c...
see: src/base/reconstruction.cc void Reconstruction::WriteCamerasBinary(const std::string& path) void Reconstruction::ReadCamerasBinary(const std::string& path)
read_cameras_binary
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def read_images_text(path): """ see: src/base/reconstruction.cc void Reconstruction::ReadImagesText(const std::string& path) void Reconstruction::WriteImagesText(const std::string& path) """ images = {} with open(path, "r") as fid: while True: line = fid.readline(...
see: src/base/reconstruction.cc void Reconstruction::ReadImagesText(const std::string& path) void Reconstruction::WriteImagesText(const std::string& path)
read_images_text
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def read_images_binary(path_to_model_file): """ see: src/base/reconstruction.cc void Reconstruction::ReadImagesBinary(const std::string& path) void Reconstruction::WriteImagesBinary(const std::string& path) """ images = {} with open(path_to_model_file, "rb") as fid: num_reg_i...
see: src/base/reconstruction.cc void Reconstruction::ReadImagesBinary(const std::string& path) void Reconstruction::WriteImagesBinary(const std::string& path)
read_images_binary
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def read_points3D_text(path): """ see: src/base/reconstruction.cc void Reconstruction::ReadPoints3DText(const std::string& path) void Reconstruction::WritePoints3DText(const std::string& path) """ points3D = {} with open(path, "r") as fid: while True: line = fid.r...
see: src/base/reconstruction.cc void Reconstruction::ReadPoints3DText(const std::string& path) void Reconstruction::WritePoints3DText(const std::string& path)
read_points3D_text
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def read_points3d_binary(path_to_model_file): """ see: src/base/reconstruction.cc void Reconstruction::ReadPoints3DBinary(const std::string& path) void Reconstruction::WritePoints3DBinary(const std::string& path) """ points3D = {} with open(path_to_model_file, "rb") as fid: n...
see: src/base/reconstruction.cc void Reconstruction::ReadPoints3DBinary(const std::string& path) void Reconstruction::WritePoints3DBinary(const std::string& path)
read_points3d_binary
python
Kai-46/nerfplusplus
colmap_runner/read_write_model.py
https://github.com/Kai-46/nerfplusplus/blob/master/colmap_runner/read_write_model.py
BSD-2-Clause
def enumerate_env() -> Optional[str]: """ Return a path for the ${pwd}/.env file. If pwd does not exist, return None. """ try: cwd = os.getcwd() except FileNotFoundError: return None path = os.path.join(cwd, '.env') return path
Return a path for the ${pwd}/.env file. If pwd does not exist, return None.
enumerate_env
python
theskumar/python-dotenv
src/dotenv/cli.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/cli.py
BSD-3-Clause
def stream_file(path: os.PathLike) -> Iterator[IO[str]]: """ Open a file and yield the corresponding (decoded) stream. Exits with error code 2 if the file cannot be opened. """ try: with open(path) as stream: yield stream except OSError as exc: print(f"Error opening...
Open a file and yield the corresponding (decoded) stream. Exits with error code 2 if the file cannot be opened.
stream_file
python
theskumar/python-dotenv
src/dotenv/cli.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/cli.py
BSD-3-Clause
def list(ctx: click.Context, format: bool) -> None: """Display all the stored key/value.""" file = ctx.obj['FILE'] with stream_file(file) as stream: values = dotenv_values(stream=stream) if format == 'json': click.echo(json.dumps(values, indent=2, sort_keys=True)) else: pre...
Display all the stored key/value.
list
python
theskumar/python-dotenv
src/dotenv/cli.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/cli.py
BSD-3-Clause
def get(ctx: click.Context, key: Any) -> None: """Retrieve the value for the given key.""" file = ctx.obj['FILE'] with stream_file(file) as stream: values = dotenv_values(stream=stream) stored_value = values.get(key) if stored_value: click.echo(stored_value) else: exit(...
Retrieve the value for the given key.
get
python
theskumar/python-dotenv
src/dotenv/cli.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/cli.py
BSD-3-Clause
def run(ctx: click.Context, override: bool, commandline: List[str]) -> None: """Run command with environment variables present.""" file = ctx.obj['FILE'] if not os.path.isfile(file): raise click.BadParameter( f'Invalid value for \'-f\' "{file}" does not exist.', ctx=ctx ...
Run command with environment variables present.
run
python
theskumar/python-dotenv
src/dotenv/cli.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/cli.py
BSD-3-Clause
def run_command(command: List[str], env: Dict[str, str]) -> None: """Replace the current process with the specified command. Replaces the current process with the specified command and the variables from `env` added in the current environment variables. Parameters ---------- command: List[str]...
Replace the current process with the specified command. Replaces the current process with the specified command and the variables from `env` added in the current environment variables. Parameters ---------- command: List[str] The command and it's parameters env: Dict The additi...
run_command
python
theskumar/python-dotenv
src/dotenv/cli.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/cli.py
BSD-3-Clause
def set_as_environment_variables(self) -> bool: """ Load the current dotenv as system environment variable. """ if not self.dict(): return False for k, v in self.dict().items(): if k in os.environ and not self.override: continue ...
Load the current dotenv as system environment variable.
set_as_environment_variables
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def get_key( dotenv_path: StrPath, key_to_get: str, encoding: Optional[str] = "utf-8", ) -> Optional[str]: """ Get the value of a given key from the given .env. Returns `None` if the key isn't found or doesn't have a value. """ return DotEnv(dotenv_path, verbose=True, encoding=encoding)...
Get the value of a given key from the given .env. Returns `None` if the key isn't found or doesn't have a value.
get_key
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def set_key( dotenv_path: StrPath, key_to_set: str, value_to_set: str, quote_mode: str = "always", export: bool = False, encoding: Optional[str] = "utf-8", ) -> Tuple[Optional[bool], str, str]: """ Adds or Updates a key/value to the given .env If the .env path given doesn't exist, f...
Adds or Updates a key/value to the given .env If the .env path given doesn't exist, fails instead of risking creating an orphan .env somewhere in the filesystem
set_key
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def unset_key( dotenv_path: StrPath, key_to_unset: str, quote_mode: str = "always", encoding: Optional[str] = "utf-8", ) -> Tuple[Optional[bool], str]: """ Removes a given key from the given `.env` file. If the .env path given doesn't exist, fails. If the given key doesn't exist in the ...
Removes a given key from the given `.env` file. If the .env path given doesn't exist, fails. If the given key doesn't exist in the .env, fails.
unset_key
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def _walk_to_root(path: str) -> Iterator[str]: """ Yield directories starting from the given directory up to the root """ if not os.path.exists(path): raise IOError("Starting path not found") if os.path.isfile(path): path = os.path.dirname(path) last_dir = None current_dir ...
Yield directories starting from the given directory up to the root
_walk_to_root
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def find_dotenv( filename: str = ".env", raise_error_if_not_found: bool = False, usecwd: bool = False, ) -> str: """ Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise """ def _is_interactive(): """Decide whe...
Search in increasingly higher folders for the given file Returns path to the file if found, or an empty string otherwise
find_dotenv
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def _is_interactive(): """Decide whether this is running in a REPL or IPython notebook""" if hasattr(sys, "ps1") or hasattr(sys, "ps2"): return True try: main = __import__("__main__", None, None, fromlist=["__file__"]) except ModuleNotFoundError: retur...
Decide whether this is running in a REPL or IPython notebook
_is_interactive
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def load_dotenv( dotenv_path: Optional[StrPath] = None, stream: Optional[IO[str]] = None, verbose: bool = False, override: bool = False, interpolate: bool = True, encoding: Optional[str] = "utf-8", ) -> bool: """Parse a .env file and then load all the variables found as environment variables...
Parse a .env file and then load all the variables found as environment variables. Parameters: dotenv_path: Absolute or relative path to .env file. stream: Text stream (such as `io.StringIO`) with .env content, used if `dotenv_path` is `None`. verbose: Whether to output a warning...
load_dotenv
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def dotenv_values( dotenv_path: Optional[StrPath] = None, stream: Optional[IO[str]] = None, verbose: bool = False, interpolate: bool = True, encoding: Optional[str] = "utf-8", ) -> Dict[str, Optional[str]]: """ Parse a .env file and return its content as a dict. The returned dict will h...
Parse a .env file and return its content as a dict. The returned dict will have `None` values for keys without values in the .env file. For example, `foo=bar` results in `{"foo": "bar"}` whereas `foo` alone results in `{"foo": None}` Parameters: dotenv_path: Absolute or relative path to t...
dotenv_values
python
theskumar/python-dotenv
src/dotenv/main.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/main.py
BSD-3-Clause
def get_cli_string( path: Optional[str] = None, action: Optional[str] = None, key: Optional[str] = None, value: Optional[str] = None, quote: Optional[str] = None, ): """Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to ...
Returns a string suitable for running as a shell script. Useful for converting a arguments passed to a fabric task to be passed to a `local` or `run` command.
get_cli_string
python
theskumar/python-dotenv
src/dotenv/__init__.py
https://github.com/theskumar/python-dotenv/blob/master/src/dotenv/__init__.py
BSD-3-Clause
def _create_dotenv_file(self, tmp_path): """Helper to create a test .env file.""" dotenv_path = tmp_path / ".env" dotenv_path.write_text("TEST=value") return dotenv_path
Helper to create a test .env file.
_create_dotenv_file
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def _setup_subdir_and_chdir(self, tmp_path, monkeypatch): """Helper to create subdirectory and change to it.""" test_dir = tmp_path / "subdir" test_dir.mkdir() monkeypatch.chdir(test_dir) return test_dir
Helper to create subdirectory and change to it.
_setup_subdir_and_chdir
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def _remove_ps_attributes(self, monkeypatch): """Helper to remove ps1/ps2 attributes if they exist.""" if hasattr(sys, "ps1"): monkeypatch.delattr(sys, "ps1") if hasattr(sys, "ps2"): monkeypatch.delattr(sys, "ps2")
Helper to remove ps1/ps2 attributes if they exist.
_remove_ps_attributes
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def _mock_main_import_error(self, monkeypatch): """Helper to mock __main__ module import that raises ModuleNotFoundError.""" original_import = builtins.__import__ def mock_import(name, *args, **kwargs): if name == "__main__": raise ModuleNotFoundError("No module name...
Helper to mock __main__ module import that raises ModuleNotFoundError.
_mock_main_import_error
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_with_ps1(self, tmp_path, monkeypatch): """Test that _is_interactive returns True when sys.ps1 exists.""" dotenv_path = self._create_dotenv_file(tmp_path) # Mock sys.ps1 to simulate interactive shell monkeypatch.setattr(sys, "ps1", ">>> ", raising=False) ...
Test that _is_interactive returns True when sys.ps1 exists.
test_is_interactive_with_ps1
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_with_ps2(self, tmp_path, monkeypatch): """Test that _is_interactive returns True when sys.ps2 exists.""" dotenv_path = self._create_dotenv_file(tmp_path) # Mock sys.ps2 to simulate multi-line interactive input monkeypatch.setattr(sys, "ps2", "... ", raising=False...
Test that _is_interactive returns True when sys.ps2 exists.
test_is_interactive_with_ps2
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_main_module_not_found(self, tmp_path, monkeypatch): """Test that _is_interactive returns False when __main__ module import fails.""" self._remove_ps_attributes(monkeypatch) self._mock_main_import_error(monkeypatch) # Change to directory and test monkeypat...
Test that _is_interactive returns False when __main__ module import fails.
test_is_interactive_main_module_not_found
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_main_without_file(self, tmp_path, monkeypatch): """Test that _is_interactive returns True when __main__ has no __file__ attribute.""" self._remove_ps_attributes(monkeypatch) dotenv_path = self._create_dotenv_file(tmp_path) # Mock __main__ module without __file__ ...
Test that _is_interactive returns True when __main__ has no __file__ attribute.
test_is_interactive_main_without_file
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_main_with_file(self, tmp_path, monkeypatch): """Test that _is_interactive returns False when __main__ has __file__ attribute.""" self._remove_ps_attributes(monkeypatch) # Mock __main__ module with __file__ attribute mock_main = mock.MagicMock() mock_main....
Test that _is_interactive returns False when __main__ has __file__ attribute.
test_is_interactive_main_with_file
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_precedence_ps1_over_main(self, tmp_path, monkeypatch): """Test that ps1/ps2 attributes take precedence over __main__ module check.""" dotenv_path = self._create_dotenv_file(tmp_path) # Set ps1 attribute monkeypatch.setattr(sys, "ps1", ">>> ", raising=False) ...
Test that ps1/ps2 attributes take precedence over __main__ module check.
test_is_interactive_precedence_ps1_over_main
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_ps1_and_ps2_both_exist(self, tmp_path, monkeypatch): """Test that _is_interactive returns True when both ps1 and ps2 exist.""" dotenv_path = self._create_dotenv_file(tmp_path) # Set both ps1 and ps2 attributes monkeypatch.setattr(sys, "ps1", ">>> ", raising=False...
Test that _is_interactive returns True when both ps1 and ps2 exist.
test_is_interactive_ps1_and_ps2_both_exist
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_main_module_with_file_attribute_none(self, tmp_path, monkeypatch): """Test _is_interactive when __main__ has __file__ attribute set to None.""" self._remove_ps_attributes(monkeypatch) # Mock __main__ module with __file__ = None mock_main = mock.MagicMock() ...
Test _is_interactive when __main__ has __file__ attribute set to None.
test_is_interactive_main_module_with_file_attribute_none
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_no_ps_attributes_and_normal_execution(self, tmp_path, monkeypatch): """Test normal script execution scenario where _is_interactive should return False.""" self._remove_ps_attributes(monkeypatch) # Don't mock anything - let it use the real __main__ module # which ...
Test normal script execution scenario where _is_interactive should return False.
test_is_interactive_no_ps_attributes_and_normal_execution
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def test_is_interactive_with_usecwd_override(self, tmp_path, monkeypatch): """Test that usecwd=True overrides _is_interactive behavior.""" self._remove_ps_attributes(monkeypatch) dotenv_path = self._create_dotenv_file(tmp_path) # Mock __main__ module with __file__ attribute (non-interac...
Test that usecwd=True overrides _is_interactive behavior.
test_is_interactive_with_usecwd_override
python
theskumar/python-dotenv
tests/test_is_interactive.py
https://github.com/theskumar/python-dotenv/blob/master/tests/test_is_interactive.py
BSD-3-Clause
def resetall( self, *, return_value: bool = False, side_effect: bool = False ) -> None: """ Call reset_mock() on all patchers started by this fixture. :param bool return_value: Reset the return_value of mocks. :param bool side_effect: Reset the side_effect of mocks. ...
Call reset_mock() on all patchers started by this fixture. :param bool return_value: Reset the return_value of mocks. :param bool side_effect: Reset the side_effect of mocks.
resetall
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def spy(self, obj: object, name: str) -> MockType: """ Create a spy of method. It will run method normally, but it is now possible to use `mock` call features with it, like call count. :param obj: An object. :param name: A method in object. :return: Spy object. "...
Create a spy of method. It will run method normally, but it is now possible to use `mock` call features with it, like call count. :param obj: An object. :param name: A method in object. :return: Spy object.
spy
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def stub(self, name: Optional[str] = None) -> unittest.mock.MagicMock: """ Create a stub method. It accepts any arguments. Ideal to register to callbacks in tests. :param name: the constructed stub's name as used in repr :return: Stub object. """ return cast( ...
Create a stub method. It accepts any arguments. Ideal to register to callbacks in tests. :param name: the constructed stub's name as used in repr :return: Stub object.
stub
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def async_stub(self, name: Optional[str] = None) -> AsyncMockType: """ Create a async stub method. It accepts any arguments. Ideal to register to callbacks in tests. :param name: the constructed stub's name as used in repr :return: Stub object. """ return cast( ...
Create a async stub method. It accepts any arguments. Ideal to register to callbacks in tests. :param name: the constructed stub's name as used in repr :return: Stub object.
async_stub
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def _start_patch( self, mock_func: Any, warn_on_mock_enter: bool, *args: Any, **kwargs: Any ) -> MockType: """Patches something by calling the given function from the mock module, registering the patch to stop it later and returns the mock object resulting from th...
Patches something by calling the given function from the mock module, registering the patch to stop it later and returns the mock object resulting from the mock call.
_start_patch
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def context_manager( self, target: builtins.object, attribute: str, new: builtins.object = DEFAULT, spec: Optional[builtins.object] = None, create: bool = False, spec_set: Optional[builtins.object] = None, autospec: Optional...
This is equivalent to mock.patch.object except that the returned mock does not issue a warning when used as a context manager.
context_manager
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def _mocker(pytestconfig: Any) -> Generator[MockerFixture, None, None]: """ Return an object that has the same interface to the `mock` module, but takes care of automatically undoing all patches after each test method. """ result = MockerFixture(pytestconfig) yield result result.stopall()
Return an object that has the same interface to the `mock` module, but takes care of automatically undoing all patches after each test method.
_mocker
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def wrap_assert_methods(config: Any) -> None: """ Wrap assert methods of mock module so we can hide their traceback and add introspection information to specified argument asserts. """ # Make sure we only do this once if _mock_module_originals: return mock_module = get_mock_module(c...
Wrap assert methods of mock module so we can hide their traceback and add introspection information to specified argument asserts.
wrap_assert_methods
python
pytest-dev/pytest-mock
src/pytest_mock/plugin.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/plugin.py
MIT
def get_mock_module(config): """ Import and return the actual "mock" module. By default this is "unittest.mock", but the user can force to always use "mock" using the mock_use_standalone_module ini option. """ global _mock_module if _mock_module is None: use_standalone_module = parse...
Import and return the actual "mock" module. By default this is "unittest.mock", but the user can force to always use "mock" using the mock_use_standalone_module ini option.
get_mock_module
python
pytest-dev/pytest-mock
src/pytest_mock/_util.py
https://github.com/pytest-dev/pytest-mock/blob/master/src/pytest_mock/_util.py
MIT
def needs_assert_rewrite(pytestconfig): """ Fixture which skips requesting test if assertion rewrite is disabled (#102) Making this a fixture to avoid accessing pytest's config in the global context. """ option = pytestconfig.getoption("assertmode") if option != "rewrite": pytest.skip( ...
Fixture which skips requesting test if assertion rewrite is disabled (#102) Making this a fixture to avoid accessing pytest's config in the global context.
needs_assert_rewrite
python
pytest-dev/pytest-mock
tests/test_pytest_mock.py
https://github.com/pytest-dev/pytest-mock/blob/master/tests/test_pytest_mock.py
MIT